answer
stringlengths
17
10.2M
package com.samourai.wallet.api; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.net.Uri; import android.os.Handler; import android.os.Looper; import com.auth0.android.jwt.JWT; import com.samourai.wallet.BuildConfig; import com.samourai.wallet.JSONRPC.JSONRPC; import com.samourai.wallet.JSONRPC.TrustedNodeUtil; import com.samourai.wallet.SamouraiWallet; import com.samourai.wallet.bip47.BIP47Meta; import com.samourai.wallet.bip47.BIP47Util; import com.samourai.wallet.crypto.DecryptionException; import com.samourai.wallet.hd.HD_Address; import com.samourai.wallet.hd.HD_Wallet; import com.samourai.wallet.hd.HD_WalletFactory; import com.samourai.wallet.network.dojo.DojoUtil; import com.samourai.wallet.payload.PayloadUtil; 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.BlockedUTXO; import com.samourai.wallet.send.FeeUtil; import com.samourai.wallet.send.MyTransactionOutPoint; import com.samourai.wallet.send.RBFUtil; import com.samourai.wallet.send.SuggestedFee; import com.samourai.wallet.send.UTXO; import com.samourai.wallet.send.UTXOFactory; import com.samourai.wallet.tor.TorManager; import com.samourai.wallet.util.AddressFactory; import com.samourai.wallet.util.AppUtil; import com.samourai.wallet.util.FormatsUtil; import com.samourai.wallet.util.PrefsUtil; import com.samourai.wallet.util.SentToFromBIP47Util; import com.samourai.wallet.util.UTXOUtil; import com.samourai.wallet.util.WebUtil; import com.samourai.wallet.bip47.rpc.PaymentCode; import com.samourai.wallet.R; import com.samourai.wallet.whirlpool.WhirlpoolMeta; import com.samourai.wallet.util.LogUtil; import org.apache.commons.lang3.StringUtils; import org.bitcoinj.core.Address; import org.bitcoinj.core.AddressFormatException; import org.bitcoinj.core.ECKey; import org.bitcoinj.core.Sha256Hash; import org.bitcoinj.core.TransactionOutPoint; import org.bitcoinj.crypto.MnemonicException; import org.bitcoinj.script.Script; import org.bouncycastle.util.encoders.Base64; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.bouncycastle.util.encoders.Hex; import java.io.IOException; import java.math.BigInteger; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import io.reactivex.subjects.BehaviorSubject; import static com.samourai.wallet.util.LogUtil.debug; import static com.samourai.wallet.util.LogUtil.info; public class APIFactory { private static String APP_TOKEN = null; // API app token private static String ACCESS_TOKEN = null; // API access token private static long ACCESS_TOKEN_REFRESH = 300L; // in seconds private static long xpub_balance = 0L; private static long xpub_postmix_balance = 0L; private static HashMap<String, Long> xpub_amounts = null; private static HashMap<String,List<Tx>> xpub_txs = null; private static HashMap<String,Integer> unspentAccounts = null; private static HashMap<String,Integer> unspentBIP49 = null; private static HashMap<String,Integer> unspentBIP84 = null; private static HashMap<String,Integer> unspentBIP84PostMix = null; private static HashMap<String,String> unspentPaths = null; private static HashMap<String,UTXO> utxos = null; private static HashMap<String,UTXO> utxosPostMix = null; private static JSONObject utxoObj0 = null; private static JSONObject utxoObj1 = null; private static HashMap<String, Long> bip47_amounts = null; public boolean walletInit = false; public BehaviorSubject<Long> walletBalanceObserver = BehaviorSubject.create(); private static long latest_block_height = -1L; private static String latest_block_hash = null; private static APIFactory instance = null; private static Context context = null; private static AlertDialog alertDialog = null; private APIFactory() { walletBalanceObserver.onNext(0L); } public static APIFactory getInstance(Context ctx) { context = ctx; if(instance == null) { xpub_amounts = new HashMap<String, Long>(); xpub_txs = new HashMap<String,List<Tx>>(); xpub_balance = 0L; bip47_amounts = new HashMap<String, Long>(); unspentPaths = new HashMap<String, String>(); unspentAccounts = new HashMap<String, Integer>(); unspentBIP49 = new HashMap<String, Integer>(); unspentBIP84 = new HashMap<String, Integer>(); unspentBIP84PostMix = new HashMap<String, Integer>(); utxos = new HashMap<String, UTXO>(); utxosPostMix = new HashMap<String, UTXO>(); instance = new APIFactory(); } return instance; } public synchronized void reset() { xpub_balance = 0L; xpub_amounts.clear(); bip47_amounts.clear(); xpub_txs.clear(); unspentPaths = new HashMap<String, String>(); unspentAccounts = new HashMap<String, Integer>(); unspentBIP49 = new HashMap<String, Integer>(); unspentBIP84 = new HashMap<String, Integer>(); unspentBIP84PostMix = new HashMap<String, Integer>(); utxos = new HashMap<String, UTXO>(); utxosPostMix = new HashMap<String, UTXO>(); UTXOFactory.getInstance().clear(); } public String getAccessToken() { if(ACCESS_TOKEN == null && APIFactory.getInstance(context).APITokenRequired()) { getToken(true); } return DojoUtil.getInstance(context).getDojoParams() == null ? "" : ACCESS_TOKEN; } public void setAccessToken(String accessToken) { ACCESS_TOKEN = accessToken; } public void setAppToken(String token) { APP_TOKEN = token; } public String getAppToken() { if(APP_TOKEN != null) { return APP_TOKEN; } else { return new String(getXORKey()); } } public byte[] getXORKey() { if(APP_TOKEN != null) { return APP_TOKEN.getBytes(); } if(BuildConfig.XOR_1.length() > 0 && BuildConfig.XOR_2.length() > 0) { byte[] xorSegments0 = Base64.decode(BuildConfig.XOR_1); byte[] xorSegments1 = Base64.decode(BuildConfig.XOR_2); return xor(xorSegments0, xorSegments1); } else { return null; } } private byte[] xor(byte[] b0, byte[] b1) { byte[] ret = new byte[b0.length]; for(int i = 0; i < b0.length; i++){ ret[i] = (byte)(b0[i] ^ b1[i]); } return ret; } public long getAccessTokenRefresh() { return ACCESS_TOKEN_REFRESH; } public boolean stayingAlive() { if(!AppUtil.getInstance(context).isOfflineMode() && APITokenRequired()) { if(APIFactory.getInstance(context).getAccessToken() == null) { APIFactory.getInstance(context).getToken(false); } if(APIFactory.getInstance(context).getAccessToken() != null) { JWT jwt = new JWT(APIFactory.getInstance(context).getAccessToken()); if(jwt != null && jwt.isExpired(APIFactory.getInstance(context).getAccessTokenRefresh())) { if(APIFactory.getInstance(context).getToken(false)) { return true; } else { return false; } } } return false; } else { return true; } } public synchronized boolean APITokenRequired() { return DojoUtil.getInstance(context).getDojoParams() == null ? false : true; } public synchronized boolean getToken(boolean setupDojo) { if(!APITokenRequired()) { return true; } String _url = SamouraiWallet.getInstance().isTestNet() ? WebUtil.SAMOURAI_API2_TESTNET : WebUtil.SAMOURAI_API2; if(DojoUtil.getInstance(context).getDojoParams() != null || setupDojo) { _url = SamouraiWallet.getInstance().isTestNet() ? WebUtil.SAMOURAI_API2_TESTNET_TOR : WebUtil.SAMOURAI_API2_TOR; } debug("APIFactory", "getToken() url:" + _url); JSONObject jsonObject = null; try { String response = null; if(AppUtil.getInstance(context).isOfflineMode()) { return true; } else if(!TorManager.getInstance(context).isRequired()) { // use POST StringBuilder args = new StringBuilder(); args.append("apikey="); args.append(new String(getXORKey())); response = WebUtil.getInstance(context).postURL(_url + "auth/login?", args.toString()); info("APIFactory", "API token response:" + response); } else { HashMap<String,String> args = new HashMap<String,String>(); args.put("apikey", new String(getXORKey())); info("APIFactory", "API key (XOR):" + new String(getXORKey())); info("APIFactory", "API key url:" + _url); response = WebUtil.getInstance(context).tor_postURL(_url + "auth/login", args); info("APIFactory", "API token response:" + response); } try { jsonObject = new JSONObject(response); if(jsonObject != null && jsonObject.has("authorizations")) { JSONObject authObj = jsonObject.getJSONObject("authorizations"); if(authObj.has("access_token")) { info("APIFactory", "setting access token:" + authObj.getString("access_token")); setAccessToken(authObj.getString("access_token")); return true; } } } catch(JSONException je) { je.printStackTrace(); jsonObject = null; return false; } } catch(Exception e) { jsonObject = null; e.printStackTrace(); return false; } return true; } private synchronized JSONObject getXPUB(String[] xpubs, boolean parse) { String _url = WebUtil.getAPIUrl(context); JSONObject jsonObject = null; try { String response = null; if(AppUtil.getInstance(context).isOfflineMode()) { response = PayloadUtil.getInstance(context).deserializeMultiAddr().toString(); } else if(!TorManager.getInstance(context).isRequired()) { // use POST StringBuilder args = new StringBuilder(); args.append("active="); args.append(StringUtils.join(xpubs, URLEncoder.encode("|", "UTF-8"))); info("APIFactory", "XPUB:" + args.toString()); args.append("&at="); args.append(getAccessToken()); response = WebUtil.getInstance(context).postURL(_url + "multiaddr?", args.toString()); info("APIFactory", "XPUB response:" + response); } else { HashMap<String,String> args = new HashMap<String,String>(); args.put("active", StringUtils.join(xpubs, "|")); info("APIFactory", "XPUB:" + args.toString()); args.put("at", getAccessToken()); info("APIFactory", "XPUB access token:" + getAccessToken()); response = WebUtil.getInstance(context).tor_postURL(_url + "multiaddr", args); info("APIFactory", "XPUB response:" + response); } try { jsonObject = new JSONObject(response); if(!parse) { return jsonObject; } xpub_txs.put(xpubs[0], new ArrayList<Tx>()); parseXPUB(jsonObject); xpub_amounts.put(HD_WalletFactory.getInstance(context).get().getAccount(0).xpubstr(), xpub_balance - BlockedUTXO.getInstance().getTotalValueBlocked0()); walletBalanceObserver.onNext( xpub_balance - BlockedUTXO.getInstance().getTotalValueBlocked0()); } catch(JSONException je) { je.printStackTrace(); jsonObject = null; } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } private synchronized JSONObject registerXPUB(String xpub, int purpose, String tag) { String _url = WebUtil.getAPIUrl(context); JSONObject jsonObject = null; try { String response = null; if(!TorManager.getInstance(context).isRequired()) { // use POST StringBuilder args = new StringBuilder(); args.append("xpub="); args.append(xpub); args.append("&type="); if(PrefsUtil.getInstance(context).getValue(PrefsUtil.IS_RESTORE, false) == true) { args.append("restore"); } else { args.append("new"); } if(purpose == 49) { args.append("&segwit="); args.append("bip49"); } else if(purpose == 84) { args.append("&segwit="); args.append("bip84"); } else { ; } info("APIFactory", "XPUB:" + args.toString()); args.append("&at="); args.append(getAccessToken()); response = WebUtil.getInstance(context).postURL(_url + "xpub?", args.toString()); info("APIFactory", "XPUB response:" + response); } else { HashMap<String,String> args = new HashMap<String,String>(); args.put("xpub", xpub); if(PrefsUtil.getInstance(context).getValue(PrefsUtil.IS_RESTORE, false) == true) { args.put("type", "restore"); } else { args.put("type", "new"); } if(purpose == 49) { args.put("segwit", "bip49"); } else if(purpose == 84) { args.put("segwit", "bip84"); } else { ; } info("APIFactory", "XPUB:" + args.toString()); args.put("at", getAccessToken()); response = WebUtil.getInstance(context).tor_postURL(_url + "xpub", args); info("APIFactory", "XPUB response:" + response); } try { jsonObject = new JSONObject(response); info("APIFactory", "XPUB response:" + jsonObject.toString()); if(jsonObject.has("status") && jsonObject.getString("status").equals("ok")) { if(tag != null) { PrefsUtil.getInstance(context).setValue(tag, true); if(tag.equals(PrefsUtil.XPUBPOSTREG)) { PrefsUtil.getInstance(context).removeValue(PrefsUtil.IS_RESTORE); } } else if(purpose == 44) { PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB44REG, true); } else if(purpose == 49) { PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB49REG, true); } else if(purpose == 84) { PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB84REG, true); } else { ; } } } catch(JSONException je) { je.printStackTrace(); jsonObject = null; } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } private synchronized boolean parseXPUB(JSONObject jsonObject) throws JSONException { if(jsonObject != null) { HashMap<String,Integer> pubkeys = new HashMap<String,Integer>(); if(jsonObject.has("wallet")) { JSONObject walletObj = (JSONObject)jsonObject.get("wallet"); if(walletObj.has("final_balance")) { xpub_balance = walletObj.getLong("final_balance"); debug("APIFactory", "xpub_balance:" + xpub_balance); } } if(jsonObject.has("info")) { JSONObject infoObj = (JSONObject)jsonObject.get("info"); if(infoObj.has("latest_block")) { JSONObject blockObj = (JSONObject)infoObj.get("latest_block"); if(blockObj.has("height")) { latest_block_height = blockObj.getLong("height"); } if(blockObj.has("hash")) { latest_block_hash = blockObj.getString("hash"); } } } if(jsonObject.has("addresses")) { JSONArray addressesArray = (JSONArray)jsonObject.get("addresses"); JSONObject addrObj = null; for(int i = 0; i < addressesArray.length(); i++) { addrObj = (JSONObject)addressesArray.get(i); if(addrObj != null && addrObj.has("final_balance") && addrObj.has("address")) { if(FormatsUtil.getInstance().isValidXpub((String)addrObj.get("address"))) { xpub_amounts.put((String)addrObj.get("address"), addrObj.getLong("final_balance")); if(addrObj.getString("address").equals(BIP84Util.getInstance(context).getWallet().getAccount(0).xpubstr()) || addrObj.getString("address").equals(BIP84Util.getInstance(context).getWallet().getAccount(0).zpubstr())) { AddressFactory.getInstance().setHighestBIP84ReceiveIdx(addrObj.has("account_index") ? addrObj.getInt("account_index") : 0); AddressFactory.getInstance().setHighestBIP84ChangeIdx(addrObj.has("change_index") ? addrObj.getInt("change_index") : 0); BIP84Util.getInstance(context).getWallet().getAccount(0).getChain(0).setAddrIdx(addrObj.has("account_index") ? addrObj.getInt("account_index") : 0); BIP84Util.getInstance(context).getWallet().getAccount(0).getChain(1).setAddrIdx(addrObj.has("change_index") ? addrObj.getInt("change_index") : 0); } else if(addrObj.getString("address").equals(BIP49Util.getInstance(context).getWallet().getAccount(0).xpubstr()) || addrObj.getString("address").equals(BIP49Util.getInstance(context).getWallet().getAccount(0).ypubstr())) { AddressFactory.getInstance().setHighestBIP49ReceiveIdx(addrObj.has("account_index") ? addrObj.getInt("account_index") : 0); AddressFactory.getInstance().setHighestBIP49ChangeIdx(addrObj.has("change_index") ? addrObj.getInt("change_index") : 0); BIP49Util.getInstance(context).getWallet().getAccount(0).getChain(0).setAddrIdx(addrObj.has("account_index") ? addrObj.getInt("account_index") : 0); BIP49Util.getInstance(context).getWallet().getAccount(0).getChain(1).setAddrIdx(addrObj.has("change_index") ? addrObj.getInt("change_index") : 0); } else if(AddressFactory.getInstance().xpub2account().get((String) addrObj.get("address")) != null) { AddressFactory.getInstance().setHighestTxReceiveIdx(AddressFactory.getInstance().xpub2account().get((String) addrObj.get("address")), addrObj.has("account_index") ? addrObj.getInt("account_index") : 0); AddressFactory.getInstance().setHighestTxChangeIdx(AddressFactory.getInstance().xpub2account().get((String)addrObj.get("address")), addrObj.has("change_index") ? addrObj.getInt("change_index") : 0); try { HD_WalletFactory.getInstance(context).get().getAccount(0).getChain(0).setAddrIdx(addrObj.has("account_index") ? addrObj.getInt("account_index") : 0); HD_WalletFactory.getInstance(context).get().getAccount(0).getChain(1).setAddrIdx(addrObj.has("change_index") ? addrObj.getInt("change_index") : 0); } catch(IOException | MnemonicException.MnemonicLengthException e) { ; } } else { ; } } else { long amount = 0L; String addr = null; addr = (String)addrObj.get("address"); amount = addrObj.getLong("final_balance"); String pcode = BIP47Meta.getInstance().getPCode4Addr(addr); if(addr != null && addr.length() > 0 && pcode != null && pcode.length() > 0 && BIP47Meta.getInstance().getIdx4Addr(addr) != null) { int idx = BIP47Meta.getInstance().getIdx4Addr(addr); if(amount > 0L) { BIP47Meta.getInstance().addUnspent(pcode, idx); if(idx > BIP47Meta.getInstance().getIncomingIdx(pcode)) { BIP47Meta.getInstance().setIncomingIdx(pcode, idx); } } else { if(addrObj.has("pubkey")) { String pubkey = addrObj.getString("pubkey"); if(pubkeys.containsKey(pubkey)) { int count = pubkeys.get(pubkey); count++; if(count == 3) { BIP47Meta.getInstance().removeUnspent(pcode, Integer.valueOf(idx)); } else { pubkeys.put(pubkey, count + 1); } } else { pubkeys.put(pubkey, 1); } } else { BIP47Meta.getInstance().removeUnspent(pcode, Integer.valueOf(idx)); } } if(addr != null) { bip47_amounts.put(addr, amount); } } } } } } if(jsonObject.has("txs")) { List<String> seenHashes = new ArrayList<String>(); JSONArray txArray = (JSONArray)jsonObject.get("txs"); JSONObject txObj = null; for(int i = 0; i < txArray.length(); i++) { txObj = (JSONObject)txArray.get(i); long height = 0L; long amount = 0L; long ts = 0L; String hash = null; String addr = null; String _addr = null; if(txObj.has("block_height")) { height = txObj.getLong("block_height"); } else { height = -1L; // 0 confirmations } if(txObj.has("hash")) { hash = (String)txObj.get("hash"); } if(txObj.has("result")) { amount = txObj.getLong("result"); } if(txObj.has("time")) { ts = txObj.getLong("time"); } if(!seenHashes.contains(hash)) { seenHashes.add(hash); } if(txObj.has("inputs")) { JSONArray inputArray = (JSONArray)txObj.get("inputs"); JSONObject inputObj = null; for(int j = 0; j < inputArray.length(); j++) { inputObj = (JSONObject)inputArray.get(j); if(inputObj.has("prev_out")) { JSONObject prevOutObj = (JSONObject)inputObj.get("prev_out"); if(prevOutObj.has("xpub")) { JSONObject xpubObj = (JSONObject)prevOutObj.get("xpub"); addr = (String)xpubObj.get("m"); } else if(prevOutObj.has("addr") && BIP47Meta.getInstance().getPCode4Addr((String)prevOutObj.get("addr")) != null) { _addr = (String)prevOutObj.get("addr"); } else { _addr = (String)prevOutObj.get("addr"); } } } } if(txObj.has("out")) { JSONArray outArray = (JSONArray)txObj.get("out"); JSONObject outObj = null; for(int j = 0; j < outArray.length(); j++) { outObj = (JSONObject)outArray.get(j); if(outObj.has("xpub")) { JSONObject xpubObj = (JSONObject)outObj.get("xpub"); addr = (String)xpubObj.get("m"); } else { _addr = (String)outObj.get("addr"); } } } if(addr != null || _addr != null) { if(addr == null) { addr = _addr; } Tx tx = new Tx(hash, addr, amount, ts, (latest_block_height > 0L && height > 0L) ? (latest_block_height - height) + 1 : 0); if(SentToFromBIP47Util.getInstance().getByHash(hash) != null) { tx.setPaymentCode(SentToFromBIP47Util.getInstance().getByHash(hash)); } if(BIP47Meta.getInstance().getPCode4Addr(addr) != null) { tx.setPaymentCode(BIP47Meta.getInstance().getPCode4Addr(addr)); } if(!xpub_txs.containsKey(addr)) { xpub_txs.put(addr, new ArrayList<Tx>()); } if(FormatsUtil.getInstance().isValidXpub(addr)) { xpub_txs.get(addr).add(tx); } else { xpub_txs.get(AddressFactory.getInstance().account2xpub().get(0)).add(tx); } if(height > 0L) { RBFUtil.getInstance().remove(hash); } } } List<String> hashesSentToViaBIP47 = SentToFromBIP47Util.getInstance().getAllHashes(); if(hashesSentToViaBIP47.size() > 0) { for(String s : hashesSentToViaBIP47) { if(!seenHashes.contains(s)) { SentToFromBIP47Util.getInstance().removeHash(s); } } } } try { PayloadUtil.getInstance(context).serializeMultiAddr(jsonObject); } catch(IOException | DecryptionException e) { ; } return true; } return false; } /* public synchronized JSONObject deleteXPUB(String xpub, boolean bip49) { String _url = SamouraiWallet.getInstance().isTestNet() ? WebUtil.SAMOURAI_API2_TESTNET : WebUtil.SAMOURAI_API2; JSONObject jsonObject = null; try { String response = null; ECKey ecKey = null; if(AddressFactory.getInstance(context).xpub2account().get(xpub) != null || xpub.equals(BIP49Util.getInstance(context).getWallet().getAccount(0).ypubstr())) { HD_Address addr = null; if(bip49) { addr = BIP49Util.getInstance(context).getWallet().getAccountAt(0).getChange().getAddressAt(0); } else { addr = HD_WalletFactory.getInstance(context).get().getAccount(0).getChain(AddressFactory.CHANGE_CHAIN).getAddressAt(0); } ecKey = addr.getECKey(); if(ecKey != null && ecKey.hasPrivKey()) { String sig = ecKey.signMessage(xpub); String address = null; if(bip49) { SegwitAddress segwitAddress = new SegwitAddress(ecKey.getPubKey(), SamouraiWallet.getInstance().getCurrentNetworkParams()); address = segwitAddress.getAddressAsString(); } else { address = ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(); } if(!TorUtil.getInstance(context).statusFromBroadcast()) { StringBuilder args = new StringBuilder(); args.append("message="); args.append(xpub); args.append("address="); args.append(address); args.append("&signature="); args.append(Uri.encode(sig)); info("APIFactory", "delete XPUB:" + args.toString()); response = WebUtil.getInstance(context).deleteURL(_url + "delete/" + xpub, args.toString()); info("APIFactory", "delete XPUB response:" + response); } else { HashMap<String,String> args = new HashMap<String,String>(); args.put("message", xpub); args.put("address", address); args.put("signature", Uri.encode(sig)); info("APIFactory", "delete XPUB:" + args.toString()); response = WebUtil.getInstance(context).tor_deleteURL(_url + "delete", args); info("APIFactory", "delete XPUB response:" + response); } try { jsonObject = new JSONObject(response); if(jsonObject.has("status") && jsonObject.getString("status").equals("ok")) { ; } } catch(JSONException je) { je.printStackTrace(); jsonObject = null; } } } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } */ public synchronized JSONObject lockXPUB(String xpub, int purpose, String tag) { String _url = WebUtil.getAPIUrl(context); JSONObject jsonObject = null; try { String response = null; ECKey ecKey = null; if(AddressFactory.getInstance(context).xpub2account().get(xpub) != null || xpub.equals(BIP49Util.getInstance(context).getWallet().getAccount(0).ypubstr()) || xpub.equals(BIP84Util.getInstance(context).getWallet().getAccount(0).zpubstr()) || xpub.equals(BIP84Util.getInstance(context).getWallet().getAccountAt(WhirlpoolMeta.getInstance(context).getWhirlpoolPremixAccount()).zpubstr()) || xpub.equals(BIP84Util.getInstance(context).getWallet().getAccountAt(WhirlpoolMeta.getInstance(context).getWhirlpoolPostmix()).zpubstr()) ) { HD_Address addr = null; switch(purpose) { case 49: addr = BIP49Util.getInstance(context).getWallet().getAccountAt(0).getChange().getAddressAt(0); break; case 84: if(tag != null && tag.equals(PrefsUtil.XPUBPRELOCK)) { addr = BIP84Util.getInstance(context).getWallet().getAccountAt(WhirlpoolMeta.getInstance(context).getWhirlpoolPremixAccount()).getChange().getAddressAt(0); } else if(tag != null && tag.equals(PrefsUtil.XPUBPOSTLOCK)) { addr = BIP84Util.getInstance(context).getWallet().getAccountAt(WhirlpoolMeta.getInstance(context).getWhirlpoolPostmix()).getChange().getAddressAt(0); } else { addr = BIP84Util.getInstance(context).getWallet().getAccountAt(0).getChange().getAddressAt(0); } break; default: addr = HD_WalletFactory.getInstance(context).get().getAccount(0).getChain(AddressFactory.CHANGE_CHAIN).getAddressAt(0); break; } ecKey = addr.getECKey(); if(ecKey != null && ecKey.hasPrivKey()) { String sig = ecKey.signMessage("lock"); String address = null; switch(purpose) { case 49: SegwitAddress p2shp2wpkh = new SegwitAddress(ecKey.getPubKey(), SamouraiWallet.getInstance().getCurrentNetworkParams()); address = p2shp2wpkh.getAddressAsString(); break; case 84: SegwitAddress segwitAddress = new SegwitAddress(ecKey.getPubKey(), SamouraiWallet.getInstance().getCurrentNetworkParams()); address = segwitAddress.getBech32AsString(); break; default: address = ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(); break; } if(!TorManager.getInstance(context).isRequired()) { StringBuilder args = new StringBuilder(); args.append("address="); args.append(address); args.append("&signature="); args.append(Uri.encode(sig)); args.append("&message="); args.append("lock"); // info("APIFactory", "lock XPUB:" + args.toString()); args.append("&at="); args.append(getAccessToken()); response = WebUtil.getInstance(context).postURL(_url + "xpub/" + xpub + "/lock/", args.toString()); // info("APIFactory", "lock XPUB response:" + response); } else { HashMap<String,String> args = new HashMap<String,String>(); args.put("address", address); // args.put("signature", Uri.encode(sig)); args.put("signature", sig); args.put("message", "lock"); args.put("at", getAccessToken()); info("APIFactory", "lock XPUB:" + _url); info("APIFactory", "lock XPUB:" + args.toString()); response = WebUtil.getInstance(context).tor_postURL(_url + "xpub/" + xpub + "/lock/", args); info("APIFactory", "lock XPUB response:" + response); } try { jsonObject = new JSONObject(response); if(jsonObject.has("status") && jsonObject.getString("status").equals("ok")) { if(tag != null) { PrefsUtil.getInstance(context).setValue(tag, true); } else { switch(purpose) { case 49: PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB49LOCK, true); break; case 84: PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB84LOCK, true); break; default: PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB44LOCK, true); break; } } } } catch(JSONException je) { je.printStackTrace(); jsonObject = null; } } } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } public long getLatestBlockHeight() { return latest_block_height; } public String getLatestBlockHash() { return latest_block_hash; } public JSONObject getNotifTx(String hash, String addr) { String _url = WebUtil.getAPIUrl(context); JSONObject jsonObject = null; try { StringBuilder url = new StringBuilder(_url); url.append("tx/"); url.append(hash); url.append("?fees=1"); // info("APIFactory", "Notif tx:" + url.toString()); url.append("&at="); url.append(getAccessToken()); String response = WebUtil.getInstance(null).getURL(url.toString()); // info("APIFactory", "Notif tx:" + response); try { jsonObject = new JSONObject(response); parseNotifTx(jsonObject, addr, hash); } catch(JSONException je) { je.printStackTrace(); jsonObject = null; } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } public JSONObject getNotifAddress(String addr) { String _url = SamouraiWallet.getInstance().isTestNet() ? WebUtil.SAMOURAI_API2_TESTNET : WebUtil.SAMOURAI_API2; JSONObject jsonObject = null; try { StringBuilder url = new StringBuilder(_url); url.append("multiaddr?active="); url.append(addr); // info("APIFactory", "Notif address:" + url.toString()); url.append("&at="); url.append(getAccessToken()); String response = WebUtil.getInstance(null).getURL(url.toString()); // info("APIFactory", "Notif address:" + response); try { jsonObject = new JSONObject(response); parseNotifAddress(jsonObject, addr); } catch(JSONException je) { je.printStackTrace(); jsonObject = null; } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } public void parseNotifAddress(JSONObject jsonObject, String addr) throws JSONException { if(jsonObject != null && jsonObject.has("txs")) { JSONArray txArray = jsonObject.getJSONArray("txs"); JSONObject txObj = null; for(int i = 0; i < txArray.length(); i++) { txObj = (JSONObject)txArray.get(i); if(!txObj.has("block_height") || (txObj.has("block_height") && txObj.getLong("block_height") < 1L)) { return; } String hash = null; if(txObj.has("hash")) { hash = (String)txObj.get("hash"); if(BIP47Meta.getInstance().getIncomingStatus(hash) == null) { getNotifTx(hash, addr); } } } } } public void parseNotifTx(JSONObject jsonObject, String addr, String hash) throws JSONException { info("APIFactory", "notif address:" + addr); info("APIFactory", "hash:" + hash); if(jsonObject != null) { byte[] mask = null; byte[] payload = null; PaymentCode pcode = null; if(jsonObject.has("inputs")) { JSONArray inArray = (JSONArray)jsonObject.get("inputs"); if(inArray.length() > 0) { JSONObject objInput = (JSONObject)inArray.get(0); byte[] pubkey = null; String strScript = objInput.getString("sig"); info("APIFactory", "scriptsig:" + strScript); if((strScript == null || strScript.length() == 0 || strScript.startsWith("160014")) && objInput.has("witness")) { JSONArray witnessArray = (JSONArray)objInput.get("witness"); if(witnessArray.length() == 2) { pubkey = Hex.decode((String)witnessArray.get(1)); } } else { Script script = new Script(Hex.decode(strScript)); info("APIFactory", "pubkey from script:" + Hex.toHexString(script.getPubKey())); pubkey = script.getPubKey(); } ECKey pKey = new ECKey(null, pubkey, true); info("APIFactory", "address from script:" + pKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString()); // info("APIFactory", "uncompressed public key from script:" + Hex.toHexString(pKey.decompress().getPubKey())); if(((JSONObject)inArray.get(0)).has("outpoint")) { JSONObject received_from = ((JSONObject) inArray.get(0)).getJSONObject("outpoint"); String strHash = received_from.getString("txid"); int idx = received_from.getInt("vout"); byte[] hashBytes = Hex.decode(strHash); Sha256Hash txHash = new Sha256Hash(hashBytes); TransactionOutPoint outPoint = new TransactionOutPoint(SamouraiWallet.getInstance().getCurrentNetworkParams(), idx, txHash); byte[] outpoint = outPoint.bitcoinSerialize(); info("APIFactory", "outpoint:" + Hex.toHexString(outpoint)); try { mask = BIP47Util.getInstance(context).getIncomingMask(pubkey, outpoint); info("APIFactory", "mask:" + Hex.toHexString(mask)); } catch(Exception e) { e.printStackTrace(); } } } } if(jsonObject.has("outputs")) { JSONArray outArray = (JSONArray)jsonObject.get("outputs"); JSONObject outObj = null; boolean isIncoming = false; String _addr = null; String script = null; String op_return = null; for(int j = 0; j < outArray.length(); j++) { outObj = (JSONObject)outArray.get(j); if(outObj.has("address")) { _addr = outObj.getString("address"); if(addr.equals(_addr)) { isIncoming = true; } } if(outObj.has("scriptpubkey")) { script = outObj.getString("scriptpubkey"); if(script.startsWith("6a4c50")) { op_return = script; } } } if(isIncoming && op_return != null && op_return.startsWith("6a4c50")) { payload = Hex.decode(op_return.substring(6)); } } if(mask != null && payload != null) { try { byte[] xlat_payload = PaymentCode.blind(payload, mask); info("APIFactory", "xlat_payload:" + Hex.toHexString(xlat_payload)); pcode = new PaymentCode(xlat_payload); info("APIFactory", "incoming payment code:" + pcode.toString()); if(!pcode.toString().equals(BIP47Util.getInstance(context).getPaymentCode().toString()) && pcode.isValid() && !BIP47Meta.getInstance().incomingExists(pcode.toString())) { BIP47Meta.getInstance().setLabel(pcode.toString(), ""); BIP47Meta.getInstance().setIncomingStatus(hash); } } catch(AddressFormatException afe) { afe.printStackTrace(); } } // get receiving addresses for spends from decoded payment code if(pcode != null) { try { // initial lookup for(int i = 0; i < BIP47Meta.INCOMING_LOOKAHEAD; i++) { info("APIFactory", "receive from " + i + ":" + BIP47Util.getInstance(context).getReceivePubKey(pcode, i)); BIP47Meta.getInstance().getIdx4AddrLookup().put(BIP47Util.getInstance(context).getReceivePubKey(pcode, i), i); BIP47Meta.getInstance().getPCode4AddrLookup().put(BIP47Util.getInstance(context).getReceivePubKey(pcode, i), pcode.toString()); } } catch(Exception e) { ; } } } } public synchronized int getNotifTxConfirmations(String hash) { String _url = WebUtil.getAPIUrl(context); // info("APIFactory", "Notif tx:" + hash); JSONObject jsonObject = null; try { StringBuilder url = new StringBuilder(_url); url.append("tx/"); url.append(hash); url.append("?fees=1"); // info("APIFactory", "Notif tx:" + url.toString()); url.append("&at="); url.append(getAccessToken()); String response = WebUtil.getInstance(null).getURL(url.toString()); // info("APIFactory", "Notif tx:" + response); jsonObject = new JSONObject(response); // info("APIFactory", "Notif tx json:" + jsonObject.toString()); return parseNotifTx(jsonObject); } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return 0; } public synchronized int parseNotifTx(JSONObject jsonObject) throws JSONException { int cf = 0; if(jsonObject != null && jsonObject.has("block") && jsonObject.getJSONObject("block").has("height")) { long latestBlockHeght = getLatestBlockHeight(); long height = jsonObject.getJSONObject("block").getLong("height"); cf = (int)((latestBlockHeght - height) + 1); if(cf < 0) { cf = 0; } } return cf; } public synchronized JSONObject getUnspentOutputs(String[] xpubs) { String _url = WebUtil.getAPIUrl(context); JSONObject jsonObject = null; String response = null; try { if(AppUtil.getInstance(context).isOfflineMode()) { response = PayloadUtil.getInstance(context).deserializeUTXO().toString(); } else if(!TorManager.getInstance(context).isRequired()) { StringBuilder args = new StringBuilder(); args.append("active="); args.append(StringUtils.join(xpubs, URLEncoder.encode("|", "UTF-8"))); debug("APIFactory", "UTXO args:" + args.toString()); args.append("&at="); args.append(getAccessToken()); response = WebUtil.getInstance(context).postURL(_url + "unspent?", args.toString()); debug("APIFactory", "UTXO:" + response); } else { HashMap<String,String> args = new HashMap<String,String>(); args.put("active", StringUtils.join(xpubs, "|")); args.put("at", getAccessToken()); response = WebUtil.getInstance(context).tor_postURL(_url + "unspent", args); } parseUnspentOutputs(response); } catch(Exception e) { jsonObject = null; e.printStackTrace(); } if(!AppUtil.getInstance(context).isOfflineMode()) { try { jsonObject = new JSONObject(response); } catch(JSONException je) { ; } } return jsonObject; } private synchronized boolean parseUnspentOutputs(String unspents) { if(unspents != null) { try { JSONObject jsonObj = new JSONObject(unspents); if(jsonObj == null || !jsonObj.has("unspent_outputs")) { return false; } JSONArray utxoArray = jsonObj.getJSONArray("unspent_outputs"); if(utxoArray == null || utxoArray.length() == 0) { return false; } utxos.clear(); for (int i = 0; i < utxoArray.length(); i++) { JSONObject outDict = utxoArray.getJSONObject(i); byte[] hashBytes = Hex.decode((String)outDict.get("tx_hash")); Sha256Hash txHash = Sha256Hash.wrap(hashBytes); int txOutputN = ((Number)outDict.get("tx_output_n")).intValue(); BigInteger value = BigInteger.valueOf(((Number)outDict.get("value")).longValue()); String script = (String)outDict.get("script"); byte[] scriptBytes = Hex.decode(script); int confirmations = ((Number)outDict.get("confirmations")).intValue(); String path = null; try { String address = null; if(Bech32Util.getInstance().isBech32Script(script)) { address = Bech32Util.getInstance().getAddressFromScript(script); } else { address = new Script(scriptBytes).getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(); } if(outDict.has("xpub")) { JSONObject xpubObj = (JSONObject)outDict.get("xpub"); path = (String)xpubObj.get("path"); String m = (String)xpubObj.get("m"); unspentPaths.put(address, path); if(m.equals(BIP49Util.getInstance(context).getWallet().getAccount(0).xpubstr())) { unspentBIP49.put(address, 0); // assume account 0 } else if(m.equals(BIP84Util.getInstance(context).getWallet().getAccount(0).xpubstr())) { unspentBIP84.put(address, 0); // assume account 0 } else { unspentAccounts.put(address, AddressFactory.getInstance(context).xpub2account().get(m)); } } else if(outDict.has("pubkey")) { int idx = BIP47Meta.getInstance().getIdx4AddrLookup().get(outDict.getString("pubkey")); BIP47Meta.getInstance().getIdx4AddrLookup().put(address, idx); String pcode = BIP47Meta.getInstance().getPCode4AddrLookup().get(outDict.getString("pubkey")); BIP47Meta.getInstance().getPCode4AddrLookup().put(address, pcode); } else { ; } // Construct the output MyTransactionOutPoint outPoint = new MyTransactionOutPoint(txHash, txOutputN, value, scriptBytes, address); outPoint.setConfirmations(confirmations); if(utxos.containsKey(script)) { utxos.get(script).getOutpoints().add(outPoint); } else { UTXO utxo = new UTXO(); utxo.getOutpoints().add(outPoint); utxo.setPath(path); utxos.put(script, utxo); } if(!BlockedUTXO.getInstance().contains(txHash.toString(), txOutputN)) { if(Bech32Util.getInstance().isBech32Script(script)) { UTXOFactory.getInstance().addP2WPKH(script, utxos.get(script)); } else if(Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), address).isP2SHAddress()) { UTXOFactory.getInstance().addP2SH_P2WPKH(script, utxos.get(script)); } else { UTXOFactory.getInstance().addP2PKH(script, utxos.get(script)); } } } catch(Exception e) { ; } } return true; } catch(JSONException je) { ; } } return false; } public synchronized JSONObject getAddressInfo(String addr) { return getXPUB(new String[] { addr }, false); } public synchronized JSONObject getTxInfo(String hash) { String _url = WebUtil.getAPIUrl(context); JSONObject jsonObject = null; try { StringBuilder url = new StringBuilder(_url); url.append("tx/"); url.append(hash); url.append("?fees=true"); url.append("&at="); url.append(getAccessToken()); String response = WebUtil.getInstance(context).getURL(url.toString()); jsonObject = new JSONObject(response); } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } public synchronized JSONObject getBlockHeader(String hash) { String _url = WebUtil.getAPIUrl(context); JSONObject jsonObject = null; try { StringBuilder url = new StringBuilder(_url); url.append("header/"); url.append(hash); url.append("?at="); url.append(getAccessToken()); String response = WebUtil.getInstance(context).getURL(url.toString()); jsonObject = new JSONObject(response); } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } public synchronized JSONObject getDynamicFees() { JSONObject jsonObject = null; try { int sel = PrefsUtil.getInstance(context).getValue(PrefsUtil.FEE_PROVIDER_SEL, 0); if(sel == 1) { int[] blocks = new int[] { 2, 6, 24 }; List<SuggestedFee> suggestedFees = new ArrayList<SuggestedFee>(); JSONRPC jsonrpc = new JSONRPC(TrustedNodeUtil.getInstance().getUser(), TrustedNodeUtil.getInstance().getPassword(), TrustedNodeUtil.getInstance().getNode(), TrustedNodeUtil.getInstance().getPort()); for(int i = 0; i < blocks.length; i++) { JSONObject feeObj = jsonrpc.getFeeEstimate(blocks[i]); if(feeObj != null && feeObj.has("result")) { double fee = feeObj.getDouble("result"); SuggestedFee suggestedFee = new SuggestedFee(); suggestedFee.setDefaultPerKB(BigInteger.valueOf((long)(fee * 1e8))); suggestedFee.setStressed(false); suggestedFee.setOK(true); suggestedFees.add(suggestedFee); } } if(suggestedFees.size() > 0) { FeeUtil.getInstance().setEstimatedFees(suggestedFees); } } else { String _url = WebUtil.getAPIUrl(context); // info("APIFactory", "Dynamic fees:" + url.toString()); String response = null; if(!AppUtil.getInstance(context).isOfflineMode()) { response = WebUtil.getInstance(null).getURL(_url + "fees" + "?at=" + getAccessToken()); } else { response = PayloadUtil.getInstance(context).deserializeFees().toString(); } // info("APIFactory", "Dynamic fees response:" + response); try { jsonObject = new JSONObject(response); parseDynamicFees_bitcoind(jsonObject); } catch(JSONException je) { je.printStackTrace(); jsonObject = null; } } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } private synchronized boolean parseDynamicFees_bitcoind(JSONObject jsonObject) throws JSONException { if(jsonObject != null) { // bitcoind List<SuggestedFee> suggestedFees = new ArrayList<SuggestedFee>(); if(jsonObject.has("2")) { long fee = jsonObject.getInt("2"); SuggestedFee suggestedFee = new SuggestedFee(); suggestedFee.setDefaultPerKB(BigInteger.valueOf(fee * 1000L)); suggestedFee.setStressed(false); suggestedFee.setOK(true); suggestedFees.add(suggestedFee); } if(jsonObject.has("6")) { long fee = jsonObject.getInt("6"); SuggestedFee suggestedFee = new SuggestedFee(); suggestedFee.setDefaultPerKB(BigInteger.valueOf(fee * 1000L)); suggestedFee.setStressed(false); suggestedFee.setOK(true); suggestedFees.add(suggestedFee); } if(jsonObject.has("24")) { long fee = jsonObject.getInt("24"); SuggestedFee suggestedFee = new SuggestedFee(); suggestedFee.setDefaultPerKB(BigInteger.valueOf(fee * 1000L)); suggestedFee.setStressed(false); suggestedFee.setOK(true); suggestedFees.add(suggestedFee); } if(suggestedFees.size() > 0) { FeeUtil.getInstance().setEstimatedFees(suggestedFees); // debug("APIFactory", "high fee:" + FeeUtil.getInstance().getHighFee().getDefaultPerKB().toString()); // debug("APIFactory", "suggested fee:" + FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().toString()); // debug("APIFactory", "low fee:" + FeeUtil.getInstance().getLowFee().getDefaultPerKB().toString()); } try { PayloadUtil.getInstance(context).serializeFees(jsonObject); } catch(IOException | DecryptionException e) { ; } return true; } return false; } public synchronized void validateAPIThread() { final Handler handler = new Handler(); new Thread(new Runnable() { @Override public void run() { Looper.prepare(); if(!AppUtil.getInstance(context).isOfflineMode()) { try { String response = WebUtil.getInstance(context).getURL(WebUtil.SAMOURAI_API_CHECK); JSONObject jsonObject = new JSONObject(response); if(!jsonObject.has("process")) { showAlertDialog(context.getString(R.string.api_error), false); } } catch(Exception e) { showAlertDialog(context.getString(R.string.cannot_reach_api), false); } } else { showAlertDialog(context.getString(R.string.no_internet), false); } handler.post(new Runnable() { @Override public void run() { ; } }); Looper.loop(); } }).start(); } private void showAlertDialog(final String message, final boolean forceExit){ if (!((Activity) context).isFinishing()) { if(alertDialog != null)alertDialog.dismiss(); final AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setMessage(message); builder.setCancelable(false); if(!forceExit) { builder.setPositiveButton(R.string.retry, new DialogInterface.OnClickListener() { public void onClick(DialogInterface d, int id) { d.dismiss(); //Retry validateAPIThread(); } }); } builder.setNegativeButton(R.string.exit, new DialogInterface.OnClickListener() { public void onClick(DialogInterface d, int id) { d.dismiss(); ((Activity) context).finish(); } }); alertDialog = builder.create(); alertDialog.show(); } } public synchronized void initWallet() { info("APIFactory", "initWallet()"); initWalletAmounts(); } private synchronized void initWalletAmounts() { APIFactory.getInstance(context).reset(); List<String> addressStrings = new ArrayList<String>(); String[] s = null; try { if(PrefsUtil.getInstance(context).getValue(PrefsUtil.XPUB44REG, false) == false) { registerXPUB(HD_WalletFactory.getInstance(context).get().getAccount(0).xpubstr(), 44, null); } if(PrefsUtil.getInstance(context).getValue(PrefsUtil.XPUB49REG, false) == false) { registerXPUB(BIP49Util.getInstance(context).getWallet().getAccount(0).xpubstr(), 49, null); } if(PrefsUtil.getInstance(context).getValue(PrefsUtil.XPUB84REG, false) == false) { registerXPUB(BIP84Util.getInstance(context).getWallet().getAccount(0).xpubstr(), 84, null); } if(PrefsUtil.getInstance(context).getValue(PrefsUtil.XPUBPREREG, false) == false) { registerXPUB(BIP84Util.getInstance(context).getWallet().getAccountAt(WhirlpoolMeta.getInstance(context).getWhirlpoolPremixAccount()).xpubstr(), 84, PrefsUtil.XPUBPREREG); } if(PrefsUtil.getInstance(context).getValue(PrefsUtil.XPUBPOSTREG, false) == false) { registerXPUB(BIP84Util.getInstance(context).getWallet().getAccountAt(WhirlpoolMeta.getInstance(context).getWhirlpoolPostmix()).xpubstr(), 84, PrefsUtil.XPUBPOSTREG); } xpub_txs.put(HD_WalletFactory.getInstance(context).get().getAccount(0).xpubstr(), new ArrayList<Tx>()); addressStrings.addAll(Arrays.asList(BIP47Meta.getInstance().getIncomingAddresses(false))); for(String _s : Arrays.asList(BIP47Meta.getInstance().getIncomingLookAhead(context))) { if(!addressStrings.contains(_s)) { addressStrings.add(_s); } } for(String pcode : BIP47Meta.getInstance().getUnspentProviders()) { for(String addr : BIP47Meta.getInstance().getUnspentAddresses(context, pcode)) { if(!addressStrings.contains(addr)) { addressStrings.add(addr); } } } if(addressStrings.size() > 0) { s = addressStrings.toArray(new String[0]); // info("APIFactory", addressStrings.toString()); utxoObj0 = getUnspentOutputs(s); } debug("APIFactory", "addresses:" + addressStrings.toString()); HD_Wallet hdw = HD_WalletFactory.getInstance(context).get(); if(hdw != null && hdw.getXPUBs() != null) { String[] all = null; if(s != null && s.length > 0) { all = new String[hdw.getXPUBs().length + 2 + s.length]; all[0] = BIP49Util.getInstance(context).getWallet().getAccount(0).xpubstr(); all[1] = BIP84Util.getInstance(context).getWallet().getAccount(0).xpubstr(); System.arraycopy(hdw.getXPUBs(), 0, all, 2, hdw.getXPUBs().length); System.arraycopy(s, 0, all, hdw.getXPUBs().length + 2, s.length); } else { all = new String[hdw.getXPUBs().length + 2]; all[0] = BIP49Util.getInstance(context).getWallet().getAccount(0).xpubstr(); all[1] = BIP84Util.getInstance(context).getWallet().getAccount(0).xpubstr(); System.arraycopy(hdw.getXPUBs(), 0, all, 2, hdw.getXPUBs().length); } APIFactory.getInstance(context).getXPUB(all, true); String[] xs = new String[4]; xs[0] = HD_WalletFactory.getInstance(context).get().getAccount(0).xpubstr(); xs[1] = HD_WalletFactory.getInstance(context).get().getAccount(1).xpubstr(); xs[2] = BIP49Util.getInstance(context).getWallet().getAccount(0).xpubstr(); xs[3] = BIP84Util.getInstance(context).getWallet().getAccount(0).xpubstr(); utxoObj1 = getUnspentOutputs(xs); getDynamicFees(); } try { List<JSONObject> utxoObjs = new ArrayList<JSONObject>(); if(utxoObj0 != null) { utxoObjs.add(utxoObj0); } if(utxoObj1 != null) { utxoObjs.add(utxoObj1); } PayloadUtil.getInstance(context).serializeUTXO(utxoObjs); } catch(IOException | DecryptionException e) { ; } List<String> seenOutputs = new ArrayList<String>(); List<UTXO> _utxos = getUtxos(false); for(UTXO _u : _utxos) { for(MyTransactionOutPoint _o : _u.getOutpoints()) { seenOutputs.add(_o.getTxHash().toString() + "-" + _o.getTxOutputN()); } } for(String _s : UTXOUtil.getInstance().getTags().keySet()) { if(!seenOutputs.contains(_s)) { UTXOUtil.getInstance().remove(_s); } } for(String _s : BlockedUTXO.getInstance().getNotDustedUTXO()) { // debug("APIFactory", "not dusted:" + _s); if(!seenOutputs.contains(_s)) { BlockedUTXO.getInstance().removeNotDusted(_s); // debug("APIFactory", "not dusted removed:" + _s); } } for(String _s : BlockedUTXO.getInstance().getBlockedUTXO().keySet()) { // debug("APIFactory", "blocked:" + _s); if(!seenOutputs.contains(_s)) { BlockedUTXO.getInstance().remove(_s); // debug("APIFactory", "blocked removed:" + _s); } } // String strPreMix = BIP84Util.getInstance(context).getWallet().getAccountAt(WhirlpoolMeta.getInstance(context).getWhirlpoolPremixAccount()).xpubstr(); String strPostMix = BIP84Util.getInstance(context).getWallet().getAccountAt(WhirlpoolMeta.getInstance(context).getWhirlpoolPostmix()).xpubstr(); // JSONObject preMultiAddrObj = getRawXPUB(new String[] { strPreMix }); // JSONObject preUnspentObj = getRawUnspentOutputs(new String[] { strPreMix }); // debug("APIFactory", "pre-mix multi:" + preMultiAddrObj.toString()); // debug("APIFactory", "pre-mix unspent:" + preUnspentObj.toString()); // boolean parsedPreMultiAddr = parseMixXPUB(preMultiAddrObj); // boolean parsedPreUnspent = parsePostMixUnspentOutputs(preUnspentObj.toString()); JSONObject postMultiAddrObj = getRawXPUB(new String[] { strPostMix }); JSONObject postUnspentObj = getRawUnspentOutputs(new String[] { strPostMix }); debug("APIFactory", "post-mix multi:" + postMultiAddrObj.toString()); debug("APIFactory", "post-mix unspent:" + postUnspentObj.toString()); boolean parsedPostMultiAddr = parseMixXPUB(postMultiAddrObj); boolean parsedPostUnspent = parsePostMixUnspentOutputs(postUnspentObj.toString()); // debug("APIFactory", "post-mix multi:" + parsedPostMultiAddr); // debug("APIFactory", "post-mix unspent:" + parsedPostUnspent); // debug("APIFactory", "post-mix multi:" + getXpubPostMixBalance()); // debug("APIFactory", "post-mix unspent:" + getUtxosPostMix().size()); } catch (IndexOutOfBoundsException ioobe) { ioobe.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } walletInit = true; } public synchronized int syncBIP47Incoming(String[] addresses) { JSONObject jsonObject = getXPUB(addresses, false); debug("APIFactory", "sync BIP47 incoming:" + jsonObject.toString()); int ret = 0; try { if(jsonObject != null && jsonObject.has("addresses")) { HashMap<String,Integer> pubkeys = new HashMap<String,Integer>(); JSONArray addressArray = (JSONArray)jsonObject.get("addresses"); JSONObject addrObj = null; for(int i = 0; i < addressArray.length(); i++) { addrObj = (JSONObject)addressArray.get(i); long amount = 0L; int nbTx = 0; String addr = null; String pcode = null; int idx = -1; if(addrObj.has("address")) { if(addrObj.has("pubkey")) { addr = (String)addrObj.get("pubkey"); pcode = BIP47Meta.getInstance().getPCode4Addr(addr); idx = BIP47Meta.getInstance().getIdx4Addr(addr); BIP47Meta.getInstance().getIdx4AddrLookup().put(addrObj.getString("address"), idx); BIP47Meta.getInstance().getPCode4AddrLookup().put(addrObj.getString("address"), pcode); } else { addr = (String)addrObj.get("address"); pcode = BIP47Meta.getInstance().getPCode4Addr(addr); idx = BIP47Meta.getInstance().getIdx4Addr(addr); } if(addrObj.has("final_balance")) { amount = addrObj.getLong("final_balance"); if(amount > 0L) { BIP47Meta.getInstance().addUnspent(pcode, idx); info("APIFactory", "BIP47 incoming amount:" + idx + ", " + addr + ", " + amount); } else { if(addrObj.has("pubkey")) { String pubkey = addrObj.getString("pubkey"); if(pubkeys.containsKey(pubkey)) { int count = pubkeys.get(pubkey); count++; if(count == 3) { BIP47Meta.getInstance().removeUnspent(pcode, Integer.valueOf(idx)); } else { pubkeys.put(pubkey, count + 1); } } else { pubkeys.put(pubkey, 1); } } else { BIP47Meta.getInstance().removeUnspent(pcode, Integer.valueOf(idx)); } } } if(addrObj.has("n_tx")) { nbTx = addrObj.getInt("n_tx"); if(nbTx > 0) { if(idx > BIP47Meta.getInstance().getIncomingIdx(pcode)) { BIP47Meta.getInstance().setIncomingIdx(pcode, idx); } info("APIFactory", "sync receive idx:" + idx + ", " + addr); ret++; } } } } } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return ret; } public synchronized int syncBIP47Outgoing(String[] addresses) { JSONObject jsonObject = getXPUB(addresses, false); int ret = 0; try { if(jsonObject != null && jsonObject.has("addresses")) { JSONArray addressArray = (JSONArray)jsonObject.get("addresses"); JSONObject addrObj = null; for(int i = 0; i < addressArray.length(); i++) { addrObj = (JSONObject)addressArray.get(i); int nbTx = 0; String addr = null; String pcode = null; int idx = -1; info("APIFactory", "address object:" + addrObj.toString()); if(addrObj.has("pubkey")) { addr = (String)addrObj.get("pubkey"); pcode = BIP47Meta.getInstance().getPCode4Addr(addr); idx = BIP47Meta.getInstance().getIdx4Addr(addr); BIP47Meta.getInstance().getIdx4AddrLookup().put(addrObj.getString("address"), idx); BIP47Meta.getInstance().getPCode4AddrLookup().put(addrObj.getString("address"), pcode); } else { addr = (String)addrObj.get("address"); pcode = BIP47Meta.getInstance().getPCode4Addr(addr); idx = BIP47Meta.getInstance().getIdx4Addr(addr); } if(addrObj.has("n_tx")) { nbTx = addrObj.getInt("n_tx"); if(nbTx > 0) { if(idx >= BIP47Meta.getInstance().getOutgoingIdx(pcode)) { info("APIFactory", "sync send idx:" + idx + ", " + addr); BIP47Meta.getInstance().setOutgoingIdx(pcode, idx + 1); } ret++; } } } } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return ret; } public long getXpubBalance() { return xpub_balance - BlockedUTXO.getInstance().getTotalValueBlocked0(); } public void setXpubBalance(long value) { xpub_balance = value; walletBalanceObserver.onNext(value); } public long getXpubPostMixBalance() { return xpub_postmix_balance - BlockedUTXO.getInstance().getTotalValueBlockedPostMix(); } public void setXpubPostMixBalance(long value) { xpub_postmix_balance = value; } public HashMap<String,Long> getXpubAmounts() { return xpub_amounts; } public HashMap<String,List<Tx>> getXpubTxs() { return xpub_txs; } public HashMap<String, String> getUnspentPaths() { return unspentPaths; } public HashMap<String, Integer> getUnspentAccounts() { return unspentAccounts; } public HashMap<String, Integer> getUnspentBIP49() { return unspentBIP49; } public HashMap<String, Integer> getUnspentBIP84() { return unspentBIP84; } public List<UTXO> getUtxos(boolean filter) { List<UTXO> unspents = new ArrayList<UTXO>(); if(filter) { for(String key : utxos.keySet()) { UTXO u = new UTXO(); for(MyTransactionOutPoint out : utxos.get(key).getOutpoints()) { if(!BlockedUTXO.getInstance().contains(out.getTxHash().toString(), out.getTxOutputN())) { u.getOutpoints().add(out); } } if(u.getOutpoints().size() > 0) { unspents.add(u); } } } else { unspents.addAll(utxos.values()); } return unspents; } public List<UTXO> getUtxosWithLocalCache(boolean filter,boolean useLocalCache) { List<UTXO> unspents = new ArrayList<UTXO>(); if(utxos.isEmpty() && useLocalCache){ try { String response = PayloadUtil.getInstance(context).deserializeUTXO().toString(); parseUnspentOutputsForSweep(response); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } if(filter) { for(String key : utxos.keySet()) { UTXO u = new UTXO(); for(MyTransactionOutPoint out : utxos.get(key).getOutpoints()) { if(!BlockedUTXO.getInstance().contains(out.getTxHash().toString(), out.getTxOutputN())) { u.getOutpoints().add(out); } } if(u.getOutpoints().size() > 0) { unspents.add(u); } } } else { unspents.addAll(utxos.values()); } return unspents; } public List<UTXO> getUtxosPostMix(boolean filter) { List<UTXO> unspents = new ArrayList<UTXO>(); if(filter) { for(String key : utxosPostMix.keySet()) { UTXO u = new UTXO(); for(MyTransactionOutPoint out : utxosPostMix.get(key).getOutpoints()) { if(!BlockedUTXO.getInstance().containsPostMix(out.getTxHash().toString(), out.getTxOutputN())) { u.getOutpoints().add(out); } } if(u.getOutpoints().size() > 0) { unspents.add(u); } } } else { unspents.addAll(utxosPostMix.values()); } return unspents; } public void setUtxos(HashMap<String, UTXO> utxos) { APIFactory.utxos = utxos; } public void setUtxosPostMix(HashMap<String, UTXO> utxos) { APIFactory.utxosPostMix = utxos; } public synchronized List<Tx> getAllXpubTxs() { List<Tx> ret = new ArrayList<Tx>(); for(String key : xpub_txs.keySet()) { List<Tx> txs = xpub_txs.get(key); for(Tx tx : txs) { ret.add(tx); } } Collections.sort(ret, new TxMostRecentDateComparator()); return ret; } public synchronized UTXO getUnspentOutputsForSweep(String address) { String _url = WebUtil.getAPIUrl(context); try { String response = null; if(!TorManager.getInstance(context).isRequired()) { StringBuilder args = new StringBuilder(); args.append("active="); args.append(address); args.append("&at="); args.append(getAccessToken()); // debug("APIFactory", args.toString()); response = WebUtil.getInstance(context).postURL(_url + "unspent?", args.toString()); // debug("APIFactory", response); } else { HashMap<String,String> args = new HashMap<String,String>(); args.put("active", address); args.put("at", getAccessToken()); // debug("APIFactory", args.toString()); response = WebUtil.getInstance(context).tor_postURL(_url + "unspent", args); // debug("APIFactory", response); } return parseUnspentOutputsForSweep(response); } catch(Exception e) { e.printStackTrace(); } return null; } private synchronized UTXO parseUnspentOutputsForSweep(String unspents) { UTXO utxo = null; if(unspents != null) { try { JSONObject jsonObj = new JSONObject(unspents); if(jsonObj == null || !jsonObj.has("unspent_outputs")) { return null; } JSONArray utxoArray = jsonObj.getJSONArray("unspent_outputs"); if(utxoArray == null || utxoArray.length() == 0) { return null; } // debug("APIFactory", "unspents found:" + outputsRoot.size()); for (int i = 0; i < utxoArray.length(); i++) { JSONObject outDict = utxoArray.getJSONObject(i); byte[] hashBytes = Hex.decode((String)outDict.get("tx_hash")); Sha256Hash txHash = Sha256Hash.wrap(hashBytes); int txOutputN = ((Number)outDict.get("tx_output_n")).intValue(); BigInteger value = BigInteger.valueOf(((Number)outDict.get("value")).longValue()); String script = (String)outDict.get("script"); byte[] scriptBytes = Hex.decode(script); int confirmations = ((Number)outDict.get("confirmations")).intValue(); try { String address = null; if(Bech32Util.getInstance().isBech32Script(script)) { address = Bech32Util.getInstance().getAddressFromScript(script); debug("address parsed:", address); } else { address = new Script(scriptBytes).getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(); } // Construct the output MyTransactionOutPoint outPoint = new MyTransactionOutPoint(txHash, txOutputN, value, scriptBytes, address); outPoint.setConfirmations(confirmations); if(utxo == null) { utxo = new UTXO(); } utxo.getOutpoints().add(outPoint); } catch(Exception e) { ; } } } catch(JSONException je) { ; } } return utxo; } public static class TxMostRecentDateComparator implements Comparator<Tx> { public int compare(Tx t1, Tx t2) { final int BEFORE = -1; final int EQUAL = 0; final int AFTER = 1; int ret = 0; if(t1.getTS() > t2.getTS()) { ret = BEFORE; } else if(t1.getTS() < t2.getTS()) { ret = AFTER; } else { ret = EQUAL; } return ret; } } // use for post-mix private synchronized JSONObject getRawXPUB(String[] xpubs) { String _url = WebUtil.getAPIUrl(context); JSONObject jsonObject = null; try { String response = null; if(AppUtil.getInstance(context).isOfflineMode()) { response = PayloadUtil.getInstance(context).deserializeMultiAddrPost().toString(); } else if(!TorManager.getInstance(context).isRequired()) { // use POST StringBuilder args = new StringBuilder(); args.append("active="); args.append(StringUtils.join(xpubs, URLEncoder.encode("|", "UTF-8"))); info("APIFactory", "XPUB:" + args.toString()); args.append("&at="); args.append(getAccessToken()); response = WebUtil.getInstance(context).postURL(_url + "multiaddr?", args.toString()); info("APIFactory", "XPUB response:" + response); } else { HashMap<String,String> args = new HashMap<String,String>(); args.put("active", StringUtils.join(xpubs, "|")); info("APIFactory", "XPUB:" + args.toString()); args.put("at", getAccessToken()); response = WebUtil.getInstance(context).tor_postURL(_url + "multiaddr", args); info("APIFactory", "XPUB response:" + response); } try { jsonObject = new JSONObject(response); return jsonObject; } catch(JSONException je) { je.printStackTrace(); jsonObject = null; } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } public synchronized JSONObject getRawUnspentOutputs(String[] xpubs) { String _url = WebUtil.getAPIUrl(context); JSONObject jsonObject = null; String response = null; try { if(AppUtil.getInstance(context).isOfflineMode()) { response = PayloadUtil.getInstance(context).deserializeUTXOPost().toString(); } else if(!TorManager.getInstance(context).isRequired()) { StringBuilder args = new StringBuilder(); args.append("active="); args.append(StringUtils.join(xpubs, URLEncoder.encode("|", "UTF-8"))); debug("APIFactory", "UTXO args:" + args.toString()); args.append("&at="); args.append(getAccessToken()); response = WebUtil.getInstance(context).postURL(_url + "unspent?", args.toString()); debug("APIFactory", "UTXO:" + response); } else { HashMap<String,String> args = new HashMap<String,String>(); args.put("active", StringUtils.join(xpubs, "|")); args.put("at", getAccessToken()); response = WebUtil.getInstance(context).tor_postURL(_url + "unspent", args); } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } if(!AppUtil.getInstance(context).isOfflineMode()) { try { jsonObject = new JSONObject(response); } catch(JSONException je) { ; } } return jsonObject; } private synchronized boolean parseMixXPUB(JSONObject jsonObject) throws JSONException { if(jsonObject != null) { if(jsonObject.has("wallet")) { JSONObject walletObj = (JSONObject)jsonObject.get("wallet"); if(walletObj.has("final_balance")) { xpub_postmix_balance = walletObj.getLong("final_balance"); debug("APIFactory", "xpub_postmix_balance:" + xpub_postmix_balance); } } if(jsonObject.has("info")) { JSONObject infoObj = (JSONObject)jsonObject.get("info"); if(infoObj.has("latest_block")) { JSONObject blockObj = (JSONObject)infoObj.get("latest_block"); if(blockObj.has("height")) { latest_block_height = blockObj.getLong("height"); } if(blockObj.has("hash")) { latest_block_hash = blockObj.getString("hash"); } } } if(jsonObject.has("addresses")) { JSONArray addressesArray = (JSONArray)jsonObject.get("addresses"); JSONObject addrObj = null; for(int i = 0; i < addressesArray.length(); i++) { addrObj = (JSONObject)addressesArray.get(i); if(addrObj != null && addrObj.has("final_balance") && addrObj.has("address")) { if(FormatsUtil.getInstance().isValidXpub((String)addrObj.get("address"))) { // xpub_amounts.put((String)addrObj.get("address"), addrObj.getLong("final_balance")); if(addrObj.getString("address").equals(BIP84Util.getInstance(context).getWallet().getAccountAt(WhirlpoolMeta.getInstance(context).getWhirlpoolPostmix()).xpubstr()) || addrObj.getString("address").equals(BIP84Util.getInstance(context).getWallet().getAccountAt(WhirlpoolMeta.getInstance(context).getWhirlpoolPostmix()).zpubstr())) { AddressFactory.getInstance().setHighestPostReceiveIdx(addrObj.has("account_index") ? addrObj.getInt("account_index") : 0); AddressFactory.getInstance().setHighestPostChangeIdx(addrObj.has("change_index") ? addrObj.getInt("change_index") : 0); BIP84Util.getInstance(context).getWallet().getAccountAt(WhirlpoolMeta.getInstance(context).getWhirlpoolPostmix()).getChain(0).setAddrIdx(addrObj.has("account_index") ? addrObj.getInt("account_index") : 0); BIP84Util.getInstance(context).getWallet().getAccountAt(WhirlpoolMeta.getInstance(context).getWhirlpoolPostmix()).getChain(1).setAddrIdx(addrObj.has("change_index") ? addrObj.getInt("change_index") : 0); } else if(addrObj.getString("address").equals(BIP84Util.getInstance(context).getWallet().getAccountAt(WhirlpoolMeta.getInstance(context).getWhirlpoolPremixAccount()).xpubstr()) || addrObj.getString("address").equals(BIP84Util.getInstance(context).getWallet().getAccountAt(WhirlpoolMeta.getInstance(context).getWhirlpoolPremixAccount()).zpubstr())) { AddressFactory.getInstance().setHighestPreReceiveIdx(addrObj.has("account_index") ? addrObj.getInt("account_index") : 0); AddressFactory.getInstance().setHighestPreChangeIdx(addrObj.has("change_index") ? addrObj.getInt("change_index") : 0); BIP84Util.getInstance(context).getWallet().getAccountAt(WhirlpoolMeta.getInstance(context).getWhirlpoolPremixAccount()).getChain(0).setAddrIdx(addrObj.has("account_index") ? addrObj.getInt("account_index") : 0); BIP84Util.getInstance(context).getWallet().getAccountAt(WhirlpoolMeta.getInstance(context).getWhirlpoolPremixAccount()).getChain(1).setAddrIdx(addrObj.has("change_index") ? addrObj.getInt("change_index") : 0); } else { ; } } } } } try { PayloadUtil.getInstance(context).serializeMultiAddrPost(jsonObject); } catch(IOException | DecryptionException e) { ; } return true; } return false; } private synchronized boolean parsePostMixUnspentOutputs(String unspents) { if(unspents != null) { try { JSONObject jsonObj = new JSONObject(unspents); if(jsonObj == null || !jsonObj.has("unspent_outputs")) { return false; } JSONArray utxoArray = jsonObj.getJSONArray("unspent_outputs"); if(utxoArray == null || utxoArray.length() == 0) { return false; } for (int i = 0; i < utxoArray.length(); i++) { JSONObject outDict = utxoArray.getJSONObject(i); byte[] hashBytes = Hex.decode((String)outDict.get("tx_hash")); Sha256Hash txHash = Sha256Hash.wrap(hashBytes); int txOutputN = ((Number)outDict.get("tx_output_n")).intValue(); BigInteger value = BigInteger.valueOf(((Number)outDict.get("value")).longValue()); String script = (String)outDict.get("script"); byte[] scriptBytes = Hex.decode(script); int confirmations = ((Number)outDict.get("confirmations")).intValue(); String path = null; try { String address = Bech32Util.getInstance().getAddressFromScript(script); if(outDict.has("xpub")) { JSONObject xpubObj = (JSONObject)outDict.get("xpub"); path = (String)xpubObj.get("path"); String m = (String)xpubObj.get("m"); unspentPaths.put(address, path); if(m.equals(BIP84Util.getInstance(context).getWallet().getAccountAt(WhirlpoolMeta.getInstance(context).getWhirlpoolPostmix()).xpubstr())) { unspentBIP84PostMix.put(address, WhirlpoolMeta.getInstance(context).getWhirlpoolPostmix()); } } else { ; } // Construct the output MyTransactionOutPoint outPoint = new MyTransactionOutPoint(txHash, txOutputN, value, scriptBytes, address); outPoint.setConfirmations(confirmations); if(utxosPostMix.containsKey(script)) { utxosPostMix.get(script).getOutpoints().add(outPoint); } else { UTXO utxo = new UTXO(); utxo.getOutpoints().add(outPoint); utxo.setPath(path); utxosPostMix.put(script, utxo); } UTXOFactory.getInstance().addPostMix(script, utxosPostMix.get(script)); } catch(Exception e) { ; } } PayloadUtil.getInstance(context).serializeUTXOPost(jsonObj); return true; } catch(Exception j) { ; } } return false; } }
package com.samourai.wallet.api; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.net.Uri; import android.os.Handler; import android.os.Looper; import android.util.Log; import com.samourai.wallet.JSONRPC.JSONRPC; import com.samourai.wallet.JSONRPC.TrustedNodeUtil; import com.samourai.wallet.SamouraiWallet; import com.samourai.wallet.bip47.BIP47Meta; import com.samourai.wallet.bip47.BIP47Util; import com.samourai.wallet.hd.HD_Address; import com.samourai.wallet.hd.HD_Wallet; import com.samourai.wallet.hd.HD_WalletFactory; import com.samourai.wallet.segwit.BIP49Util; import com.samourai.wallet.segwit.BIP84Util; import com.samourai.wallet.segwit.SegwitAddress; import com.samourai.wallet.segwit.bech32.Bech32Segwit; import com.samourai.wallet.segwit.bech32.Bech32Util; import com.samourai.wallet.send.BlockedUTXO; import com.samourai.wallet.send.FeeUtil; import com.samourai.wallet.send.MyTransactionOutPoint; import com.samourai.wallet.send.RBFUtil; import com.samourai.wallet.send.SuggestedFee; import com.samourai.wallet.send.UTXO; import com.samourai.wallet.send.UTXOFactory; import com.samourai.wallet.util.AddressFactory; import com.samourai.wallet.util.ConnectivityStatus; import com.samourai.wallet.util.FormatsUtil; import com.samourai.wallet.util.PrefsUtil; import com.samourai.wallet.util.TorUtil; import com.samourai.wallet.util.WebUtil; import com.samourai.wallet.bip47.rpc.PaymentCode; import com.samourai.wallet.bip47.rpc.PaymentAddress; import com.samourai.wallet.R; import org.apache.commons.lang3.ArrayUtils; import org.apache.commons.lang3.StringUtils; import org.bitcoinj.core.Address; import org.bitcoinj.core.AddressFormatException; import org.bitcoinj.core.ECKey; import org.bitcoinj.core.Sha256Hash; import org.bitcoinj.core.TransactionOutPoint; import org.bitcoinj.crypto.MnemonicException; import org.bitcoinj.params.MainNetParams; import org.bitcoinj.params.TestNet3Params; import org.bitcoinj.script.Script; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.bouncycastle.util.encoders.Hex; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.Writer; import java.math.BigInteger; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; public class APIFactory { private static long xpub_balance = 0L; private static HashMap<String, Long> xpub_amounts = null; private static HashMap<String,List<Tx>> xpub_txs = null; private static HashMap<String,Integer> unspentAccounts = null; private static HashMap<String,Integer> unspentBIP49 = null; private static HashMap<String,Integer> unspentBIP84 = null; private static HashMap<String,String> unspentPaths = null; private static HashMap<String,UTXO> utxos = null; private static HashMap<String, Long> bip47_amounts = null; private static long latest_block_height = -1L; private static String latest_block_hash = null; private static APIFactory instance = null; private static Context context = null; private static AlertDialog alertDialog = null; private APIFactory() { ; } public static APIFactory getInstance(Context ctx) { context = ctx; if(instance == null) { xpub_amounts = new HashMap<String, Long>(); xpub_txs = new HashMap<String,List<Tx>>(); xpub_balance = 0L; bip47_amounts = new HashMap<String, Long>(); unspentPaths = new HashMap<String, String>(); unspentAccounts = new HashMap<String, Integer>(); unspentBIP49 = new HashMap<String, Integer>(); unspentBIP84 = new HashMap<String, Integer>(); utxos = new HashMap<String, UTXO>(); instance = new APIFactory(); } return instance; } public synchronized void reset() { xpub_balance = 0L; xpub_amounts.clear(); bip47_amounts.clear(); xpub_txs.clear(); unspentPaths = new HashMap<String, String>(); unspentAccounts = new HashMap<String, Integer>(); unspentBIP49 = new HashMap<String, Integer>(); unspentBIP84 = new HashMap<String, Integer>(); utxos = new HashMap<String, UTXO>(); UTXOFactory.getInstance().clear(); } private synchronized JSONObject getXPUB(String[] xpubs, boolean parse) { String _url = SamouraiWallet.getInstance().isTestNet() ? WebUtil.SAMOURAI_API2_TESTNET : WebUtil.SAMOURAI_API2; JSONObject jsonObject = null; try { String response = null; if(!TorUtil.getInstance(context).statusFromBroadcast()) { // use POST StringBuilder args = new StringBuilder(); args.append("active="); args.append(StringUtils.join(xpubs, URLEncoder.encode("|", "UTF-8"))); Log.i("APIFactory", "XPUB:" + args.toString()); response = WebUtil.getInstance(context).postURL(_url + "multiaddr?", args.toString()); Log.i("APIFactory", "XPUB response:" + response); } else { HashMap<String,String> args = new HashMap<String,String>(); args.put("active", StringUtils.join(xpubs, "|")); Log.i("APIFactory", "XPUB:" + args.toString()); response = WebUtil.getInstance(context).tor_postURL(_url + "multiaddr", args); Log.i("APIFactory", "XPUB response:" + response); } try { jsonObject = new JSONObject(response); if(!parse) { return jsonObject; } xpub_txs.put(xpubs[0], new ArrayList<Tx>()); parseXPUB(jsonObject); xpub_amounts.put(HD_WalletFactory.getInstance(context).get().getAccount(0).xpubstr(), xpub_balance - BlockedUTXO.getInstance().getTotalValueBlocked()); } catch(JSONException je) { je.printStackTrace(); jsonObject = null; } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } private synchronized JSONObject registerXPUB(String xpub, int purpose) { String _url = SamouraiWallet.getInstance().isTestNet() ? WebUtil.SAMOURAI_API2_TESTNET : WebUtil.SAMOURAI_API2; JSONObject jsonObject = null; try { String response = null; if(!TorUtil.getInstance(context).statusFromBroadcast()) { // use POST StringBuilder args = new StringBuilder(); args.append("xpub="); args.append(xpub); args.append("&type="); if(PrefsUtil.getInstance(context).getValue(PrefsUtil.IS_RESTORE, false) == true) { args.append("restore"); } else { args.append("new"); } if(purpose == 49) { args.append("&segwit="); args.append("bip49"); } else if(purpose == 84) { args.append("&segwit="); args.append("bip84"); } else { ; } Log.i("APIFactory", "XPUB:" + args.toString()); response = WebUtil.getInstance(context).postURL(_url + "xpub?", args.toString()); Log.i("APIFactory", "XPUB response:" + response); } else { HashMap<String,String> args = new HashMap<String,String>(); args.put("xpub", xpub); if(PrefsUtil.getInstance(context).getValue(PrefsUtil.IS_RESTORE, false) == true) { args.put("type", "restore"); } else { args.put("type", "new"); } if(purpose == 49) { args.put("segwit", "bip49"); } else if(purpose == 84) { args.put("segwit", "bip84"); } else { ; } Log.i("APIFactory", "XPUB:" + args.toString()); response = WebUtil.getInstance(context).tor_postURL(_url + "xpub", args); Log.i("APIFactory", "XPUB response:" + response); } try { jsonObject = new JSONObject(response); Log.i("APIFactory", "XPUB response:" + jsonObject.toString()); if(jsonObject.has("status") && jsonObject.getString("status").equals("ok")) { if(purpose == 49) { PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB49REG, true); PrefsUtil.getInstance(context).removeValue(PrefsUtil.IS_RESTORE); } else if(purpose == 84) { PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB84REG, true); PrefsUtil.getInstance(context).removeValue(PrefsUtil.IS_RESTORE); } else { ; } } } catch(JSONException je) { je.printStackTrace(); jsonObject = null; } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } private synchronized boolean parseXPUB(JSONObject jsonObject) throws JSONException { if(jsonObject != null) { if(jsonObject.has("wallet")) { JSONObject walletObj = (JSONObject)jsonObject.get("wallet"); if(walletObj.has("final_balance")) { xpub_balance = walletObj.getLong("final_balance"); Log.d("APIFactory", "xpub_balance:" + xpub_balance); } } if(jsonObject.has("info")) { JSONObject infoObj = (JSONObject)jsonObject.get("info"); if(infoObj.has("latest_block")) { JSONObject blockObj = (JSONObject)infoObj.get("latest_block"); if(blockObj.has("height")) { latest_block_height = blockObj.getLong("height"); } if(blockObj.has("hash")) { latest_block_hash = blockObj.getString("hash"); } } } if(jsonObject.has("addresses")) { JSONArray addressesArray = (JSONArray)jsonObject.get("addresses"); JSONObject addrObj = null; for(int i = 0; i < addressesArray.length(); i++) { addrObj = (JSONObject)addressesArray.get(i); if(addrObj != null && addrObj.has("final_balance") && addrObj.has("address")) { if(FormatsUtil.getInstance().isValidXpub((String)addrObj.get("address"))) { xpub_amounts.put((String)addrObj.get("address"), addrObj.getLong("final_balance")); if(addrObj.getString("address").equals(BIP84Util.getInstance(context).getWallet().getAccount(0).xpubstr())) { AddressFactory.getInstance().setHighestBIP84ReceiveIdx(addrObj.has("account_index") ? addrObj.getInt("account_index") : 0); AddressFactory.getInstance().setHighestBIP84ChangeIdx(addrObj.has("change_index") ? addrObj.getInt("change_index") : 0); } else if(addrObj.getString("address").equals(BIP49Util.getInstance(context).getWallet().getAccount(0).xpubstr())) { AddressFactory.getInstance().setHighestBIP49ReceiveIdx(addrObj.has("account_index") ? addrObj.getInt("account_index") : 0); AddressFactory.getInstance().setHighestBIP49ChangeIdx(addrObj.has("change_index") ? addrObj.getInt("change_index") : 0); } else if(AddressFactory.getInstance().xpub2account().get((String) addrObj.get("address")) != null) { AddressFactory.getInstance().setHighestTxReceiveIdx(AddressFactory.getInstance().xpub2account().get((String) addrObj.get("address")), addrObj.has("account_index") ? addrObj.getInt("account_index") : 0); AddressFactory.getInstance().setHighestTxChangeIdx(AddressFactory.getInstance().xpub2account().get((String)addrObj.get("address")), addrObj.has("change_index") ? addrObj.getInt("change_index") : 0); } else { ; } } else { long amount = 0L; String addr = null; addr = (String)addrObj.get("address"); amount = addrObj.getLong("final_balance"); String pcode = BIP47Meta.getInstance().getPCode4Addr(addr); if(addr != null && addr.length() > 0 && pcode != null && pcode.length() > 0 && BIP47Meta.getInstance().getIdx4Addr(addr) != null) { int idx = BIP47Meta.getInstance().getIdx4Addr(addr); if(amount > 0L) { BIP47Meta.getInstance().addUnspent(pcode, idx); } else { BIP47Meta.getInstance().removeUnspent(pcode, Integer.valueOf(idx)); } if(addr != null) { bip47_amounts.put(addr, amount); } } } } } } if(jsonObject.has("txs")) { JSONArray txArray = (JSONArray)jsonObject.get("txs"); JSONObject txObj = null; for(int i = 0; i < txArray.length(); i++) { txObj = (JSONObject)txArray.get(i); long height = 0L; long amount = 0L; long ts = 0L; String hash = null; String addr = null; String _addr = null; if(txObj.has("block_height")) { height = txObj.getLong("block_height"); } else { height = -1L; // 0 confirmations } if(txObj.has("hash")) { hash = (String)txObj.get("hash"); } if(txObj.has("result")) { amount = txObj.getLong("result"); } if(txObj.has("time")) { ts = txObj.getLong("time"); } if(txObj.has("inputs")) { JSONArray inputArray = (JSONArray)txObj.get("inputs"); JSONObject inputObj = null; for(int j = 0; j < inputArray.length(); j++) { inputObj = (JSONObject)inputArray.get(j); if(inputObj.has("prev_out")) { JSONObject prevOutObj = (JSONObject)inputObj.get("prev_out"); if(prevOutObj.has("xpub")) { JSONObject xpubObj = (JSONObject)prevOutObj.get("xpub"); addr = (String)xpubObj.get("m"); } else if(prevOutObj.has("addr") && BIP47Meta.getInstance().getPCode4Addr((String)prevOutObj.get("addr")) != null) { _addr = (String)prevOutObj.get("addr"); } else { _addr = (String)prevOutObj.get("addr"); } } } } if(txObj.has("out")) { JSONArray outArray = (JSONArray)txObj.get("out"); JSONObject outObj = null; for(int j = 0; j < outArray.length(); j++) { outObj = (JSONObject)outArray.get(j); if(outObj.has("xpub")) { JSONObject xpubObj = (JSONObject)outObj.get("xpub"); addr = (String)xpubObj.get("m"); } else { _addr = (String)outObj.get("addr"); } } } if(addr != null || _addr != null) { if(addr == null) { addr = _addr; } Tx tx = new Tx(hash, addr, amount, ts, (latest_block_height > 0L && height > 0L) ? (latest_block_height - height) + 1 : 0); if(BIP47Meta.getInstance().getPCode4Addr(addr) != null) { tx.setPaymentCode(BIP47Meta.getInstance().getPCode4Addr(addr)); } if(!xpub_txs.containsKey(addr)) { xpub_txs.put(addr, new ArrayList<Tx>()); } if(FormatsUtil.getInstance().isValidXpub(addr)) { xpub_txs.get(addr).add(tx); } else { xpub_txs.get(AddressFactory.getInstance().account2xpub().get(0)).add(tx); } if(height > 0L) { RBFUtil.getInstance().remove(hash); } } } } return true; } return false; } /* public synchronized JSONObject deleteXPUB(String xpub, boolean bip49) { String _url = SamouraiWallet.getInstance().isTestNet() ? WebUtil.SAMOURAI_API2_TESTNET : WebUtil.SAMOURAI_API2; JSONObject jsonObject = null; try { String response = null; ECKey ecKey = null; if(AddressFactory.getInstance(context).xpub2account().get(xpub) != null || xpub.equals(BIP49Util.getInstance(context).getWallet().getAccount(0).ypubstr())) { HD_Address addr = null; if(bip49) { addr = BIP49Util.getInstance(context).getWallet().getAccountAt(0).getChange().getAddressAt(0); } else { addr = HD_WalletFactory.getInstance(context).get().getAccount(0).getChain(AddressFactory.CHANGE_CHAIN).getAddressAt(0); } ecKey = addr.getECKey(); if(ecKey != null && ecKey.hasPrivKey()) { String sig = ecKey.signMessage(xpub); String address = null; if(bip49) { SegwitAddress segwitAddress = new SegwitAddress(ecKey.getPubKey(), SamouraiWallet.getInstance().getCurrentNetworkParams()); address = segwitAddress.getAddressAsString(); } else { address = ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(); } if(!TorUtil.getInstance(context).statusFromBroadcast()) { StringBuilder args = new StringBuilder(); args.append("message="); args.append(xpub); args.append("address="); args.append(address); args.append("&signature="); args.append(Uri.encode(sig)); Log.i("APIFactory", "delete XPUB:" + args.toString()); response = WebUtil.getInstance(context).deleteURL(_url + "delete/" + xpub, args.toString()); Log.i("APIFactory", "delete XPUB response:" + response); } else { HashMap<String,String> args = new HashMap<String,String>(); args.put("message", xpub); args.put("address", address); args.put("signature", Uri.encode(sig)); Log.i("APIFactory", "delete XPUB:" + args.toString()); response = WebUtil.getInstance(context).tor_deleteURL(_url + "delete", args); Log.i("APIFactory", "delete XPUB response:" + response); } try { jsonObject = new JSONObject(response); if(jsonObject.has("status") && jsonObject.getString("status").equals("ok")) { ; } } catch(JSONException je) { je.printStackTrace(); jsonObject = null; } } } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } */ public synchronized JSONObject lockXPUB(String xpub, int purpose) { String _url = SamouraiWallet.getInstance().isTestNet() ? WebUtil.SAMOURAI_API2_TESTNET : WebUtil.SAMOURAI_API2; JSONObject jsonObject = null; try { String response = null; ECKey ecKey = null; if(AddressFactory.getInstance(context).xpub2account().get(xpub) != null || xpub.equals(BIP49Util.getInstance(context).getWallet().getAccount(0).ypubstr())) { HD_Address addr = null; switch(purpose) { case 49: addr = BIP49Util.getInstance(context).getWallet().getAccountAt(0).getChange().getAddressAt(0); break; case 84: addr = BIP84Util.getInstance(context).getWallet().getAccountAt(0).getChange().getAddressAt(0); break; default: addr = HD_WalletFactory.getInstance(context).get().getAccount(0).getChain(AddressFactory.CHANGE_CHAIN).getAddressAt(0); break; } ecKey = addr.getECKey(); if(ecKey != null && ecKey.hasPrivKey()) { String sig = ecKey.signMessage("lock"); String address = null; switch(purpose) { case 49: SegwitAddress p2shp2wpkh = new SegwitAddress(ecKey.getPubKey(), SamouraiWallet.getInstance().getCurrentNetworkParams()); address = p2shp2wpkh.getAddressAsString(); break; case 84: SegwitAddress segwitAddress = new SegwitAddress(ecKey.getPubKey(), SamouraiWallet.getInstance().getCurrentNetworkParams()); address = segwitAddress.getBech32AsString(); break; default: address = ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(); break; } if(!TorUtil.getInstance(context).statusFromBroadcast()) { StringBuilder args = new StringBuilder(); args.append("address="); args.append(address); args.append("&signature="); args.append(Uri.encode(sig)); args.append("&message="); args.append("lock"); // Log.i("APIFactory", "lock XPUB:" + args.toString()); response = WebUtil.getInstance(context).postURL(_url + "xpub/" + xpub + "/lock/", args.toString()); // Log.i("APIFactory", "lock XPUB response:" + response); } else { HashMap<String,String> args = new HashMap<String,String>(); args.put("address", address); args.put("signature", Uri.encode(sig)); args.put("message", "lock"); // Log.i("APIFactory", "lock XPUB:" + args.toString()); response = WebUtil.getInstance(context).tor_postURL(_url + "xpub" + xpub + "/lock/", args); // Log.i("APIFactory", "lock XPUB response:" + response); } try { jsonObject = new JSONObject(response); if(jsonObject.has("status") && jsonObject.getString("status").equals("ok")) { switch(purpose) { case 49: PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB49LOCK, true); break; case 84: PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB84LOCK, true); break; default: PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB44LOCK, true); break; } } } catch(JSONException je) { je.printStackTrace(); jsonObject = null; } } } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } public long getLatestBlockHeight() { return latest_block_height; } public String getLatestBlockHash() { return latest_block_hash; } public JSONObject getNotifTx(String hash, String addr) { String _url = SamouraiWallet.getInstance().isTestNet() ? WebUtil.SAMOURAI_API2_TESTNET : WebUtil.SAMOURAI_API2; JSONObject jsonObject = null; try { StringBuilder url = new StringBuilder(_url); url.append("tx/"); url.append(hash); url.append("?fees=1"); // Log.i("APIFactory", "Notif tx:" + url.toString()); String response = WebUtil.getInstance(null).getURL(url.toString()); // Log.i("APIFactory", "Notif tx:" + response); try { jsonObject = new JSONObject(response); parseNotifTx(jsonObject, addr, hash); } catch(JSONException je) { je.printStackTrace(); jsonObject = null; } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } public JSONObject getNotifAddress(String addr) { String _url = SamouraiWallet.getInstance().isTestNet() ? WebUtil.SAMOURAI_API2_TESTNET : WebUtil.SAMOURAI_API2; JSONObject jsonObject = null; try { StringBuilder url = new StringBuilder(_url); url.append("multiaddr?active="); url.append(addr); // Log.i("APIFactory", "Notif address:" + url.toString()); String response = WebUtil.getInstance(null).getURL(url.toString()); // Log.i("APIFactory", "Notif address:" + response); try { jsonObject = new JSONObject(response); parseNotifAddress(jsonObject, addr); } catch(JSONException je) { je.printStackTrace(); jsonObject = null; } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } public void parseNotifAddress(JSONObject jsonObject, String addr) throws JSONException { if(jsonObject != null && jsonObject.has("txs")) { JSONArray txArray = jsonObject.getJSONArray("txs"); JSONObject txObj = null; for(int i = 0; i < txArray.length(); i++) { txObj = (JSONObject)txArray.get(i); if(!txObj.has("block_height") || (txObj.has("block_height") && txObj.getLong("block_height") < 1L)) { return; } String hash = null; if(txObj.has("hash")) { hash = (String)txObj.get("hash"); if(BIP47Meta.getInstance().getIncomingStatus(hash) == null) { getNotifTx(hash, addr); } } } } } public void parseNotifTx(JSONObject jsonObject, String addr, String hash) throws JSONException { Log.i("APIFactory", "notif address:" + addr); Log.i("APIFactory", "hash:" + hash); if(jsonObject != null) { byte[] mask = null; byte[] payload = null; PaymentCode pcode = null; if(jsonObject.has("inputs")) { JSONArray inArray = (JSONArray)jsonObject.get("inputs"); if(inArray.length() > 0) { JSONObject objInput = (JSONObject)inArray.get(0); byte[] pubkey = null; String strScript = objInput.getString("sig"); Log.i("APIFactory", "scriptsig:" + strScript); if((strScript == null || strScript.length() == 0 || strScript.startsWith("160014")) && objInput.has("witness")) { JSONArray witnessArray = (JSONArray)objInput.get("witness"); if(witnessArray.length() == 2) { pubkey = Hex.decode((String)witnessArray.get(1)); } } else { Script script = new Script(Hex.decode(strScript)); Log.i("APIFactory", "pubkey from script:" + Hex.toHexString(script.getPubKey())); pubkey = script.getPubKey(); } ECKey pKey = new ECKey(null, pubkey, true); Log.i("APIFactory", "address from script:" + pKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString()); // Log.i("APIFactory", "uncompressed public key from script:" + Hex.toHexString(pKey.decompress().getPubKey())); if(((JSONObject)inArray.get(0)).has("outpoint")) { JSONObject received_from = ((JSONObject) inArray.get(0)).getJSONObject("outpoint"); String strHash = received_from.getString("txid"); int idx = received_from.getInt("vout"); byte[] hashBytes = Hex.decode(strHash); Sha256Hash txHash = new Sha256Hash(hashBytes); TransactionOutPoint outPoint = new TransactionOutPoint(SamouraiWallet.getInstance().getCurrentNetworkParams(), idx, txHash); byte[] outpoint = outPoint.bitcoinSerialize(); Log.i("APIFactory", "outpoint:" + Hex.toHexString(outpoint)); try { mask = BIP47Util.getInstance(context).getIncomingMask(pubkey, outpoint); Log.i("APIFactory", "mask:" + Hex.toHexString(mask)); } catch(Exception e) { e.printStackTrace(); } } } } if(jsonObject.has("outputs")) { JSONArray outArray = (JSONArray)jsonObject.get("outputs"); JSONObject outObj = null; boolean isIncoming = false; String _addr = null; String script = null; String op_return = null; for(int j = 0; j < outArray.length(); j++) { outObj = (JSONObject)outArray.get(j); if(outObj.has("address")) { _addr = outObj.getString("address"); if(addr.equals(_addr)) { isIncoming = true; } } if(outObj.has("scriptpubkey")) { script = outObj.getString("scriptpubkey"); if(script.startsWith("6a4c50")) { op_return = script; } } } if(isIncoming && op_return != null && op_return.startsWith("6a4c50")) { payload = Hex.decode(op_return.substring(6)); } } if(mask != null && payload != null) { try { byte[] xlat_payload = PaymentCode.blind(payload, mask); Log.i("APIFactory", "xlat_payload:" + Hex.toHexString(xlat_payload)); pcode = new PaymentCode(xlat_payload); Log.i("APIFactory", "incoming payment code:" + pcode.toString()); if(!pcode.toString().equals(BIP47Util.getInstance(context).getPaymentCode().toString()) && pcode.isValid() && !BIP47Meta.getInstance().incomingExists(pcode.toString())) { BIP47Meta.getInstance().setLabel(pcode.toString(), ""); BIP47Meta.getInstance().setIncomingStatus(hash); } } catch(AddressFormatException afe) { afe.printStackTrace(); } } // get receiving addresses for spends from decoded payment code if(pcode != null) { try { // initial lookup for(int i = 0; i < 3; i++) { PaymentAddress receiveAddress = BIP47Util.getInstance(context).getReceiveAddress(pcode, i); // Log.i("APIFactory", "receive from " + i + ":" + receiveAddress.getReceiveECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString()); BIP47Meta.getInstance().setIncomingIdx(pcode.toString(), i, receiveAddress.getReceiveECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString()); BIP47Meta.getInstance().getIdx4AddrLookup().put(receiveAddress.getReceiveECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(), i); BIP47Meta.getInstance().getPCode4AddrLookup().put(receiveAddress.getReceiveECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(), pcode.toString()); // Log.i("APIFactory", "send to " + i + ":" + sendAddress.getSendECKey().toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString()); } } catch(Exception e) { ; } } } } public synchronized int getNotifTxConfirmations(String hash) { String _url = SamouraiWallet.getInstance().isTestNet() ? WebUtil.SAMOURAI_API2_TESTNET : WebUtil.SAMOURAI_API2; // Log.i("APIFactory", "Notif tx:" + hash); JSONObject jsonObject = null; try { StringBuilder url = new StringBuilder(_url); url.append("tx/"); url.append(hash); url.append("?fees=1"); // Log.i("APIFactory", "Notif tx:" + url.toString()); String response = WebUtil.getInstance(null).getURL(url.toString()); // Log.i("APIFactory", "Notif tx:" + response); jsonObject = new JSONObject(response); // Log.i("APIFactory", "Notif tx json:" + jsonObject.toString()); return parseNotifTx(jsonObject); } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return 0; } public synchronized int parseNotifTx(JSONObject jsonObject) throws JSONException { int cf = 0; if(jsonObject != null && jsonObject.has("block") && jsonObject.getJSONObject("block").has("height")) { long latestBlockHeght = getLatestBlockHeight(); long height = jsonObject.getJSONObject("block").getLong("height"); cf = (int)((latestBlockHeght - height) + 1); if(cf < 0) { cf = 0; } } return cf; } public synchronized JSONObject getUnspentOutputs(String[] xpubs) { String _url = SamouraiWallet.getInstance().isTestNet() ? WebUtil.SAMOURAI_API2_TESTNET : WebUtil.SAMOURAI_API2; JSONObject jsonObject = null; try { String response = null; if(!TorUtil.getInstance(context).statusFromBroadcast()) { StringBuilder args = new StringBuilder(); args.append("active="); args.append(StringUtils.join(xpubs, URLEncoder.encode("|", "UTF-8"))); response = WebUtil.getInstance(context).postURL(_url + "unspent?", args.toString()); } else { HashMap<String,String> args = new HashMap<String,String>(); args.put("active", StringUtils.join(xpubs, "|")); response = WebUtil.getInstance(context).tor_postURL(_url + "unspent", args); } parseUnspentOutputs(response); } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } private synchronized boolean parseUnspentOutputs(String unspents) { if(unspents != null) { try { JSONObject jsonObj = new JSONObject(unspents); if(jsonObj == null || !jsonObj.has("unspent_outputs")) { return false; } JSONArray utxoArray = jsonObj.getJSONArray("unspent_outputs"); if(utxoArray == null || utxoArray.length() == 0) { return false; } for (int i = 0; i < utxoArray.length(); i++) { JSONObject outDict = utxoArray.getJSONObject(i); byte[] hashBytes = Hex.decode((String)outDict.get("tx_hash")); Sha256Hash txHash = Sha256Hash.wrap(hashBytes); int txOutputN = ((Number)outDict.get("tx_output_n")).intValue(); BigInteger value = BigInteger.valueOf(((Number)outDict.get("value")).longValue()); String script = (String)outDict.get("script"); byte[] scriptBytes = Hex.decode(script); int confirmations = ((Number)outDict.get("confirmations")).intValue(); try { String address = null; if(Bech32Util.getInstance().isBech32Script(script)) { address = Bech32Util.getInstance().getAddressFromScript(script); } else { address = new Script(scriptBytes).getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(); } if(outDict.has("xpub")) { JSONObject xpubObj = (JSONObject)outDict.get("xpub"); String path = (String)xpubObj.get("path"); String m = (String)xpubObj.get("m"); unspentPaths.put(address, path); if(m.equals(BIP49Util.getInstance(context).getWallet().getAccount(0).xpubstr())) { unspentBIP49.put(address, 0); // assume account 0 } else if(m.equals(BIP84Util.getInstance(context).getWallet().getAccount(0).xpubstr())) { unspentBIP84.put(address, 0); // assume account 0 } else { unspentAccounts.put(address, AddressFactory.getInstance(context).xpub2account().get(m)); } } // Construct the output MyTransactionOutPoint outPoint = new MyTransactionOutPoint(txHash, txOutputN, value, scriptBytes, address); outPoint.setConfirmations(confirmations); if(utxos.containsKey(script)) { utxos.get(script).getOutpoints().add(outPoint); } else { UTXO utxo = new UTXO(); utxo.getOutpoints().add(outPoint); utxos.put(script, utxo); } if(!BlockedUTXO.getInstance().contains(txHash.toString(), txOutputN)) { if(Bech32Util.getInstance().isBech32Script(script)) { UTXOFactory.getInstance().addP2WPKH(script, utxos.get(script)); } else if(Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), address).isP2SHAddress()) { UTXOFactory.getInstance().addP2SH_P2WPKH(script, utxos.get(script)); } else { UTXOFactory.getInstance().addP2PKH(script, utxos.get(script)); } } } catch(Exception e) { ; } } return true; } catch(JSONException je) { ; } } return false; } public synchronized JSONObject getAddressInfo(String addr) { return getXPUB(new String[] { addr }, false); } public synchronized JSONObject getTxInfo(String hash) { String _url = SamouraiWallet.getInstance().isTestNet() ? WebUtil.SAMOURAI_API2_TESTNET : WebUtil.SAMOURAI_API2; JSONObject jsonObject = null; try { StringBuilder url = new StringBuilder(_url); url.append("tx/"); url.append(hash); url.append("?fees=true"); String response = WebUtil.getInstance(context).getURL(url.toString()); jsonObject = new JSONObject(response); } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } public synchronized JSONObject getBlockHeader(String hash) { String _url = SamouraiWallet.getInstance().isTestNet() ? WebUtil.SAMOURAI_API2_TESTNET : WebUtil.SAMOURAI_API2; JSONObject jsonObject = null; try { StringBuilder url = new StringBuilder(_url); url.append("header/"); url.append(hash); String response = WebUtil.getInstance(context).getURL(url.toString()); jsonObject = new JSONObject(response); } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } public synchronized JSONObject getDynamicFees() { JSONObject jsonObject = null; try { int sel = PrefsUtil.getInstance(context).getValue(PrefsUtil.FEE_PROVIDER_SEL, 0); if(sel == 1) { int[] blocks = new int[] { 2, 6, 24 }; List<SuggestedFee> suggestedFees = new ArrayList<SuggestedFee>(); JSONRPC jsonrpc = new JSONRPC(TrustedNodeUtil.getInstance().getUser(), TrustedNodeUtil.getInstance().getPassword(), TrustedNodeUtil.getInstance().getNode(), TrustedNodeUtil.getInstance().getPort()); for(int i = 0; i < blocks.length; i++) { JSONObject feeObj = jsonrpc.getFeeEstimate(blocks[i]); if(feeObj != null && feeObj.has("result")) { double fee = feeObj.getDouble("result"); SuggestedFee suggestedFee = new SuggestedFee(); suggestedFee.setDefaultPerKB(BigInteger.valueOf((long)(fee * 1e8))); suggestedFee.setStressed(false); suggestedFee.setOK(true); suggestedFees.add(suggestedFee); } } if(suggestedFees.size() > 0) { FeeUtil.getInstance().setEstimatedFees(suggestedFees); } } else { StringBuilder url = new StringBuilder(WebUtil.BITCOIND_FEE_URL); // Log.i("APIFactory", "Dynamic fees:" + url.toString()); String response = WebUtil.getInstance(null).getURL(url.toString()); // Log.i("APIFactory", "Dynamic fees response:" + response); try { jsonObject = new JSONObject(response); parseDynamicFees_bitcoind(jsonObject); } catch(JSONException je) { je.printStackTrace(); jsonObject = null; } } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } private synchronized boolean parseDynamicFees_bitcoind(JSONObject jsonObject) throws JSONException { if(jsonObject != null) { // bitcoind List<SuggestedFee> suggestedFees = new ArrayList<SuggestedFee>(); if(jsonObject.has("2")) { long fee = jsonObject.getInt("2"); SuggestedFee suggestedFee = new SuggestedFee(); suggestedFee.setDefaultPerKB(BigInteger.valueOf(fee * 1000L)); suggestedFee.setStressed(false); suggestedFee.setOK(true); suggestedFees.add(suggestedFee); } if(jsonObject.has("6")) { long fee = jsonObject.getInt("6"); SuggestedFee suggestedFee = new SuggestedFee(); suggestedFee.setDefaultPerKB(BigInteger.valueOf(fee * 1000L)); suggestedFee.setStressed(false); suggestedFee.setOK(true); suggestedFees.add(suggestedFee); } if(jsonObject.has("24")) { long fee = jsonObject.getInt("24"); SuggestedFee suggestedFee = new SuggestedFee(); suggestedFee.setDefaultPerKB(BigInteger.valueOf(fee * 1000L)); suggestedFee.setStressed(false); suggestedFee.setOK(true); suggestedFees.add(suggestedFee); } if(suggestedFees.size() > 0) { FeeUtil.getInstance().setEstimatedFees(suggestedFees); // Log.d("APIFactory", "high fee:" + FeeUtil.getInstance().getHighFee().getDefaultPerKB().toString()); // Log.d("APIFactory", "suggested fee:" + FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().toString()); // Log.d("APIFactory", "low fee:" + FeeUtil.getInstance().getLowFee().getDefaultPerKB().toString()); } return true; } return false; } public synchronized void validateAPIThread() { final Handler handler = new Handler(); new Thread(new Runnable() { @Override public void run() { Looper.prepare(); if(ConnectivityStatus.hasConnectivity(context)) { try { String response = WebUtil.getInstance(context).getURL(WebUtil.SAMOURAI_API_CHECK); JSONObject jsonObject = new JSONObject(response); if(!jsonObject.has("process")) { showAlertDialog(context.getString(R.string.api_error), false); } } catch(Exception e) { showAlertDialog(context.getString(R.string.cannot_reach_api), false); } } else { showAlertDialog(context.getString(R.string.no_internet), false); } handler.post(new Runnable() { @Override public void run() { ; } }); Looper.loop(); } }).start(); } private void showAlertDialog(final String message, final boolean forceExit){ if (!((Activity) context).isFinishing()) { if(alertDialog != null)alertDialog.dismiss(); final AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setMessage(message); builder.setCancelable(false); if(!forceExit) { builder.setPositiveButton(R.string.retry, new DialogInterface.OnClickListener() { public void onClick(DialogInterface d, int id) { d.dismiss(); //Retry validateAPIThread(); } }); } builder.setNegativeButton(R.string.exit, new DialogInterface.OnClickListener() { public void onClick(DialogInterface d, int id) { d.dismiss(); ((Activity) context).finish(); } }); alertDialog = builder.create(); alertDialog.show(); } } public synchronized void initWallet() { Log.i("APIFactory", "initWallet()"); initWalletAmounts(); } private synchronized void initWalletAmounts() { APIFactory.getInstance(context).reset(); List<String> addressStrings = new ArrayList<String>(); String[] s = null; try { /* if(PrefsUtil.getInstance(context).getValue(PrefsUtil.XPUB44REG, false) == false) { registerXPUB(HD_WalletFactory.getInstance(context).get().getAccount(0).xpubstr(), false); } */ if(PrefsUtil.getInstance(context).getValue(PrefsUtil.XPUB49REG, false) == false) { registerXPUB(BIP49Util.getInstance(context).getWallet().getAccount(0).xpubstr(), 49); } if(PrefsUtil.getInstance(context).getValue(PrefsUtil.XPUB84REG, false) == false) { registerXPUB(BIP84Util.getInstance(context).getWallet().getAccount(0).xpubstr(), 84); } xpub_txs.put(HD_WalletFactory.getInstance(context).get().getAccount(0).xpubstr(), new ArrayList<Tx>()); addressStrings.addAll(Arrays.asList(BIP47Meta.getInstance().getIncomingAddresses(false))); for(String _s : Arrays.asList(BIP47Meta.getInstance().getIncomingLookAhead(context))) { if(!addressStrings.contains(_s)) { addressStrings.add(_s); } } for(String pcode : BIP47Meta.getInstance().getUnspentProviders()) { for(String addr : BIP47Meta.getInstance().getUnspentAddresses(context, pcode)) { if(!addressStrings.contains(addr)) { addressStrings.add(addr); } } } if(addressStrings.size() > 0) { s = addressStrings.toArray(new String[0]); // Log.i("APIFactory", addressStrings.toString()); getUnspentOutputs(s); } Log.d("APIFactory", "addresses:" + addressStrings.toString()); HD_Wallet hdw = HD_WalletFactory.getInstance(context).get(); if(hdw != null && hdw.getXPUBs() != null) { String[] all = null; if(s != null && s.length > 0) { all = new String[hdw.getXPUBs().length + 2 + s.length]; all[0] = BIP49Util.getInstance(context).getWallet().getAccount(0).xpubstr(); all[1] = BIP84Util.getInstance(context).getWallet().getAccount(0).xpubstr(); System.arraycopy(hdw.getXPUBs(), 0, all, 2, hdw.getXPUBs().length); System.arraycopy(s, 0, all, hdw.getXPUBs().length + 2, s.length); } else { all = new String[hdw.getXPUBs().length + 2]; all[0] = BIP49Util.getInstance(context).getWallet().getAccount(0).xpubstr(); all[1] = BIP84Util.getInstance(context).getWallet().getAccount(0).xpubstr(); System.arraycopy(hdw.getXPUBs(), 0, all, 2, hdw.getXPUBs().length); } APIFactory.getInstance(context).getXPUB(all, true); String[] xs = new String[4]; xs[0] = HD_WalletFactory.getInstance(context).get().getAccount(0).xpubstr(); xs[1] = HD_WalletFactory.getInstance(context).get().getAccount(1).xpubstr(); xs[2] = BIP49Util.getInstance(context).getWallet().getAccount(0).xpubstr(); xs[3] = BIP84Util.getInstance(context).getWallet().getAccount(0).xpubstr(); getUnspentOutputs(xs); getDynamicFees(); } List<String> seenOutputs = new ArrayList<String>(); List<UTXO> _utxos = getUtxos(false); for(UTXO _u : _utxos) { for(MyTransactionOutPoint _o : _u.getOutpoints()) { seenOutputs.add(_o.getTxHash().toString() + "-" + _o.getTxOutputN()); } } for(String _s : BlockedUTXO.getInstance().getNotDustedUTXO()) { // Log.d("APIFactory", "not dusted:" + _s); if(!seenOutputs.contains(_s)) { BlockedUTXO.getInstance().removeNotDusted(_s); // Log.d("APIFactory", "not dusted removed:" + _s); } } for(String _s : BlockedUTXO.getInstance().getBlockedUTXO().keySet()) { // Log.d("APIFactory", "blocked:" + _s); if(!seenOutputs.contains(_s)) { BlockedUTXO.getInstance().remove(_s); // Log.d("APIFactory", "blocked removed:" + _s); } } } catch (IndexOutOfBoundsException ioobe) { ioobe.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public synchronized int syncBIP47Incoming(String[] addresses) { JSONObject jsonObject = getXPUB(addresses, false); int ret = 0; try { if(jsonObject != null && jsonObject.has("addresses")) { JSONArray addressArray = (JSONArray)jsonObject.get("addresses"); JSONObject addrObj = null; for(int i = 0; i < addressArray.length(); i++) { addrObj = (JSONObject)addressArray.get(i); long amount = 0L; int nbTx = 0; String addr = null; String pcode = null; int idx = -1; if(addrObj.has("address")) { addr = (String)addrObj.get("address"); pcode = BIP47Meta.getInstance().getPCode4Addr(addr); idx = BIP47Meta.getInstance().getIdx4Addr(addr); if(addrObj.has("final_balance")) { amount = addrObj.getLong("final_balance"); if(amount > 0L) { BIP47Meta.getInstance().addUnspent(pcode, idx); } else { BIP47Meta.getInstance().removeUnspent(pcode, Integer.valueOf(idx)); } } if(addrObj.has("n_tx")) { nbTx = addrObj.getInt("n_tx"); if(nbTx > 0) { // Log.i("APIFactory", "sync receive idx:" + idx + ", " + addr); ret++; } } } } } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return ret; } public synchronized int syncBIP47Outgoing(String[] addresses) { JSONObject jsonObject = getXPUB(addresses, false); int ret = 0; try { if(jsonObject != null && jsonObject.has("addresses")) { JSONArray addressArray = (JSONArray)jsonObject.get("addresses"); JSONObject addrObj = null; for(int i = 0; i < addressArray.length(); i++) { addrObj = (JSONObject)addressArray.get(i); int nbTx = 0; String addr = null; String pcode = null; int idx = -1; if(addrObj.has("address")) { addr = (String)addrObj.get("address"); pcode = BIP47Meta.getInstance().getPCode4Addr(addr); idx = BIP47Meta.getInstance().getIdx4Addr(addr); if(addrObj.has("n_tx")) { nbTx = addrObj.getInt("n_tx"); if(nbTx > 0) { int stored = BIP47Meta.getInstance().getOutgoingIdx(pcode); if(idx >= stored) { // Log.i("APIFactory", "sync send idx:" + idx + ", " + addr); BIP47Meta.getInstance().setOutgoingIdx(pcode, idx + 1); } ret++; } } } } } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return ret; } public long getXpubBalance() { return xpub_balance - BlockedUTXO.getInstance().getTotalValueBlocked(); } public void setXpubBalance(long value) { xpub_balance = value; } public HashMap<String,Long> getXpubAmounts() { return xpub_amounts; } public HashMap<String,List<Tx>> getXpubTxs() { return xpub_txs; } public HashMap<String, String> getUnspentPaths() { return unspentPaths; } public HashMap<String, Integer> getUnspentAccounts() { return unspentAccounts; } public HashMap<String, Integer> getUnspentBIP49() { return unspentBIP49; } public HashMap<String, Integer> getUnspentBIP84() { return unspentBIP84; } public List<UTXO> getUtxos(boolean filter) { List<UTXO> unspents = new ArrayList<UTXO>(); if(filter) { for(String key : utxos.keySet()) { UTXO u = new UTXO(); for(MyTransactionOutPoint out : utxos.get(key).getOutpoints()) { if(!BlockedUTXO.getInstance().contains(out.getTxHash().toString(), out.getTxOutputN())) { u.getOutpoints().add(out); } } if(u.getOutpoints().size() > 0) { unspents.add(u); } } } else { unspents.addAll(utxos.values()); } return unspents; } public void setUtxos(HashMap<String, UTXO> utxos) { APIFactory.utxos = utxos; } public synchronized List<Tx> getAllXpubTxs() { List<Tx> ret = new ArrayList<Tx>(); for(String key : xpub_txs.keySet()) { List<Tx> txs = xpub_txs.get(key); for(Tx tx : txs) { ret.add(tx); } } Collections.sort(ret, new TxMostRecentDateComparator()); return ret; } public synchronized UTXO getUnspentOutputsForSweep(String address) { String _url = SamouraiWallet.getInstance().isTestNet() ? WebUtil.SAMOURAI_API2_TESTNET : WebUtil.SAMOURAI_API2; try { String response = null; if(!TorUtil.getInstance(context).statusFromBroadcast()) { StringBuilder args = new StringBuilder(); args.append("active="); args.append(address); // Log.d("APIFactory", args.toString()); response = WebUtil.getInstance(context).postURL(_url + "unspent?", args.toString()); // Log.d("APIFactory", response); } else { HashMap<String,String> args = new HashMap<String,String>(); args.put("active", address); // Log.d("APIFactory", args.toString()); response = WebUtil.getInstance(context).tor_postURL(_url + "unspent", args); // Log.d("APIFactory", response); } return parseUnspentOutputsForSweep(response); } catch(Exception e) { e.printStackTrace(); } return null; } private synchronized UTXO parseUnspentOutputsForSweep(String unspents) { UTXO utxo = null; if(unspents != null) { try { JSONObject jsonObj = new JSONObject(unspents); if(jsonObj == null || !jsonObj.has("unspent_outputs")) { return null; } JSONArray utxoArray = jsonObj.getJSONArray("unspent_outputs"); if(utxoArray == null || utxoArray.length() == 0) { return null; } // Log.d("APIFactory", "unspents found:" + outputsRoot.size()); for (int i = 0; i < utxoArray.length(); i++) { JSONObject outDict = utxoArray.getJSONObject(i); byte[] hashBytes = Hex.decode((String)outDict.get("tx_hash")); Sha256Hash txHash = Sha256Hash.wrap(hashBytes); int txOutputN = ((Number)outDict.get("tx_output_n")).intValue(); BigInteger value = BigInteger.valueOf(((Number)outDict.get("value")).longValue()); String script = (String)outDict.get("script"); byte[] scriptBytes = Hex.decode(script); int confirmations = ((Number)outDict.get("confirmations")).intValue(); try { String address = null; if(Bech32Util.getInstance().isBech32Script(script)) { address = Bech32Util.getInstance().getAddressFromScript(script); Log.d("address parsed:", address); } else { address = new Script(scriptBytes).getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(); } // Construct the output MyTransactionOutPoint outPoint = new MyTransactionOutPoint(txHash, txOutputN, value, scriptBytes, address); outPoint.setConfirmations(confirmations); if(utxo == null) { utxo = new UTXO(); } utxo.getOutpoints().add(outPoint); } catch(Exception e) { ; } } } catch(JSONException je) { ; } } return utxo; } public static class TxMostRecentDateComparator implements Comparator<Tx> { public int compare(Tx t1, Tx t2) { final int BEFORE = -1; final int EQUAL = 0; final int AFTER = 1; int ret = 0; if(t1.getTS() > t2.getTS()) { ret = BEFORE; } else if(t1.getTS() < t2.getTS()) { ret = AFTER; } else { ret = EQUAL; } return ret; } } }
package com.samourai.wallet.api; import android.app.Activity; import android.app.AlertDialog; import android.content.Context; import android.content.DialogInterface; import android.net.Uri; import android.os.Handler; import android.os.Looper; import com.auth0.android.jwt.JWT; import com.samourai.wallet.BuildConfig; import com.samourai.wallet.JSONRPC.JSONRPC; import com.samourai.wallet.JSONRPC.TrustedNodeUtil; import com.samourai.wallet.SamouraiWallet; import com.samourai.wallet.bip47.BIP47Meta; import com.samourai.wallet.bip47.BIP47Util; import com.samourai.wallet.crypto.DecryptionException; import com.samourai.wallet.hd.HD_Address; import com.samourai.wallet.hd.HD_Wallet; import com.samourai.wallet.hd.HD_WalletFactory; import com.samourai.wallet.network.dojo.DojoUtil; import com.samourai.wallet.payload.PayloadUtil; 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.BlockedUTXO; import com.samourai.wallet.send.FeeUtil; import com.samourai.wallet.send.MyTransactionOutPoint; import com.samourai.wallet.send.RBFUtil; import com.samourai.wallet.send.SuggestedFee; import com.samourai.wallet.send.UTXO; import com.samourai.wallet.send.UTXOFactory; import com.samourai.wallet.tor.TorManager; import com.samourai.wallet.util.AddressFactory; import com.samourai.wallet.util.AppUtil; import com.samourai.wallet.util.FormatsUtil; import com.samourai.wallet.util.PrefsUtil; import com.samourai.wallet.util.SentToFromBIP47Util; import com.samourai.wallet.util.UTXOUtil; import com.samourai.wallet.util.WebUtil; import com.samourai.wallet.bip47.rpc.PaymentCode; import com.samourai.wallet.R; import com.samourai.wallet.whirlpool.WhirlpoolMeta; import com.samourai.wallet.util.LogUtil; import org.apache.commons.lang3.StringUtils; import org.bitcoinj.core.Address; import org.bitcoinj.core.AddressFormatException; import org.bitcoinj.core.ECKey; import org.bitcoinj.core.Sha256Hash; import org.bitcoinj.core.TransactionOutPoint; import org.bitcoinj.crypto.MnemonicException; import org.bitcoinj.script.Script; import org.bouncycastle.util.encoders.Base64; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.bouncycastle.util.encoders.Hex; import java.io.IOException; import java.math.BigInteger; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import io.reactivex.subjects.BehaviorSubject; import static com.samourai.wallet.util.LogUtil.debug; import static com.samourai.wallet.util.LogUtil.info; public class APIFactory { private static String APP_TOKEN = null; // API app token private static String ACCESS_TOKEN = null; // API access token private static long ACCESS_TOKEN_REFRESH = 300L; // in seconds private static long xpub_balance = 0L; private static long xpub_postmix_balance = 0L; private static HashMap<String, Long> xpub_amounts = null; private static HashMap<String,List<Tx>> xpub_txs = null; private static HashMap<String,Integer> unspentAccounts = null; private static HashMap<String,Integer> unspentBIP49 = null; private static HashMap<String,Integer> unspentBIP84 = null; private static HashMap<String,Integer> unspentBIP84PostMix = null; private static HashMap<String,String> unspentPaths = null; private static HashMap<String,UTXO> utxos = null; private static HashMap<String,UTXO> utxosPostMix = null; private static JSONObject utxoObj0 = null; private static JSONObject utxoObj1 = null; private static HashMap<String, Long> bip47_amounts = null; public boolean walletInit = false; public BehaviorSubject<Long> walletBalanceObserver = BehaviorSubject.create(); private static long latest_block_height = -1L; private static String latest_block_hash = null; private static APIFactory instance = null; private static Context context = null; private static AlertDialog alertDialog = null; private APIFactory() { walletBalanceObserver.onNext(0L); } public static APIFactory getInstance(Context ctx) { context = ctx; if(instance == null) { xpub_amounts = new HashMap<String, Long>(); xpub_txs = new HashMap<String,List<Tx>>(); xpub_balance = 0L; bip47_amounts = new HashMap<String, Long>(); unspentPaths = new HashMap<String, String>(); unspentAccounts = new HashMap<String, Integer>(); unspentBIP49 = new HashMap<String, Integer>(); unspentBIP84 = new HashMap<String, Integer>(); unspentBIP84PostMix = new HashMap<String, Integer>(); utxos = new HashMap<String, UTXO>(); utxosPostMix = new HashMap<String, UTXO>(); instance = new APIFactory(); } return instance; } public synchronized void reset() { xpub_balance = 0L; xpub_amounts.clear(); bip47_amounts.clear(); xpub_txs.clear(); unspentPaths = new HashMap<String, String>(); unspentAccounts = new HashMap<String, Integer>(); unspentBIP49 = new HashMap<String, Integer>(); unspentBIP84 = new HashMap<String, Integer>(); unspentBIP84PostMix = new HashMap<String, Integer>(); utxos = new HashMap<String, UTXO>(); utxosPostMix = new HashMap<String, UTXO>(); UTXOFactory.getInstance().clear(); } public String getAccessToken() { if(ACCESS_TOKEN == null && APIFactory.getInstance(context).APITokenRequired()) { getToken(true); } return DojoUtil.getInstance(context).getDojoParams() == null ? "" : ACCESS_TOKEN; } public void setAccessToken(String accessToken) { ACCESS_TOKEN = accessToken; } public void setAppToken(String token) { APP_TOKEN = token; } public String getAppToken() { if(APP_TOKEN != null) { return APP_TOKEN; } else { return new String(getXORKey()); } } public byte[] getXORKey() { if(APP_TOKEN != null) { return APP_TOKEN.getBytes(); } if(BuildConfig.XOR_1.length() > 0 && BuildConfig.XOR_2.length() > 0) { byte[] xorSegments0 = Base64.decode(BuildConfig.XOR_1); byte[] xorSegments1 = Base64.decode(BuildConfig.XOR_2); return xor(xorSegments0, xorSegments1); } else { return null; } } private byte[] xor(byte[] b0, byte[] b1) { byte[] ret = new byte[b0.length]; for(int i = 0; i < b0.length; i++){ ret[i] = (byte)(b0[i] ^ b1[i]); } return ret; } public long getAccessTokenRefresh() { return ACCESS_TOKEN_REFRESH; } public boolean stayingAlive() { if(!AppUtil.getInstance(context).isOfflineMode() && APITokenRequired()) { if(APIFactory.getInstance(context).getAccessToken() == null) { APIFactory.getInstance(context).getToken(false); } if(APIFactory.getInstance(context).getAccessToken() != null) { JWT jwt = new JWT(APIFactory.getInstance(context).getAccessToken()); if(jwt != null && jwt.isExpired(APIFactory.getInstance(context).getAccessTokenRefresh())) { if(APIFactory.getInstance(context).getToken(false)) { return true; } else { return false; } } } return false; } else { return true; } } public synchronized boolean APITokenRequired() { return DojoUtil.getInstance(context).getDojoParams() == null ? false : true; } public synchronized boolean getToken(boolean setupDojo) { if(!APITokenRequired()) { return true; } String _url = SamouraiWallet.getInstance().isTestNet() ? WebUtil.SAMOURAI_API2_TESTNET : WebUtil.SAMOURAI_API2; if(DojoUtil.getInstance(context).getDojoParams() != null || setupDojo) { _url = SamouraiWallet.getInstance().isTestNet() ? WebUtil.SAMOURAI_API2_TESTNET_TOR : WebUtil.SAMOURAI_API2_TOR; } debug("APIFactory", "getToken() url:" + _url); JSONObject jsonObject = null; try { String response = null; if(AppUtil.getInstance(context).isOfflineMode()) { return true; } else if(!TorManager.getInstance(context).isRequired()) { // use POST StringBuilder args = new StringBuilder(); args.append("apikey="); args.append(new String(getXORKey())); response = WebUtil.getInstance(context).postURL(_url + "auth/login?", args.toString()); info("APIFactory", "API token response:" + response); } else { HashMap<String,String> args = new HashMap<String,String>(); args.put("apikey", new String(getXORKey())); info("APIFactory", "API key (XOR):" + new String(getXORKey())); info("APIFactory", "API key url:" + _url); response = WebUtil.getInstance(context).tor_postURL(_url + "auth/login", args); info("APIFactory", "API token response:" + response); } try { jsonObject = new JSONObject(response); if(jsonObject != null && jsonObject.has("authorizations")) { JSONObject authObj = jsonObject.getJSONObject("authorizations"); if(authObj.has("access_token")) { info("APIFactory", "setting access token:" + authObj.getString("access_token")); setAccessToken(authObj.getString("access_token")); return true; } } } catch(JSONException je) { je.printStackTrace(); jsonObject = null; return false; } } catch(Exception e) { jsonObject = null; e.printStackTrace(); return false; } return true; } private synchronized JSONObject getXPUB(String[] xpubs, boolean parse) { String _url = WebUtil.getAPIUrl(context); JSONObject jsonObject = null; try { String response = null; if(AppUtil.getInstance(context).isOfflineMode()) { response = PayloadUtil.getInstance(context).deserializeMultiAddr().toString(); } else if(!TorManager.getInstance(context).isRequired()) { // use POST StringBuilder args = new StringBuilder(); args.append("active="); args.append(StringUtils.join(xpubs, URLEncoder.encode("|", "UTF-8"))); info("APIFactory", "XPUB:" + args.toString()); args.append("&at="); args.append(getAccessToken()); response = WebUtil.getInstance(context).postURL(_url + "multiaddr?", args.toString()); info("APIFactory", "XPUB response:" + response); } else { HashMap<String,String> args = new HashMap<String,String>(); args.put("active", StringUtils.join(xpubs, "|")); info("APIFactory", "XPUB:" + args.toString()); args.put("at", getAccessToken()); info("APIFactory", "XPUB access token:" + getAccessToken()); response = WebUtil.getInstance(context).tor_postURL(_url + "multiaddr", args); info("APIFactory", "XPUB response:" + response); } try { jsonObject = new JSONObject(response); if(!parse) { return jsonObject; } xpub_txs.put(xpubs[0], new ArrayList<Tx>()); parseXPUB(jsonObject); xpub_amounts.put(HD_WalletFactory.getInstance(context).get().getAccount(0).xpubstr(), xpub_balance - BlockedUTXO.getInstance().getTotalValueBlocked0()); walletBalanceObserver.onNext( xpub_balance - BlockedUTXO.getInstance().getTotalValueBlocked0()); } catch(JSONException je) { je.printStackTrace(); jsonObject = null; } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } private synchronized JSONObject registerXPUB(String xpub, int purpose, String tag) { String _url = WebUtil.getAPIUrl(context); JSONObject jsonObject = null; try { String response = null; if(!TorManager.getInstance(context).isRequired()) { // use POST StringBuilder args = new StringBuilder(); args.append("xpub="); args.append(xpub); args.append("&type="); if(PrefsUtil.getInstance(context).getValue(PrefsUtil.IS_RESTORE, false) == true) { args.append("restore"); } else { args.append("new"); } if(purpose == 49) { args.append("&segwit="); args.append("bip49"); } else if(purpose == 84) { args.append("&segwit="); args.append("bip84"); } else { ; } info("APIFactory", "XPUB:" + args.toString()); args.append("&at="); args.append(getAccessToken()); response = WebUtil.getInstance(context).postURL(_url + "xpub?", args.toString()); info("APIFactory", "XPUB response:" + response); } else { HashMap<String,String> args = new HashMap<String,String>(); args.put("xpub", xpub); if(PrefsUtil.getInstance(context).getValue(PrefsUtil.IS_RESTORE, false) == true) { args.put("type", "restore"); } else { args.put("type", "new"); } if(purpose == 49) { args.put("segwit", "bip49"); } else if(purpose == 84) { args.put("segwit", "bip84"); } else { ; } info("APIFactory", "XPUB:" + args.toString()); args.put("at", getAccessToken()); response = WebUtil.getInstance(context).tor_postURL(_url + "xpub", args); info("APIFactory", "XPUB response:" + response); } try { jsonObject = new JSONObject(response); info("APIFactory", "XPUB response:" + jsonObject.toString()); if(jsonObject.has("status") && jsonObject.getString("status").equals("ok")) { if(tag != null) { PrefsUtil.getInstance(context).setValue(tag, true); if(tag.equals(PrefsUtil.XPUBPOSTREG)) { PrefsUtil.getInstance(context).removeValue(PrefsUtil.IS_RESTORE); } } else if(purpose == 44) { PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB44REG, true); } else if(purpose == 49) { PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB49REG, true); } else if(purpose == 84) { PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB84REG, true); } else { ; } } } catch(JSONException je) { je.printStackTrace(); jsonObject = null; } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } private synchronized boolean parseXPUB(JSONObject jsonObject) throws JSONException { if(jsonObject != null) { HashMap<String,Integer> pubkeys = new HashMap<String,Integer>(); if(jsonObject.has("wallet")) { JSONObject walletObj = (JSONObject)jsonObject.get("wallet"); if(walletObj.has("final_balance")) { xpub_balance = walletObj.getLong("final_balance"); debug("APIFactory", "xpub_balance:" + xpub_balance); } } if(jsonObject.has("info")) { JSONObject infoObj = (JSONObject)jsonObject.get("info"); if(infoObj.has("latest_block")) { JSONObject blockObj = (JSONObject)infoObj.get("latest_block"); if(blockObj.has("height")) { latest_block_height = blockObj.getLong("height"); } if(blockObj.has("hash")) { latest_block_hash = blockObj.getString("hash"); } } } if(jsonObject.has("addresses")) { JSONArray addressesArray = (JSONArray)jsonObject.get("addresses"); JSONObject addrObj = null; for(int i = 0; i < addressesArray.length(); i++) { addrObj = (JSONObject)addressesArray.get(i); if(addrObj != null && addrObj.has("final_balance") && addrObj.has("address")) { if(FormatsUtil.getInstance().isValidXpub((String)addrObj.get("address"))) { xpub_amounts.put((String)addrObj.get("address"), addrObj.getLong("final_balance")); if(addrObj.getString("address").equals(BIP84Util.getInstance(context).getWallet().getAccount(0).xpubstr()) || addrObj.getString("address").equals(BIP84Util.getInstance(context).getWallet().getAccount(0).zpubstr())) { AddressFactory.getInstance().setHighestBIP84ReceiveIdx(addrObj.has("account_index") ? addrObj.getInt("account_index") : 0); AddressFactory.getInstance().setHighestBIP84ChangeIdx(addrObj.has("change_index") ? addrObj.getInt("change_index") : 0); BIP84Util.getInstance(context).getWallet().getAccount(0).getChain(0).setAddrIdx(addrObj.has("account_index") ? addrObj.getInt("account_index") : 0); BIP84Util.getInstance(context).getWallet().getAccount(0).getChain(1).setAddrIdx(addrObj.has("change_index") ? addrObj.getInt("change_index") : 0); } else if(addrObj.getString("address").equals(BIP49Util.getInstance(context).getWallet().getAccount(0).xpubstr()) || addrObj.getString("address").equals(BIP49Util.getInstance(context).getWallet().getAccount(0).ypubstr())) { AddressFactory.getInstance().setHighestBIP49ReceiveIdx(addrObj.has("account_index") ? addrObj.getInt("account_index") : 0); AddressFactory.getInstance().setHighestBIP49ChangeIdx(addrObj.has("change_index") ? addrObj.getInt("change_index") : 0); BIP49Util.getInstance(context).getWallet().getAccount(0).getChain(0).setAddrIdx(addrObj.has("account_index") ? addrObj.getInt("account_index") : 0); BIP49Util.getInstance(context).getWallet().getAccount(0).getChain(1).setAddrIdx(addrObj.has("change_index") ? addrObj.getInt("change_index") : 0); } else if(AddressFactory.getInstance().xpub2account().get((String) addrObj.get("address")) != null) { AddressFactory.getInstance().setHighestTxReceiveIdx(AddressFactory.getInstance().xpub2account().get((String) addrObj.get("address")), addrObj.has("account_index") ? addrObj.getInt("account_index") : 0); AddressFactory.getInstance().setHighestTxChangeIdx(AddressFactory.getInstance().xpub2account().get((String)addrObj.get("address")), addrObj.has("change_index") ? addrObj.getInt("change_index") : 0); try { HD_WalletFactory.getInstance(context).get().getAccount(0).getChain(0).setAddrIdx(addrObj.has("account_index") ? addrObj.getInt("account_index") : 0); HD_WalletFactory.getInstance(context).get().getAccount(0).getChain(1).setAddrIdx(addrObj.has("change_index") ? addrObj.getInt("change_index") : 0); } catch(IOException | MnemonicException.MnemonicLengthException e) { ; } } else { ; } } else { long amount = 0L; String addr = null; addr = (String)addrObj.get("address"); amount = addrObj.getLong("final_balance"); String pcode = BIP47Meta.getInstance().getPCode4Addr(addr); if(addr != null && addr.length() > 0 && pcode != null && pcode.length() > 0 && BIP47Meta.getInstance().getIdx4Addr(addr) != null) { int idx = BIP47Meta.getInstance().getIdx4Addr(addr); if(amount > 0L) { BIP47Meta.getInstance().addUnspent(pcode, idx); if(idx > BIP47Meta.getInstance().getIncomingIdx(pcode)) { BIP47Meta.getInstance().setIncomingIdx(pcode, idx); } } else { if(addrObj.has("pubkey")) { String pubkey = addrObj.getString("pubkey"); if(pubkeys.containsKey(pubkey)) { int count = pubkeys.get(pubkey); count++; if(count == 3) { BIP47Meta.getInstance().removeUnspent(pcode, Integer.valueOf(idx)); } else { pubkeys.put(pubkey, count + 1); } } else { pubkeys.put(pubkey, 1); } } else { BIP47Meta.getInstance().removeUnspent(pcode, Integer.valueOf(idx)); } } if(addr != null) { bip47_amounts.put(addr, amount); } } } } } } if(jsonObject.has("txs")) { List<String> seenHashes = new ArrayList<String>(); JSONArray txArray = (JSONArray)jsonObject.get("txs"); JSONObject txObj = null; for(int i = 0; i < txArray.length(); i++) { txObj = (JSONObject)txArray.get(i); long height = 0L; long amount = 0L; long ts = 0L; String hash = null; String addr = null; String _addr = null; if(txObj.has("block_height")) { height = txObj.getLong("block_height"); } else { height = -1L; // 0 confirmations } if(txObj.has("hash")) { hash = (String)txObj.get("hash"); } if(txObj.has("result")) { amount = txObj.getLong("result"); } if(txObj.has("time")) { ts = txObj.getLong("time"); } if(!seenHashes.contains(hash)) { seenHashes.add(hash); } if(txObj.has("inputs")) { JSONArray inputArray = (JSONArray)txObj.get("inputs"); JSONObject inputObj = null; for(int j = 0; j < inputArray.length(); j++) { inputObj = (JSONObject)inputArray.get(j); if(inputObj.has("prev_out")) { JSONObject prevOutObj = (JSONObject)inputObj.get("prev_out"); if(prevOutObj.has("xpub")) { JSONObject xpubObj = (JSONObject)prevOutObj.get("xpub"); addr = (String)xpubObj.get("m"); } else if(prevOutObj.has("addr") && BIP47Meta.getInstance().getPCode4Addr((String)prevOutObj.get("addr")) != null) { _addr = (String)prevOutObj.get("addr"); } else { _addr = (String)prevOutObj.get("addr"); } } } } if(txObj.has("out")) { JSONArray outArray = (JSONArray)txObj.get("out"); JSONObject outObj = null; for(int j = 0; j < outArray.length(); j++) { outObj = (JSONObject)outArray.get(j); if(outObj.has("xpub")) { JSONObject xpubObj = (JSONObject)outObj.get("xpub"); addr = (String)xpubObj.get("m"); } else { _addr = (String)outObj.get("addr"); } } } if(addr != null || _addr != null) { if(addr == null) { addr = _addr; } Tx tx = new Tx(hash, addr, amount, ts, (latest_block_height > 0L && height > 0L) ? (latest_block_height - height) + 1 : 0); if(SentToFromBIP47Util.getInstance().getByHash(hash) != null) { tx.setPaymentCode(SentToFromBIP47Util.getInstance().getByHash(hash)); } if(BIP47Meta.getInstance().getPCode4Addr(addr) != null) { tx.setPaymentCode(BIP47Meta.getInstance().getPCode4Addr(addr)); } if(!xpub_txs.containsKey(addr)) { xpub_txs.put(addr, new ArrayList<Tx>()); } if(FormatsUtil.getInstance().isValidXpub(addr)) { xpub_txs.get(addr).add(tx); } else { xpub_txs.get(AddressFactory.getInstance().account2xpub().get(0)).add(tx); } if(height > 0L) { RBFUtil.getInstance().remove(hash); } } } List<String> hashesSentToViaBIP47 = SentToFromBIP47Util.getInstance().getAllHashes(); if(hashesSentToViaBIP47.size() > 0) { for(String s : hashesSentToViaBIP47) { if(!seenHashes.contains(s)) { SentToFromBIP47Util.getInstance().removeHash(s); } } } } try { PayloadUtil.getInstance(context).serializeMultiAddr(jsonObject); } catch(IOException | DecryptionException e) { ; } return true; } return false; } /* public synchronized JSONObject deleteXPUB(String xpub, boolean bip49) { String _url = SamouraiWallet.getInstance().isTestNet() ? WebUtil.SAMOURAI_API2_TESTNET : WebUtil.SAMOURAI_API2; JSONObject jsonObject = null; try { String response = null; ECKey ecKey = null; if(AddressFactory.getInstance(context).xpub2account().get(xpub) != null || xpub.equals(BIP49Util.getInstance(context).getWallet().getAccount(0).ypubstr())) { HD_Address addr = null; if(bip49) { addr = BIP49Util.getInstance(context).getWallet().getAccountAt(0).getChange().getAddressAt(0); } else { addr = HD_WalletFactory.getInstance(context).get().getAccount(0).getChain(AddressFactory.CHANGE_CHAIN).getAddressAt(0); } ecKey = addr.getECKey(); if(ecKey != null && ecKey.hasPrivKey()) { String sig = ecKey.signMessage(xpub); String address = null; if(bip49) { SegwitAddress segwitAddress = new SegwitAddress(ecKey.getPubKey(), SamouraiWallet.getInstance().getCurrentNetworkParams()); address = segwitAddress.getAddressAsString(); } else { address = ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(); } if(!TorUtil.getInstance(context).statusFromBroadcast()) { StringBuilder args = new StringBuilder(); args.append("message="); args.append(xpub); args.append("address="); args.append(address); args.append("&signature="); args.append(Uri.encode(sig)); info("APIFactory", "delete XPUB:" + args.toString()); response = WebUtil.getInstance(context).deleteURL(_url + "delete/" + xpub, args.toString()); info("APIFactory", "delete XPUB response:" + response); } else { HashMap<String,String> args = new HashMap<String,String>(); args.put("message", xpub); args.put("address", address); args.put("signature", Uri.encode(sig)); info("APIFactory", "delete XPUB:" + args.toString()); response = WebUtil.getInstance(context).tor_deleteURL(_url + "delete", args); info("APIFactory", "delete XPUB response:" + response); } try { jsonObject = new JSONObject(response); if(jsonObject.has("status") && jsonObject.getString("status").equals("ok")) { ; } } catch(JSONException je) { je.printStackTrace(); jsonObject = null; } } } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } */ public synchronized JSONObject lockXPUB(String xpub, int purpose, String tag) { String _url = WebUtil.getAPIUrl(context); JSONObject jsonObject = null; try { String response = null; ECKey ecKey = null; if(AddressFactory.getInstance(context).xpub2account().get(xpub) != null || xpub.equals(BIP49Util.getInstance(context).getWallet().getAccount(0).ypubstr()) || xpub.equals(BIP84Util.getInstance(context).getWallet().getAccount(0).zpubstr()) || xpub.equals(BIP84Util.getInstance(context).getWallet().getAccountAt(WhirlpoolMeta.getInstance(context).getWhirlpoolPremixAccount()).zpubstr()) || xpub.equals(BIP84Util.getInstance(context).getWallet().getAccountAt(WhirlpoolMeta.getInstance(context).getWhirlpoolPostmix()).zpubstr()) ) { HD_Address addr = null; switch(purpose) { case 49: addr = BIP49Util.getInstance(context).getWallet().getAccountAt(0).getChange().getAddressAt(0); break; case 84: if(tag != null && tag.equals(PrefsUtil.XPUBPRELOCK)) { addr = BIP84Util.getInstance(context).getWallet().getAccountAt(WhirlpoolMeta.getInstance(context).getWhirlpoolPremixAccount()).getChange().getAddressAt(0); } else if(tag != null && tag.equals(PrefsUtil.XPUBPOSTLOCK)) { addr = BIP84Util.getInstance(context).getWallet().getAccountAt(WhirlpoolMeta.getInstance(context).getWhirlpoolPostmix()).getChange().getAddressAt(0); } else { addr = BIP84Util.getInstance(context).getWallet().getAccountAt(0).getChange().getAddressAt(0); } break; default: addr = HD_WalletFactory.getInstance(context).get().getAccount(0).getChain(AddressFactory.CHANGE_CHAIN).getAddressAt(0); break; } ecKey = addr.getECKey(); if(ecKey != null && ecKey.hasPrivKey()) { String sig = ecKey.signMessage("lock"); String address = null; switch(purpose) { case 49: SegwitAddress p2shp2wpkh = new SegwitAddress(ecKey.getPubKey(), SamouraiWallet.getInstance().getCurrentNetworkParams()); address = p2shp2wpkh.getAddressAsString(); break; case 84: SegwitAddress segwitAddress = new SegwitAddress(ecKey.getPubKey(), SamouraiWallet.getInstance().getCurrentNetworkParams()); address = segwitAddress.getBech32AsString(); break; default: address = ecKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(); break; } if(!TorManager.getInstance(context).isRequired()) { StringBuilder args = new StringBuilder(); args.append("address="); args.append(address); args.append("&signature="); args.append(Uri.encode(sig)); args.append("&message="); args.append("lock"); // info("APIFactory", "lock XPUB:" + args.toString()); args.append("&at="); args.append(getAccessToken()); response = WebUtil.getInstance(context).postURL(_url + "xpub/" + xpub + "/lock/", args.toString()); // info("APIFactory", "lock XPUB response:" + response); } else { HashMap<String,String> args = new HashMap<String,String>(); args.put("address", address); // args.put("signature", Uri.encode(sig)); args.put("signature", sig); args.put("message", "lock"); args.put("at", getAccessToken()); info("APIFactory", "lock XPUB:" + _url); info("APIFactory", "lock XPUB:" + args.toString()); response = WebUtil.getInstance(context).tor_postURL(_url + "xpub/" + xpub + "/lock/", args); info("APIFactory", "lock XPUB response:" + response); } try { jsonObject = new JSONObject(response); if(jsonObject.has("status") && jsonObject.getString("status").equals("ok")) { if(tag != null) { PrefsUtil.getInstance(context).setValue(tag, true); } else { switch(purpose) { case 49: PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB49LOCK, true); break; case 84: PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB84LOCK, true); break; default: PrefsUtil.getInstance(context).setValue(PrefsUtil.XPUB44LOCK, true); break; } } } } catch(JSONException je) { je.printStackTrace(); jsonObject = null; } } } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } public long getLatestBlockHeight() { return latest_block_height; } public String getLatestBlockHash() { return latest_block_hash; } public JSONObject getNotifTx(String hash, String addr) { String _url = WebUtil.getAPIUrl(context); JSONObject jsonObject = null; try { StringBuilder url = new StringBuilder(_url); url.append("tx/"); url.append(hash); url.append("?fees=1"); // info("APIFactory", "Notif tx:" + url.toString()); url.append("&at="); url.append(getAccessToken()); String response = WebUtil.getInstance(null).getURL(url.toString()); // info("APIFactory", "Notif tx:" + response); try { jsonObject = new JSONObject(response); parseNotifTx(jsonObject, addr, hash); } catch(JSONException je) { je.printStackTrace(); jsonObject = null; } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } public JSONObject getNotifAddress(String addr) { String _url = SamouraiWallet.getInstance().isTestNet() ? WebUtil.SAMOURAI_API2_TESTNET : WebUtil.SAMOURAI_API2; JSONObject jsonObject = null; try { StringBuilder url = new StringBuilder(_url); url.append("multiaddr?active="); url.append(addr); // info("APIFactory", "Notif address:" + url.toString()); url.append("&at="); url.append(getAccessToken()); String response = WebUtil.getInstance(null).getURL(url.toString()); // info("APIFactory", "Notif address:" + response); try { jsonObject = new JSONObject(response); parseNotifAddress(jsonObject, addr); } catch(JSONException je) { je.printStackTrace(); jsonObject = null; } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } public void parseNotifAddress(JSONObject jsonObject, String addr) throws JSONException { if(jsonObject != null && jsonObject.has("txs")) { JSONArray txArray = jsonObject.getJSONArray("txs"); JSONObject txObj = null; for(int i = 0; i < txArray.length(); i++) { txObj = (JSONObject)txArray.get(i); if(!txObj.has("block_height") || (txObj.has("block_height") && txObj.getLong("block_height") < 1L)) { return; } String hash = null; if(txObj.has("hash")) { hash = (String)txObj.get("hash"); if(BIP47Meta.getInstance().getIncomingStatus(hash) == null) { getNotifTx(hash, addr); } } } } } public void parseNotifTx(JSONObject jsonObject, String addr, String hash) throws JSONException { info("APIFactory", "notif address:" + addr); info("APIFactory", "hash:" + hash); if(jsonObject != null) { byte[] mask = null; byte[] payload = null; PaymentCode pcode = null; if(jsonObject.has("inputs")) { JSONArray inArray = (JSONArray)jsonObject.get("inputs"); if(inArray.length() > 0) { JSONObject objInput = (JSONObject)inArray.get(0); byte[] pubkey = null; String strScript = objInput.getString("sig"); info("APIFactory", "scriptsig:" + strScript); if((strScript == null || strScript.length() == 0 || strScript.startsWith("160014")) && objInput.has("witness")) { JSONArray witnessArray = (JSONArray)objInput.get("witness"); if(witnessArray.length() == 2) { pubkey = Hex.decode((String)witnessArray.get(1)); } } else { Script script = new Script(Hex.decode(strScript)); info("APIFactory", "pubkey from script:" + Hex.toHexString(script.getPubKey())); pubkey = script.getPubKey(); } ECKey pKey = new ECKey(null, pubkey, true); info("APIFactory", "address from script:" + pKey.toAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString()); // info("APIFactory", "uncompressed public key from script:" + Hex.toHexString(pKey.decompress().getPubKey())); if(((JSONObject)inArray.get(0)).has("outpoint")) { JSONObject received_from = ((JSONObject) inArray.get(0)).getJSONObject("outpoint"); String strHash = received_from.getString("txid"); int idx = received_from.getInt("vout"); byte[] hashBytes = Hex.decode(strHash); Sha256Hash txHash = new Sha256Hash(hashBytes); TransactionOutPoint outPoint = new TransactionOutPoint(SamouraiWallet.getInstance().getCurrentNetworkParams(), idx, txHash); byte[] outpoint = outPoint.bitcoinSerialize(); info("APIFactory", "outpoint:" + Hex.toHexString(outpoint)); try { mask = BIP47Util.getInstance(context).getIncomingMask(pubkey, outpoint); info("APIFactory", "mask:" + Hex.toHexString(mask)); } catch(Exception e) { e.printStackTrace(); } } } } if(jsonObject.has("outputs")) { JSONArray outArray = (JSONArray)jsonObject.get("outputs"); JSONObject outObj = null; boolean isIncoming = false; String _addr = null; String script = null; String op_return = null; for(int j = 0; j < outArray.length(); j++) { outObj = (JSONObject)outArray.get(j); if(outObj.has("address")) { _addr = outObj.getString("address"); if(addr.equals(_addr)) { isIncoming = true; } } if(outObj.has("scriptpubkey")) { script = outObj.getString("scriptpubkey"); if(script.startsWith("6a4c50")) { op_return = script; } } } if(isIncoming && op_return != null && op_return.startsWith("6a4c50")) { payload = Hex.decode(op_return.substring(6)); } } if(mask != null && payload != null) { try { byte[] xlat_payload = PaymentCode.blind(payload, mask); info("APIFactory", "xlat_payload:" + Hex.toHexString(xlat_payload)); pcode = new PaymentCode(xlat_payload); info("APIFactory", "incoming payment code:" + pcode.toString()); if(!pcode.toString().equals(BIP47Util.getInstance(context).getPaymentCode().toString()) && pcode.isValid() && !BIP47Meta.getInstance().incomingExists(pcode.toString())) { BIP47Meta.getInstance().setLabel(pcode.toString(), ""); BIP47Meta.getInstance().setIncomingStatus(hash); } } catch(AddressFormatException afe) { afe.printStackTrace(); } } // get receiving addresses for spends from decoded payment code if(pcode != null) { try { // initial lookup for(int i = 0; i < BIP47Meta.INCOMING_LOOKAHEAD; i++) { info("APIFactory", "receive from " + i + ":" + BIP47Util.getInstance(context).getReceivePubKey(pcode, i)); BIP47Meta.getInstance().getIdx4AddrLookup().put(BIP47Util.getInstance(context).getReceivePubKey(pcode, i), i); BIP47Meta.getInstance().getPCode4AddrLookup().put(BIP47Util.getInstance(context).getReceivePubKey(pcode, i), pcode.toString()); } } catch(Exception e) { ; } } } } public synchronized int getNotifTxConfirmations(String hash) { String _url = WebUtil.getAPIUrl(context); // info("APIFactory", "Notif tx:" + hash); JSONObject jsonObject = null; try { StringBuilder url = new StringBuilder(_url); url.append("tx/"); url.append(hash); url.append("?fees=1"); // info("APIFactory", "Notif tx:" + url.toString()); url.append("&at="); url.append(getAccessToken()); String response = WebUtil.getInstance(null).getURL(url.toString()); // info("APIFactory", "Notif tx:" + response); jsonObject = new JSONObject(response); // info("APIFactory", "Notif tx json:" + jsonObject.toString()); return parseNotifTx(jsonObject); } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return 0; } public synchronized int parseNotifTx(JSONObject jsonObject) throws JSONException { int cf = 0; if(jsonObject != null && jsonObject.has("block") && jsonObject.getJSONObject("block").has("height")) { long latestBlockHeght = getLatestBlockHeight(); long height = jsonObject.getJSONObject("block").getLong("height"); cf = (int)((latestBlockHeght - height) + 1); if(cf < 0) { cf = 0; } } return cf; } public synchronized JSONObject getUnspentOutputs(String[] xpubs) { String _url = WebUtil.getAPIUrl(context); JSONObject jsonObject = null; String response = null; try { if(AppUtil.getInstance(context).isOfflineMode()) { response = PayloadUtil.getInstance(context).deserializeUTXO().toString(); } else if(!TorManager.getInstance(context).isRequired()) { StringBuilder args = new StringBuilder(); args.append("active="); args.append(StringUtils.join(xpubs, URLEncoder.encode("|", "UTF-8"))); debug("APIFactory", "UTXO args:" + args.toString()); args.append("&at="); args.append(getAccessToken()); response = WebUtil.getInstance(context).postURL(_url + "unspent?", args.toString()); debug("APIFactory", "UTXO:" + response); } else { HashMap<String,String> args = new HashMap<String,String>(); args.put("active", StringUtils.join(xpubs, "|")); args.put("at", getAccessToken()); response = WebUtil.getInstance(context).tor_postURL(_url + "unspent", args); } parseUnspentOutputs(response); } catch(Exception e) { jsonObject = null; e.printStackTrace(); } if(!AppUtil.getInstance(context).isOfflineMode()) { try { jsonObject = new JSONObject(response); } catch(JSONException je) { ; } } return jsonObject; } private synchronized boolean parseUnspentOutputs(String unspents) { if(unspents != null) { try { JSONObject jsonObj = new JSONObject(unspents); if(jsonObj == null || !jsonObj.has("unspent_outputs")) { return false; } JSONArray utxoArray = jsonObj.getJSONArray("unspent_outputs"); if(utxoArray == null || utxoArray.length() == 0) { return false; } utxos.clear(); for (int i = 0; i < utxoArray.length(); i++) { JSONObject outDict = utxoArray.getJSONObject(i); byte[] hashBytes = Hex.decode((String)outDict.get("tx_hash")); Sha256Hash txHash = Sha256Hash.wrap(hashBytes); int txOutputN = ((Number)outDict.get("tx_output_n")).intValue(); BigInteger value = BigInteger.valueOf(((Number)outDict.get("value")).longValue()); String script = (String)outDict.get("script"); byte[] scriptBytes = Hex.decode(script); int confirmations = ((Number)outDict.get("confirmations")).intValue(); String path = null; try { String address = null; if(Bech32Util.getInstance().isBech32Script(script)) { address = Bech32Util.getInstance().getAddressFromScript(script); } else { address = new Script(scriptBytes).getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(); } if(outDict.has("xpub")) { JSONObject xpubObj = (JSONObject)outDict.get("xpub"); path = (String)xpubObj.get("path"); String m = (String)xpubObj.get("m"); unspentPaths.put(address, path); if(m.equals(BIP49Util.getInstance(context).getWallet().getAccount(0).xpubstr())) { unspentBIP49.put(address, 0); // assume account 0 } else if(m.equals(BIP84Util.getInstance(context).getWallet().getAccount(0).xpubstr())) { unspentBIP84.put(address, 0); // assume account 0 } else { unspentAccounts.put(address, AddressFactory.getInstance(context).xpub2account().get(m)); } } else if(outDict.has("pubkey")) { int idx = BIP47Meta.getInstance().getIdx4AddrLookup().get(outDict.getString("pubkey")); BIP47Meta.getInstance().getIdx4AddrLookup().put(address, idx); String pcode = BIP47Meta.getInstance().getPCode4AddrLookup().get(outDict.getString("pubkey")); BIP47Meta.getInstance().getPCode4AddrLookup().put(address, pcode); } else { ; } // Construct the output MyTransactionOutPoint outPoint = new MyTransactionOutPoint(txHash, txOutputN, value, scriptBytes, address); outPoint.setConfirmations(confirmations); if(utxos.containsKey(script)) { utxos.get(script).getOutpoints().add(outPoint); } else { UTXO utxo = new UTXO(); utxo.getOutpoints().add(outPoint); utxo.setPath(path); utxos.put(script, utxo); } if(!BlockedUTXO.getInstance().contains(txHash.toString(), txOutputN)) { if(Bech32Util.getInstance().isBech32Script(script)) { UTXOFactory.getInstance().addP2WPKH(script, utxos.get(script)); } else if(Address.fromBase58(SamouraiWallet.getInstance().getCurrentNetworkParams(), address).isP2SHAddress()) { UTXOFactory.getInstance().addP2SH_P2WPKH(script, utxos.get(script)); } else { UTXOFactory.getInstance().addP2PKH(script, utxos.get(script)); } } } catch(Exception e) { ; } } return true; } catch(JSONException je) { ; } } return false; } public synchronized JSONObject getAddressInfo(String addr) { return getXPUB(new String[] { addr }, false); } public synchronized JSONObject getTxInfo(String hash) { String _url = WebUtil.getAPIUrl(context); JSONObject jsonObject = null; try { StringBuilder url = new StringBuilder(_url); url.append("tx/"); url.append(hash); url.append("?fees=true"); url.append("&at="); url.append(getAccessToken()); String response = WebUtil.getInstance(context).getURL(url.toString()); jsonObject = new JSONObject(response); } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } public synchronized JSONObject getBlockHeader(String hash) { String _url = WebUtil.getAPIUrl(context); JSONObject jsonObject = null; try { StringBuilder url = new StringBuilder(_url); url.append("header/"); url.append(hash); url.append("?at="); url.append(getAccessToken()); String response = WebUtil.getInstance(context).getURL(url.toString()); jsonObject = new JSONObject(response); } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } public synchronized JSONObject getDynamicFees() { JSONObject jsonObject = null; try { int sel = PrefsUtil.getInstance(context).getValue(PrefsUtil.FEE_PROVIDER_SEL, 0); if(sel == 1) { int[] blocks = new int[] { 2, 6, 24 }; List<SuggestedFee> suggestedFees = new ArrayList<SuggestedFee>(); JSONRPC jsonrpc = new JSONRPC(TrustedNodeUtil.getInstance().getUser(), TrustedNodeUtil.getInstance().getPassword(), TrustedNodeUtil.getInstance().getNode(), TrustedNodeUtil.getInstance().getPort()); for(int i = 0; i < blocks.length; i++) { JSONObject feeObj = jsonrpc.getFeeEstimate(blocks[i]); if(feeObj != null && feeObj.has("result")) { double fee = feeObj.getDouble("result"); SuggestedFee suggestedFee = new SuggestedFee(); suggestedFee.setDefaultPerKB(BigInteger.valueOf((long)(fee * 1e8))); suggestedFee.setStressed(false); suggestedFee.setOK(true); suggestedFees.add(suggestedFee); } } if(suggestedFees.size() > 0) { FeeUtil.getInstance().setEstimatedFees(suggestedFees); } } else { String _url = WebUtil.getAPIUrl(context); // info("APIFactory", "Dynamic fees:" + url.toString()); String response = null; if(!AppUtil.getInstance(context).isOfflineMode()) { response = WebUtil.getInstance(null).getURL(_url + "fees" + "?at=" + getAccessToken()); } else { response = PayloadUtil.getInstance(context).deserializeFees().toString(); } // info("APIFactory", "Dynamic fees response:" + response); try { jsonObject = new JSONObject(response); parseDynamicFees_bitcoind(jsonObject); } catch(JSONException je) { je.printStackTrace(); jsonObject = null; } } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } private synchronized boolean parseDynamicFees_bitcoind(JSONObject jsonObject) throws JSONException { if(jsonObject != null) { // bitcoind List<SuggestedFee> suggestedFees = new ArrayList<SuggestedFee>(); if(jsonObject.has("2")) { long fee = jsonObject.getInt("2"); SuggestedFee suggestedFee = new SuggestedFee(); suggestedFee.setDefaultPerKB(BigInteger.valueOf(fee * 1000L)); suggestedFee.setStressed(false); suggestedFee.setOK(true); suggestedFees.add(suggestedFee); } if(jsonObject.has("6")) { long fee = jsonObject.getInt("6"); SuggestedFee suggestedFee = new SuggestedFee(); suggestedFee.setDefaultPerKB(BigInteger.valueOf(fee * 1000L)); suggestedFee.setStressed(false); suggestedFee.setOK(true); suggestedFees.add(suggestedFee); } if(jsonObject.has("24")) { long fee = jsonObject.getInt("24"); SuggestedFee suggestedFee = new SuggestedFee(); suggestedFee.setDefaultPerKB(BigInteger.valueOf(fee * 1000L)); suggestedFee.setStressed(false); suggestedFee.setOK(true); suggestedFees.add(suggestedFee); } if(suggestedFees.size() > 0) { FeeUtil.getInstance().setEstimatedFees(suggestedFees); // debug("APIFactory", "high fee:" + FeeUtil.getInstance().getHighFee().getDefaultPerKB().toString()); // debug("APIFactory", "suggested fee:" + FeeUtil.getInstance().getSuggestedFee().getDefaultPerKB().toString()); // debug("APIFactory", "low fee:" + FeeUtil.getInstance().getLowFee().getDefaultPerKB().toString()); } try { PayloadUtil.getInstance(context).serializeFees(jsonObject); } catch(IOException | DecryptionException e) { ; } return true; } return false; } public synchronized void validateAPIThread() { final Handler handler = new Handler(); new Thread(new Runnable() { @Override public void run() { Looper.prepare(); if(!AppUtil.getInstance(context).isOfflineMode()) { try { String response = WebUtil.getInstance(context).getURL(WebUtil.SAMOURAI_API_CHECK); JSONObject jsonObject = new JSONObject(response); if(!jsonObject.has("process")) { showAlertDialog(context.getString(R.string.api_error), false); } } catch(Exception e) { showAlertDialog(context.getString(R.string.cannot_reach_api), false); } } else { showAlertDialog(context.getString(R.string.no_internet), false); } handler.post(new Runnable() { @Override public void run() { ; } }); Looper.loop(); } }).start(); } private void showAlertDialog(final String message, final boolean forceExit){ if (!((Activity) context).isFinishing()) { if(alertDialog != null)alertDialog.dismiss(); final AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setMessage(message); builder.setCancelable(false); if(!forceExit) { builder.setPositiveButton(R.string.retry, new DialogInterface.OnClickListener() { public void onClick(DialogInterface d, int id) { d.dismiss(); //Retry validateAPIThread(); } }); } builder.setNegativeButton(R.string.exit, new DialogInterface.OnClickListener() { public void onClick(DialogInterface d, int id) { d.dismiss(); ((Activity) context).finish(); } }); alertDialog = builder.create(); alertDialog.show(); } } public synchronized void initWallet() { info("APIFactory", "initWallet()"); initWalletAmounts(); } private synchronized void initWalletAmounts() { APIFactory.getInstance(context).reset(); List<String> addressStrings = new ArrayList<String>(); String[] s = null; try { if(PrefsUtil.getInstance(context).getValue(PrefsUtil.XPUB44REG, false) == false) { registerXPUB(HD_WalletFactory.getInstance(context).get().getAccount(0).xpubstr(), 44, null); } if(PrefsUtil.getInstance(context).getValue(PrefsUtil.XPUB49REG, false) == false) { registerXPUB(BIP49Util.getInstance(context).getWallet().getAccount(0).xpubstr(), 49, null); } if(PrefsUtil.getInstance(context).getValue(PrefsUtil.XPUB84REG, false) == false) { registerXPUB(BIP84Util.getInstance(context).getWallet().getAccount(0).xpubstr(), 84, null); } if(PrefsUtil.getInstance(context).getValue(PrefsUtil.XPUBPREREG, false) == false) { registerXPUB(BIP84Util.getInstance(context).getWallet().getAccountAt(WhirlpoolMeta.getInstance(context).getWhirlpoolPremixAccount()).xpubstr(), 84, PrefsUtil.XPUBPREREG); } if(PrefsUtil.getInstance(context).getValue(PrefsUtil.XPUBPOSTREG, false) == false) { registerXPUB(BIP84Util.getInstance(context).getWallet().getAccountAt(WhirlpoolMeta.getInstance(context).getWhirlpoolPostmix()).xpubstr(), 84, PrefsUtil.XPUBPOSTREG); } xpub_txs.put(HD_WalletFactory.getInstance(context).get().getAccount(0).xpubstr(), new ArrayList<Tx>()); addressStrings.addAll(Arrays.asList(BIP47Meta.getInstance().getIncomingAddresses(false))); for(String _s : Arrays.asList(BIP47Meta.getInstance().getIncomingLookAhead(context))) { if(!addressStrings.contains(_s)) { addressStrings.add(_s); } } for(String pcode : BIP47Meta.getInstance().getUnspentProviders()) { for(String addr : BIP47Meta.getInstance().getUnspentAddresses(context, pcode)) { if(!addressStrings.contains(addr)) { addressStrings.add(addr); } } } if(addressStrings.size() > 0) { s = addressStrings.toArray(new String[0]); // info("APIFactory", addressStrings.toString()); utxoObj0 = getUnspentOutputs(s); } debug("APIFactory", "addresses:" + addressStrings.toString()); HD_Wallet hdw = HD_WalletFactory.getInstance(context).get(); if(hdw != null && hdw.getXPUBs() != null) { String[] all = null; if(s != null && s.length > 0) { all = new String[hdw.getXPUBs().length + 2 + s.length]; all[0] = BIP49Util.getInstance(context).getWallet().getAccount(0).xpubstr(); all[1] = BIP84Util.getInstance(context).getWallet().getAccount(0).xpubstr(); System.arraycopy(hdw.getXPUBs(), 0, all, 2, hdw.getXPUBs().length); System.arraycopy(s, 0, all, hdw.getXPUBs().length + 2, s.length); } else { all = new String[hdw.getXPUBs().length + 2]; all[0] = BIP49Util.getInstance(context).getWallet().getAccount(0).xpubstr(); all[1] = BIP84Util.getInstance(context).getWallet().getAccount(0).xpubstr(); System.arraycopy(hdw.getXPUBs(), 0, all, 2, hdw.getXPUBs().length); } APIFactory.getInstance(context).getXPUB(all, true); String[] xs = new String[4]; xs[0] = HD_WalletFactory.getInstance(context).get().getAccount(0).xpubstr(); xs[1] = HD_WalletFactory.getInstance(context).get().getAccount(1).xpubstr(); xs[2] = BIP49Util.getInstance(context).getWallet().getAccount(0).xpubstr(); xs[3] = BIP84Util.getInstance(context).getWallet().getAccount(0).xpubstr(); utxoObj1 = getUnspentOutputs(xs); getDynamicFees(); } try { List<JSONObject> utxoObjs = new ArrayList<JSONObject>(); if(utxoObj0 != null) { utxoObjs.add(utxoObj0); } if(utxoObj1 != null) { utxoObjs.add(utxoObj1); } PayloadUtil.getInstance(context).serializeUTXO(utxoObjs); } catch(IOException | DecryptionException e) { ; } List<String> seenOutputs = new ArrayList<String>(); List<UTXO> _utxos = getUtxos(false); for(UTXO _u : _utxos) { for(MyTransactionOutPoint _o : _u.getOutpoints()) { seenOutputs.add(_o.getTxHash().toString() + "-" + _o.getTxOutputN()); } } for(String _s : BlockedUTXO.getInstance().getNotDustedUTXO()) { // debug("APIFactory", "not dusted:" + _s); if(!seenOutputs.contains(_s)) { BlockedUTXO.getInstance().removeNotDusted(_s); // debug("APIFactory", "not dusted removed:" + _s); } } for(String _s : BlockedUTXO.getInstance().getBlockedUTXO().keySet()) { // debug("APIFactory", "blocked:" + _s); if(!seenOutputs.contains(_s)) { BlockedUTXO.getInstance().remove(_s); // debug("APIFactory", "blocked removed:" + _s); } } // String strPreMix = BIP84Util.getInstance(context).getWallet().getAccountAt(WhirlpoolMeta.getInstance(context).getWhirlpoolPremixAccount()).xpubstr(); String strPostMix = BIP84Util.getInstance(context).getWallet().getAccountAt(WhirlpoolMeta.getInstance(context).getWhirlpoolPostmix()).xpubstr(); // JSONObject preMultiAddrObj = getRawXPUB(new String[] { strPreMix }); // JSONObject preUnspentObj = getRawUnspentOutputs(new String[] { strPreMix }); // debug("APIFactory", "pre-mix multi:" + preMultiAddrObj.toString()); // debug("APIFactory", "pre-mix unspent:" + preUnspentObj.toString()); // boolean parsedPreMultiAddr = parseMixXPUB(preMultiAddrObj); // boolean parsedPreUnspent = parsePostMixUnspentOutputs(preUnspentObj.toString()); JSONObject postMultiAddrObj = getRawXPUB(new String[] { strPostMix }); JSONObject postUnspentObj = getRawUnspentOutputs(new String[] { strPostMix }); debug("APIFactory", "post-mix multi:" + postMultiAddrObj.toString()); debug("APIFactory", "post-mix unspent:" + postUnspentObj.toString()); boolean parsedPostMultiAddr = parseMixXPUB(postMultiAddrObj); boolean parsedPostUnspent = parsePostMixUnspentOutputs(postUnspentObj.toString()); // debug("APIFactory", "post-mix multi:" + parsedPostMultiAddr); // debug("APIFactory", "post-mix unspent:" + parsedPostUnspent); // debug("APIFactory", "post-mix multi:" + getXpubPostMixBalance()); // debug("APIFactory", "post-mix unspent:" + getUtxosPostMix().size()); List<String> seenOutputsPostMix = new ArrayList<String>(); List<UTXO> _utxosPostMix = getUtxosPostMix(false); for(UTXO _u : _utxosPostMix) { for(MyTransactionOutPoint _o : _u.getOutpoints()) { seenOutputsPostMix.add(_o.getTxHash().toString() + "-" + _o.getTxOutputN()); } } for(String _s : UTXOUtil.getInstance().getTags().keySet()) { if(!seenOutputsPostMix.contains(_s) && !seenOutputs.contains(_s)) { UTXOUtil.getInstance().remove(_s); } } /* for(String _s : BlockedUTXO.getInstance().getNotDustedUTXO()) { // debug("APIFactory", "not dusted:" + _s); if(!seenOutputsPostMix.contains(_s)) { BlockedUTXO.getInstance().removeNotDusted(_s); // debug("APIFactory", "not dusted removed:" + _s); } } */ for(String _s : BlockedUTXO.getInstance().getBlockedUTXOPostMix().keySet()) { debug("APIFactory", "blocked post-mix:" + _s); if(!seenOutputsPostMix.contains(_s)) { BlockedUTXO.getInstance().removePostMix(_s); debug("APIFactory", "blocked removed:" + _s); } } } catch (IndexOutOfBoundsException ioobe) { ioobe.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } walletInit = true; } public synchronized int syncBIP47Incoming(String[] addresses) { JSONObject jsonObject = getXPUB(addresses, false); debug("APIFactory", "sync BIP47 incoming:" + jsonObject.toString()); int ret = 0; try { if(jsonObject != null && jsonObject.has("addresses")) { HashMap<String,Integer> pubkeys = new HashMap<String,Integer>(); JSONArray addressArray = (JSONArray)jsonObject.get("addresses"); JSONObject addrObj = null; for(int i = 0; i < addressArray.length(); i++) { addrObj = (JSONObject)addressArray.get(i); long amount = 0L; int nbTx = 0; String addr = null; String pcode = null; int idx = -1; if(addrObj.has("address")) { if(addrObj.has("pubkey")) { addr = (String)addrObj.get("pubkey"); pcode = BIP47Meta.getInstance().getPCode4Addr(addr); idx = BIP47Meta.getInstance().getIdx4Addr(addr); BIP47Meta.getInstance().getIdx4AddrLookup().put(addrObj.getString("address"), idx); BIP47Meta.getInstance().getPCode4AddrLookup().put(addrObj.getString("address"), pcode); } else { addr = (String)addrObj.get("address"); pcode = BIP47Meta.getInstance().getPCode4Addr(addr); idx = BIP47Meta.getInstance().getIdx4Addr(addr); } if(addrObj.has("final_balance")) { amount = addrObj.getLong("final_balance"); if(amount > 0L) { BIP47Meta.getInstance().addUnspent(pcode, idx); info("APIFactory", "BIP47 incoming amount:" + idx + ", " + addr + ", " + amount); } else { if(addrObj.has("pubkey")) { String pubkey = addrObj.getString("pubkey"); if(pubkeys.containsKey(pubkey)) { int count = pubkeys.get(pubkey); count++; if(count == 3) { BIP47Meta.getInstance().removeUnspent(pcode, Integer.valueOf(idx)); } else { pubkeys.put(pubkey, count + 1); } } else { pubkeys.put(pubkey, 1); } } else { BIP47Meta.getInstance().removeUnspent(pcode, Integer.valueOf(idx)); } } } if(addrObj.has("n_tx")) { nbTx = addrObj.getInt("n_tx"); if(nbTx > 0) { if(idx > BIP47Meta.getInstance().getIncomingIdx(pcode)) { BIP47Meta.getInstance().setIncomingIdx(pcode, idx); } info("APIFactory", "sync receive idx:" + idx + ", " + addr); ret++; } } } } } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return ret; } public synchronized int syncBIP47Outgoing(String[] addresses) { JSONObject jsonObject = getXPUB(addresses, false); int ret = 0; try { if(jsonObject != null && jsonObject.has("addresses")) { JSONArray addressArray = (JSONArray)jsonObject.get("addresses"); JSONObject addrObj = null; for(int i = 0; i < addressArray.length(); i++) { addrObj = (JSONObject)addressArray.get(i); int nbTx = 0; String addr = null; String pcode = null; int idx = -1; info("APIFactory", "address object:" + addrObj.toString()); if(addrObj.has("pubkey")) { addr = (String)addrObj.get("pubkey"); pcode = BIP47Meta.getInstance().getPCode4Addr(addr); idx = BIP47Meta.getInstance().getIdx4Addr(addr); BIP47Meta.getInstance().getIdx4AddrLookup().put(addrObj.getString("address"), idx); BIP47Meta.getInstance().getPCode4AddrLookup().put(addrObj.getString("address"), pcode); } else { addr = (String)addrObj.get("address"); pcode = BIP47Meta.getInstance().getPCode4Addr(addr); idx = BIP47Meta.getInstance().getIdx4Addr(addr); } if(addrObj.has("n_tx")) { nbTx = addrObj.getInt("n_tx"); if(nbTx > 0) { if(idx >= BIP47Meta.getInstance().getOutgoingIdx(pcode)) { info("APIFactory", "sync send idx:" + idx + ", " + addr); BIP47Meta.getInstance().setOutgoingIdx(pcode, idx + 1); } ret++; } } } } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return ret; } public long getXpubBalance() { return xpub_balance - BlockedUTXO.getInstance().getTotalValueBlocked0(); } public void setXpubBalance(long value) { xpub_balance = value; walletBalanceObserver.onNext(value); } public long getXpubPostMixBalance() { return xpub_postmix_balance - BlockedUTXO.getInstance().getTotalValueBlockedPostMix(); } public void setXpubPostMixBalance(long value) { xpub_postmix_balance = value; } public HashMap<String,Long> getXpubAmounts() { return xpub_amounts; } public HashMap<String,List<Tx>> getXpubTxs() { return xpub_txs; } public HashMap<String, String> getUnspentPaths() { return unspentPaths; } public HashMap<String, Integer> getUnspentAccounts() { return unspentAccounts; } public HashMap<String, Integer> getUnspentBIP49() { return unspentBIP49; } public HashMap<String, Integer> getUnspentBIP84() { return unspentBIP84; } public List<UTXO> getUtxos(boolean filter) { List<UTXO> unspents = new ArrayList<UTXO>(); if(filter) { for(String key : utxos.keySet()) { UTXO u = new UTXO(); for(MyTransactionOutPoint out : utxos.get(key).getOutpoints()) { if(!BlockedUTXO.getInstance().contains(out.getTxHash().toString(), out.getTxOutputN())) { u.getOutpoints().add(out); } } if(u.getOutpoints().size() > 0) { unspents.add(u); } } } else { unspents.addAll(utxos.values()); } return unspents; } public List<UTXO> getUtxosWithLocalCache(boolean filter,boolean useLocalCache) { List<UTXO> unspents = new ArrayList<UTXO>(); if(utxos.isEmpty() && useLocalCache){ try { String response = PayloadUtil.getInstance(context).deserializeUTXO().toString(); parseUnspentOutputsForSweep(response); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } if(filter) { for(String key : utxos.keySet()) { UTXO u = new UTXO(); for(MyTransactionOutPoint out : utxos.get(key).getOutpoints()) { if(!BlockedUTXO.getInstance().contains(out.getTxHash().toString(), out.getTxOutputN())) { u.getOutpoints().add(out); } } if(u.getOutpoints().size() > 0) { unspents.add(u); } } } else { unspents.addAll(utxos.values()); } return unspents; } public List<UTXO> getUtxosPostMix(boolean filter) { List<UTXO> unspents = new ArrayList<UTXO>(); if(filter) { for(String key : utxosPostMix.keySet()) { UTXO u = new UTXO(); for(MyTransactionOutPoint out : utxosPostMix.get(key).getOutpoints()) { if(!BlockedUTXO.getInstance().containsPostMix(out.getTxHash().toString(), out.getTxOutputN())) { u.getOutpoints().add(out); } } if(u.getOutpoints().size() > 0) { unspents.add(u); } } } else { unspents.addAll(utxosPostMix.values()); } return unspents; } public void setUtxos(HashMap<String, UTXO> utxos) { APIFactory.utxos = utxos; } public void setUtxosPostMix(HashMap<String, UTXO> utxos) { APIFactory.utxosPostMix = utxos; } public synchronized List<Tx> getAllXpubTxs() { List<Tx> ret = new ArrayList<Tx>(); for(String key : xpub_txs.keySet()) { List<Tx> txs = xpub_txs.get(key); for(Tx tx : txs) { ret.add(tx); } } Collections.sort(ret, new TxMostRecentDateComparator()); return ret; } public synchronized UTXO getUnspentOutputsForSweep(String address) { String _url = WebUtil.getAPIUrl(context); try { String response = null; if(!TorManager.getInstance(context).isRequired()) { StringBuilder args = new StringBuilder(); args.append("active="); args.append(address); args.append("&at="); args.append(getAccessToken()); // debug("APIFactory", args.toString()); response = WebUtil.getInstance(context).postURL(_url + "unspent?", args.toString()); // debug("APIFactory", response); } else { HashMap<String,String> args = new HashMap<String,String>(); args.put("active", address); args.put("at", getAccessToken()); // debug("APIFactory", args.toString()); response = WebUtil.getInstance(context).tor_postURL(_url + "unspent", args); // debug("APIFactory", response); } return parseUnspentOutputsForSweep(response); } catch(Exception e) { e.printStackTrace(); } return null; } private synchronized UTXO parseUnspentOutputsForSweep(String unspents) { UTXO utxo = null; if(unspents != null) { try { JSONObject jsonObj = new JSONObject(unspents); if(jsonObj == null || !jsonObj.has("unspent_outputs")) { return null; } JSONArray utxoArray = jsonObj.getJSONArray("unspent_outputs"); if(utxoArray == null || utxoArray.length() == 0) { return null; } // debug("APIFactory", "unspents found:" + outputsRoot.size()); for (int i = 0; i < utxoArray.length(); i++) { JSONObject outDict = utxoArray.getJSONObject(i); byte[] hashBytes = Hex.decode((String)outDict.get("tx_hash")); Sha256Hash txHash = Sha256Hash.wrap(hashBytes); int txOutputN = ((Number)outDict.get("tx_output_n")).intValue(); BigInteger value = BigInteger.valueOf(((Number)outDict.get("value")).longValue()); String script = (String)outDict.get("script"); byte[] scriptBytes = Hex.decode(script); int confirmations = ((Number)outDict.get("confirmations")).intValue(); try { String address = null; if(Bech32Util.getInstance().isBech32Script(script)) { address = Bech32Util.getInstance().getAddressFromScript(script); debug("address parsed:", address); } else { address = new Script(scriptBytes).getToAddress(SamouraiWallet.getInstance().getCurrentNetworkParams()).toString(); } // Construct the output MyTransactionOutPoint outPoint = new MyTransactionOutPoint(txHash, txOutputN, value, scriptBytes, address); outPoint.setConfirmations(confirmations); if(utxo == null) { utxo = new UTXO(); } utxo.getOutpoints().add(outPoint); } catch(Exception e) { ; } } } catch(JSONException je) { ; } } return utxo; } public static class TxMostRecentDateComparator implements Comparator<Tx> { public int compare(Tx t1, Tx t2) { final int BEFORE = -1; final int EQUAL = 0; final int AFTER = 1; int ret = 0; if(t1.getTS() > t2.getTS()) { ret = BEFORE; } else if(t1.getTS() < t2.getTS()) { ret = AFTER; } else { ret = EQUAL; } return ret; } } // use for post-mix private synchronized JSONObject getRawXPUB(String[] xpubs) { String _url = WebUtil.getAPIUrl(context); JSONObject jsonObject = null; try { String response = null; if(AppUtil.getInstance(context).isOfflineMode()) { response = PayloadUtil.getInstance(context).deserializeMultiAddrPost().toString(); } else if(!TorManager.getInstance(context).isRequired()) { // use POST StringBuilder args = new StringBuilder(); args.append("active="); args.append(StringUtils.join(xpubs, URLEncoder.encode("|", "UTF-8"))); info("APIFactory", "XPUB:" + args.toString()); args.append("&at="); args.append(getAccessToken()); response = WebUtil.getInstance(context).postURL(_url + "multiaddr?", args.toString()); info("APIFactory", "XPUB response:" + response); } else { HashMap<String,String> args = new HashMap<String,String>(); args.put("active", StringUtils.join(xpubs, "|")); info("APIFactory", "XPUB:" + args.toString()); args.put("at", getAccessToken()); response = WebUtil.getInstance(context).tor_postURL(_url + "multiaddr", args); info("APIFactory", "XPUB response:" + response); } try { jsonObject = new JSONObject(response); return jsonObject; } catch(JSONException je) { je.printStackTrace(); jsonObject = null; } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } return jsonObject; } public synchronized JSONObject getRawUnspentOutputs(String[] xpubs) { String _url = WebUtil.getAPIUrl(context); JSONObject jsonObject = null; String response = null; try { if(AppUtil.getInstance(context).isOfflineMode()) { response = PayloadUtil.getInstance(context).deserializeUTXOPost().toString(); } else if(!TorManager.getInstance(context).isRequired()) { StringBuilder args = new StringBuilder(); args.append("active="); args.append(StringUtils.join(xpubs, URLEncoder.encode("|", "UTF-8"))); debug("APIFactory", "UTXO args:" + args.toString()); args.append("&at="); args.append(getAccessToken()); response = WebUtil.getInstance(context).postURL(_url + "unspent?", args.toString()); debug("APIFactory", "UTXO:" + response); } else { HashMap<String,String> args = new HashMap<String,String>(); args.put("active", StringUtils.join(xpubs, "|")); args.put("at", getAccessToken()); response = WebUtil.getInstance(context).tor_postURL(_url + "unspent", args); } } catch(Exception e) { jsonObject = null; e.printStackTrace(); } if(!AppUtil.getInstance(context).isOfflineMode()) { try { jsonObject = new JSONObject(response); } catch(JSONException je) { ; } } return jsonObject; } private synchronized boolean parseMixXPUB(JSONObject jsonObject) throws JSONException { if(jsonObject != null) { if(jsonObject.has("wallet")) { JSONObject walletObj = (JSONObject)jsonObject.get("wallet"); if(walletObj.has("final_balance")) { xpub_postmix_balance = walletObj.getLong("final_balance"); debug("APIFactory", "xpub_postmix_balance:" + xpub_postmix_balance); } } if(jsonObject.has("info")) { JSONObject infoObj = (JSONObject)jsonObject.get("info"); if(infoObj.has("latest_block")) { JSONObject blockObj = (JSONObject)infoObj.get("latest_block"); if(blockObj.has("height")) { latest_block_height = blockObj.getLong("height"); } if(blockObj.has("hash")) { latest_block_hash = blockObj.getString("hash"); } } } if(jsonObject.has("addresses")) { JSONArray addressesArray = (JSONArray)jsonObject.get("addresses"); JSONObject addrObj = null; for(int i = 0; i < addressesArray.length(); i++) { addrObj = (JSONObject)addressesArray.get(i); if(addrObj != null && addrObj.has("final_balance") && addrObj.has("address")) { if(FormatsUtil.getInstance().isValidXpub((String)addrObj.get("address"))) { // xpub_amounts.put((String)addrObj.get("address"), addrObj.getLong("final_balance")); if(addrObj.getString("address").equals(BIP84Util.getInstance(context).getWallet().getAccountAt(WhirlpoolMeta.getInstance(context).getWhirlpoolPostmix()).xpubstr()) || addrObj.getString("address").equals(BIP84Util.getInstance(context).getWallet().getAccountAt(WhirlpoolMeta.getInstance(context).getWhirlpoolPostmix()).zpubstr())) { AddressFactory.getInstance().setHighestPostReceiveIdx(addrObj.has("account_index") ? addrObj.getInt("account_index") : 0); AddressFactory.getInstance().setHighestPostChangeIdx(addrObj.has("change_index") ? addrObj.getInt("change_index") : 0); BIP84Util.getInstance(context).getWallet().getAccountAt(WhirlpoolMeta.getInstance(context).getWhirlpoolPostmix()).getChain(0).setAddrIdx(addrObj.has("account_index") ? addrObj.getInt("account_index") : 0); BIP84Util.getInstance(context).getWallet().getAccountAt(WhirlpoolMeta.getInstance(context).getWhirlpoolPostmix()).getChain(1).setAddrIdx(addrObj.has("change_index") ? addrObj.getInt("change_index") : 0); } else if(addrObj.getString("address").equals(BIP84Util.getInstance(context).getWallet().getAccountAt(WhirlpoolMeta.getInstance(context).getWhirlpoolPremixAccount()).xpubstr()) || addrObj.getString("address").equals(BIP84Util.getInstance(context).getWallet().getAccountAt(WhirlpoolMeta.getInstance(context).getWhirlpoolPremixAccount()).zpubstr())) { AddressFactory.getInstance().setHighestPreReceiveIdx(addrObj.has("account_index") ? addrObj.getInt("account_index") : 0); AddressFactory.getInstance().setHighestPreChangeIdx(addrObj.has("change_index") ? addrObj.getInt("change_index") : 0); BIP84Util.getInstance(context).getWallet().getAccountAt(WhirlpoolMeta.getInstance(context).getWhirlpoolPremixAccount()).getChain(0).setAddrIdx(addrObj.has("account_index") ? addrObj.getInt("account_index") : 0); BIP84Util.getInstance(context).getWallet().getAccountAt(WhirlpoolMeta.getInstance(context).getWhirlpoolPremixAccount()).getChain(1).setAddrIdx(addrObj.has("change_index") ? addrObj.getInt("change_index") : 0); } else { ; } } } } } try { PayloadUtil.getInstance(context).serializeMultiAddrPost(jsonObject); } catch(IOException | DecryptionException e) { ; } return true; } return false; } private synchronized boolean parsePostMixUnspentOutputs(String unspents) { if(unspents != null) { try { JSONObject jsonObj = new JSONObject(unspents); if(jsonObj == null || !jsonObj.has("unspent_outputs")) { return false; } JSONArray utxoArray = jsonObj.getJSONArray("unspent_outputs"); if(utxoArray == null || utxoArray.length() == 0) { return false; } for (int i = 0; i < utxoArray.length(); i++) { JSONObject outDict = utxoArray.getJSONObject(i); byte[] hashBytes = Hex.decode((String)outDict.get("tx_hash")); Sha256Hash txHash = Sha256Hash.wrap(hashBytes); int txOutputN = ((Number)outDict.get("tx_output_n")).intValue(); BigInteger value = BigInteger.valueOf(((Number)outDict.get("value")).longValue()); String script = (String)outDict.get("script"); byte[] scriptBytes = Hex.decode(script); int confirmations = ((Number)outDict.get("confirmations")).intValue(); String path = null; try { String address = Bech32Util.getInstance().getAddressFromScript(script); if(outDict.has("xpub")) { JSONObject xpubObj = (JSONObject)outDict.get("xpub"); path = (String)xpubObj.get("path"); String m = (String)xpubObj.get("m"); unspentPaths.put(address, path); if(m.equals(BIP84Util.getInstance(context).getWallet().getAccountAt(WhirlpoolMeta.getInstance(context).getWhirlpoolPostmix()).xpubstr())) { unspentBIP84PostMix.put(address, WhirlpoolMeta.getInstance(context).getWhirlpoolPostmix()); } } else { ; } // Construct the output MyTransactionOutPoint outPoint = new MyTransactionOutPoint(txHash, txOutputN, value, scriptBytes, address); outPoint.setConfirmations(confirmations); if(utxosPostMix.containsKey(script)) { utxosPostMix.get(script).getOutpoints().add(outPoint); } else { UTXO utxo = new UTXO(); utxo.getOutpoints().add(outPoint); utxo.setPath(path); utxosPostMix.put(script, utxo); } UTXOFactory.getInstance().addPostMix(script, utxosPostMix.get(script)); } catch(Exception e) { ; } } PayloadUtil.getInstance(context).serializeUTXOPost(jsonObj); return true; } catch(Exception j) { ; } } return false; } }
package com.wsfmn.view; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageView; import android.widget.TextView; import com.wsfmn.controller.HabitListController; import com.wsfmn.controller.OnlineController; import com.wsfmn.model.Habit; import com.wsfmn.model.Date; import com.wsfmn.model.HabitEvent; import com.wsfmn.model.WeekDays; import com.wsfmn.model.Geolocation; public class FriendHabitActivity extends AppCompatActivity { private Habit fHabit; private HabitEvent fEvent; TextView fhTitle; TextView fhReason; TextView fhDate; TextView fEventComment; TextView fEventDate; TextView fEventAddress; ImageView friendImage; private CheckBox monday; private CheckBox tuesday; private CheckBox wednesday; private CheckBox thursday; private CheckBox friday; private CheckBox saturday; private CheckBox sunday; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_friend_habit); Intent intent = getIntent(); fHabit = (Habit) intent.getSerializableExtra("friend"); fhTitle = (TextView) findViewById(R.id.fhTitle); fhReason = (TextView) findViewById(R.id.fhReason); fhDate = (TextView) findViewById(R.id.fhDate); monday = (CheckBox) findViewById(R.id.monday); tuesday = (CheckBox) findViewById(R.id.tuesday); wednesday = (CheckBox) findViewById(R.id.wednesday); thursday = (CheckBox) findViewById(R.id.thursday); friday = (CheckBox) findViewById(R.id.friday); saturday = (CheckBox) findViewById(R.id.saturday); sunday = (CheckBox) findViewById(R.id.sunday); fEventComment = (TextView) findViewById(R.id.fEventComment); fEventDate = (TextView) findViewById(R.id.fEventDate); fEventAddress = (TextView) findViewById(R.id.fEventAddress); friendImage = (ImageView) findViewById(R.id.friendImage); monday.setClickable(false); tuesday.setClickable(false); wednesday.setClickable(false); thursday.setClickable(false); friday.setClickable(false); saturday.setClickable(false); sunday.setClickable(false); setCheckBox(monday, WeekDays.MONDAY); setCheckBox(tuesday, WeekDays.TUESDAY); setCheckBox(wednesday, WeekDays.WEDNESDAY); setCheckBox(thursday, WeekDays.THURSDAY); setCheckBox(friday, WeekDays.FRIDAY); setCheckBox(saturday, WeekDays.SATURDAY); setCheckBox(sunday, WeekDays.SUNDAY); fhTitle.setText(fHabit.getTitle()); fhReason.setText(fHabit.getReason()); fhDate.setText(fHabit.getDate().toString()); } public void setCheckBox(CheckBox checkBox, int day){ checkBox.setChecked(fHabit.getWeekDays().getDay(day)); } @Override protected void onStart() { super.onStart(); OnlineController.GetRecentEvent fRecentEvent = new OnlineController.GetRecentEvent(); fRecentEvent.execute(fHabit.getTitle().toLowerCase(),fHabit.getOwner()); try{ fEvent = fRecentEvent.get(); fEventComment.setText(fEvent.getComment()); friendImage.setImageBitmap(fEvent.getImageBitmap()); fEventDate.setText(fEvent.getDate().toString()); fEventAddress.setText(fEvent.getGeolocation().getAddress()); } catch (Exception e) { Log.i("Error", "Failed to get the requests from the async object"); } } }
package me.devsaki.hentoid.core; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.hardware.usb.UsbManager; import android.os.Build; import androidx.annotation.NonNull; import androidx.documentfile.provider.DocumentFile; import androidx.work.ExistingWorkPolicy; import androidx.work.OneTimeWorkRequest; import androidx.work.WorkManager; import com.google.firebase.analytics.FirebaseAnalytics; import com.google.firebase.crashlytics.FirebaseCrashlytics; import org.greenrobot.eventbus.EventBus; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import io.reactivex.Observable; import io.reactivex.ObservableEmitter; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.Disposable; import io.reactivex.functions.BiConsumer; import io.reactivex.functions.Consumer; import io.reactivex.schedulers.Schedulers; import me.devsaki.hentoid.BuildConfig; import me.devsaki.hentoid.R; import me.devsaki.hentoid.database.CollectionDAO; import me.devsaki.hentoid.database.DatabaseMaintenance; import me.devsaki.hentoid.database.ObjectBoxDAO; import me.devsaki.hentoid.enums.Site; import me.devsaki.hentoid.events.AppUpdatedEvent; import me.devsaki.hentoid.json.JsonSiteSettings; import me.devsaki.hentoid.notification.action.UserActionNotificationChannel; import me.devsaki.hentoid.notification.delete.DeleteNotificationChannel; import me.devsaki.hentoid.notification.download.DownloadNotificationChannel; import me.devsaki.hentoid.notification.startup.StartupNotificationChannel; import me.devsaki.hentoid.notification.update.UpdateNotificationChannel; import me.devsaki.hentoid.receiver.PlugEventsReceiver; import me.devsaki.hentoid.services.UpdateCheckService; import me.devsaki.hentoid.util.FileHelper; import me.devsaki.hentoid.util.Helper; import me.devsaki.hentoid.util.JsonHelper; import me.devsaki.hentoid.util.Preferences; import me.devsaki.hentoid.workers.StartupWorker; import timber.log.Timber; public class AppStartup { private List<Observable<Float>> launchTasks; private Disposable launchDisposable = null; private static boolean isInitialized = false; private synchronized static void setInitialized() { isInitialized = true; } public void initApp( @NonNull final Context context, @NonNull Consumer<Float> onMainProgress, @NonNull Consumer<Float> onSecondaryProgress, @NonNull Runnable onComplete ) { if (isInitialized) onComplete.run(); // Wait until pre-launch tasks are completed launchTasks = getPreLaunchTasks(context); launchTasks.addAll(DatabaseMaintenance.getPreLaunchCleanupTasks(context)); // TODO switch from a recursive function to a full RxJava-powered chain doRunTask(0, onMainProgress, onSecondaryProgress, () -> { if (launchDisposable != null) launchDisposable.dispose(); setInitialized(); onComplete.run(); // Run post-launch tasks on a worker WorkManager workManager = WorkManager.getInstance(context); workManager.enqueueUniqueWork(Integer.toString(R.id.startup_service), ExistingWorkPolicy.KEEP, new OneTimeWorkRequest.Builder(StartupWorker.class).build()); }); } private void doRunTask( int taskIndex, @NonNull Consumer<Float> onMainProgress, @NonNull Consumer<Float> onSecondaryProgress, @NonNull Runnable onComplete ) { if (launchDisposable != null) launchDisposable.dispose(); try { onMainProgress.accept(taskIndex * 1f / launchTasks.size()); } catch (Exception e) { Timber.w(e); } // Continue executing launch tasks if (taskIndex < launchTasks.size()) { Timber.i("Pre-launch task %s/%s", taskIndex + 1, launchTasks.size()); launchDisposable = launchTasks.get(taskIndex) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe( onSecondaryProgress, Timber::e, () -> doRunTask(taskIndex + 1, onMainProgress, onSecondaryProgress, onComplete) ); } else { onComplete.run(); } } /** * Application initialization tasks * NB : Heavy operations; must be performed in the background to avoid ANR at startup */ public static List<Observable<Float>> getPreLaunchTasks(@NonNull final Context context) { List<Observable<Float>> result = new ArrayList<>(); result.add(createObservableFrom(context, AppStartup::stopWorkers)); result.add(createObservableFrom(context, AppStartup::processAppUpdate)); result.add(createObservableFrom(context, AppStartup::loadSiteProperties)); result.add(createObservableFrom(context, AppStartup::initUtils)); return result; } public static List<Observable<Float>> getPostLaunchTasks(@NonNull final Context context) { List<Observable<Float>> result = new ArrayList<>(); // result.add(createObservableFrom(context, AppStartupDev::testImg)); result.add(createObservableFrom(context, AppStartup::searchForUpdates)); result.add(createObservableFrom(context, AppStartup::sendFirebaseStats)); result.add(createObservableFrom(context, AppStartup::clearPictureCache)); result.add(createObservableFrom(context, AppStartup::createBookmarksJson)); result.add(createObservableFrom(context, AppStartup::createPlugReceiver)); return result; } private static Observable<Float> createObservableFrom(@NonNull final Context context, BiConsumer<Context, ObservableEmitter<Float>> function) { return Observable.create(emitter -> function.accept(context, emitter)); } private static void stopWorkers(@NonNull final Context context, ObservableEmitter<Float> emitter) { try { Timber.i("Stop workers : start"); WorkManager.getInstance(context).cancelAllWorkByTag(Consts.WORK_CLOSEABLE); Timber.i("Stop workers : done"); } finally { emitter.onComplete(); } } private static void loadSiteProperties(@NonNull final Context context, ObservableEmitter<Float> emitter) { try (InputStream is = context.getResources().openRawResource(R.raw.sites)) { String siteSettingsStr = FileHelper.readStreamAsString(is); JsonSiteSettings siteSettings = JsonHelper.jsonToObject(siteSettingsStr, JsonSiteSettings.class); for (Map.Entry<String, JsonSiteSettings.JsonSite> entry : siteSettings.sites.entrySet()) { for (Site site : Site.values()) { if (site.name().equalsIgnoreCase(entry.getKey())) { site.updateFrom(entry.getValue()); break; } } } } catch (IOException e) { Timber.e(e); } finally { emitter.onComplete(); } } private static void initUtils(@NonNull final Context context, ObservableEmitter<Float> emitter) { try { Timber.i("Init notifications : start"); // Init notification channels StartupNotificationChannel.init(context); UpdateNotificationChannel.init(context); DownloadNotificationChannel.init(context); UserActionNotificationChannel.init(context); DeleteNotificationChannel.init(context); // Clears all previous notifications NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); if (manager != null) manager.cancelAll(); Timber.i("Init notifications : done"); } finally { emitter.onComplete(); } } private static void processAppUpdate(@NonNull final Context context, ObservableEmitter<Float> emitter) { Timber.i("Process app update : start"); try { if (Preferences.getLastKnownAppVersionCode() < BuildConfig.VERSION_CODE) { Timber.d("Process app update : update detected from %s to %s", Preferences.getLastKnownAppVersionCode(), BuildConfig.VERSION_CODE); Timber.d("Process app update : Clearing webview cache"); ContextXKt.clearWebviewCache(context); Timber.d("Process app update : Clearing app cache"); ContextXKt.clearAppCache(context); Timber.d("Process app update : Complete"); EventBus.getDefault().postSticky(new AppUpdatedEvent()); Preferences.setLastKnownAppVersionCode(BuildConfig.VERSION_CODE); } } finally { emitter.onComplete(); } Timber.i("Process app update : done"); } private static void searchForUpdates(@NonNull final Context context, ObservableEmitter<Float> emitter) { Timber.i("Run app update : start"); try { if (Preferences.isAutomaticUpdateEnabled()) { Timber.i("Run app update : auto-check is enabled"); Intent intent = UpdateCheckService.makeIntent(context, false); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { context.startForegroundService(intent); } else { context.startService(intent); } } } finally { emitter.onComplete(); } Timber.i("Run app update : done"); } private static void sendFirebaseStats(@NonNull final Context context, ObservableEmitter<Float> emitter) { Timber.i("Send Firebase stats : start"); try { FirebaseAnalytics.getInstance(context).setUserProperty("color_theme", Integer.toString(Preferences.getColorTheme())); FirebaseAnalytics.getInstance(context).setUserProperty("endless", Boolean.toString(Preferences.getEndlessScroll())); FirebaseCrashlytics.getInstance().setCustomKey("Library display mode", Preferences.getEndlessScroll() ? "endless" : "paged"); } catch (IllegalStateException e) { // Happens during unit tests Timber.e(e, "fail@init Crashlytics"); } finally { emitter.onComplete(); } Timber.i("Send Firebase stats : done"); } // Clear archive picture cache (useful when user kills the app while in background with the viewer open) private static void clearPictureCache(@NonNull final Context context, ObservableEmitter<Float> emitter) { Timber.i("Clear picture cache : start"); try { FileHelper.emptyCacheFolder(context, Consts.PICTURE_CACHE_FOLDER); } finally { emitter.onComplete(); } Timber.i("Clear picture cache : done"); } // Creates the JSON file for bookmarks if it doesn't exist private static void createBookmarksJson(@NonNull final Context context, ObservableEmitter<Float> emitter) { Timber.i("Create bookmarks JSON : start"); try { DocumentFile appRoot = FileHelper.getFolderFromTreeUriString(context, Preferences.getStorageUri()); if (appRoot != null) { DocumentFile bookmarksJson = FileHelper.findFile(context, appRoot, Consts.BOOKMARKS_JSON_FILE_NAME); if (null == bookmarksJson) { Timber.i("Create bookmarks JSON : creating JSON"); CollectionDAO dao = new ObjectBoxDAO(context); try { Helper.updateBookmarksJson(context, dao); } finally { dao.cleanup(); } } else { Timber.i("Create bookmarks JSON : already exists"); } } } finally { emitter.onComplete(); } Timber.i("Create bookmarks JSON : done"); } private static void createPlugReceiver(@NonNull final Context context, ObservableEmitter<Float> emitter) { Timber.i("Create plug receiver : start"); try { PlugEventsReceiver rcv = new PlugEventsReceiver(); final IntentFilter filter = new IntentFilter(); filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED); filter.addAction(Intent.ACTION_POWER_CONNECTED); filter.addAction(Intent.ACTION_HEADSET_PLUG); context.registerReceiver(rcv, filter); } finally { emitter.onComplete(); } Timber.i("Create plug receiver : done"); } }
package scal.io.liger.model; import android.content.Context; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.util.ArrayList; import scal.io.liger.JsonHelper; import scal.io.liger.MainActivity; import scal.io.liger.StoryPathDeserializer; public class StoryPathModel { public String id; public String title; public ArrayList<CardModel> cards; public ArrayList<DependencyModel> dependencies; // this is used by the JsonHelper class to load json assets // if there is an alternate way to load them, this should be removed // also must be cleared before serializing story path public Context context; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public ArrayList<CardModel> getCards() { return cards; } public void setCards(ArrayList<CardModel> cards) { this.cards = cards; } public void addCard(CardModel card) { if (this.cards == null) this.cards = new ArrayList<CardModel>(); this.cards.add(card); } public CardModel getCardById(String fullPath) { // assumes the format story::card::field::value String[] pathParts = fullPath.split("::"); // sanity check if (!this.id.equals(pathParts[0])) { System.err.println("STORY PATH ID " + pathParts[0] + " DOES NOT MATCH"); return null; } for (CardModel card : cards) { if (card.getId().equals(pathParts[1])) { return card; } } System.err.println("CARD ID " + pathParts[1] + " WAS NOT FOUND"); return null; } public ArrayList<CardModel> getValidCards() { ArrayList<CardModel> validCards = new ArrayList<CardModel>(); for (CardModel card : cards) { if (card.checkReferencedValues()) { validCards.add(card); } } return validCards; } public ArrayList<DependencyModel> getDependencies() { return dependencies; } public void setDependencies(ArrayList<DependencyModel> dependencies) { this.dependencies = dependencies; } public void addDependency(DependencyModel dependency) { if (this.dependencies == null) this.dependencies = new ArrayList<DependencyModel>(); this.dependencies.add(dependency); } // set a reference to this story path in each card // must be done before cards attempt to reference // values from previous story paths or cards public void setCardReferences() { for (CardModel card : cards) { card.setStoryPathReference(this); } } // clear references to this story path from each card // must be done before serializing this story path to // prevent duplication or circular references public void clearCardReferences() { for (CardModel card : cards) { card.setStoryPathReference(null); } } public String getReferencedValue(String fullPath) { // assumes the format story::card::field::value String[] pathParts = fullPath.split("::"); StoryPathModel story = null; if (this.getId().equals(pathParts[0])) { // reference targets this story path story = this; } else { // reference targets a serialized story path for (DependencyModel dependency : dependencies) { if (dependency.getDependencyId().equals(pathParts[0])) { GsonBuilder gBuild = new GsonBuilder(); gBuild.registerTypeAdapter(StoryPathModel.class, new StoryPathDeserializer()); Gson gson = gBuild.create(); String json = JsonHelper.loadJSONFromPath(dependency.getDependencyFile()); story = gson.fromJson(json, StoryPathModel.class); } } } if (story == null) { System.err.println("STORY PATH ID " + pathParts[0] + " WAS NOT FOUND"); return null; } CardModel card = story.getCardById(fullPath); if (card == null) { return null; } else { String value = card.getValueById(fullPath); if (value == null) { return null; } else { return value; } } } public void notifyActivity() { if (context != null) { MainActivity mainActivity = (MainActivity) context; // FIXME this isn't a save cast as context can sometimes not be an activity (getApplicationContext()) mainActivity.refreshCardView(); } else { System.err.println("APP CONTEXT REFERENCE NOT FOUND, CANNOT SEND NOTIFICATION"); } } public void linkNotification(String linkPath) { if (context != null) { MainActivity mainActivity = (MainActivity) context; mainActivity.goToCard(linkPath); } else { System.err.println("APP CONTEXT REFERENCE NOT FOUND, CANNOT SEND LINK NOTIFICATION"); } } public void rearrangeCards(int currentIndex, int newIndex) { CardModel card = cards.remove(currentIndex); cards.add(newIndex, card); } }
package org.commcare.android.database; import org.commcare.android.database.user.models.ACase; import org.commcare.android.util.SessionUnavailableException; import org.commcare.cases.ledger.Ledger; import org.commcare.cases.model.Case; import org.commcare.core.interfaces.UserSandbox; import org.commcare.dalvik.application.CommCareApplication; import org.javarosa.core.model.User; import org.javarosa.core.model.instance.FormInstance; import org.javarosa.core.services.storage.IStorageUtilityIndexed; public class AndroidSandbox extends UserSandbox { CommCareApplication app; public AndroidSandbox(CommCareApplication app){ this.app = app; } @Override public IStorageUtilityIndexed<Case> getCaseStorage() { return app.getUserStorage(ACase.STORAGE_KEY, ACase.class); } @Override public IStorageUtilityIndexed<Ledger> getLedgerStorage() { return app.getUserStorage(Ledger.STORAGE_KEY, Ledger.class); } @Override public IStorageUtilityIndexed<User> getUserStorage() { return app.getUserStorage("USER", User.class); } @Override public IStorageUtilityIndexed<FormInstance> getUserFixtureStorage() { return app.getUserStorage("fixture", FormInstance.class); } @Override public IStorageUtilityIndexed<FormInstance> getAppFixtureStorage() { return app.getAppStorage("fixture", FormInstance.class); } @Override public User getLoggedInUser() { try { return app.getSession().getLoggedInUser(); } catch (SessionUnavailableException e) { return null; } } @Override public void setLoggedInUser(User user) { } }
package org.commcare.models.encryption; import org.commcare.core.encryption.CryptUtil; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import javax.crypto.Cipher; import javax.crypto.NoSuchPaddingException; /** * NOTE: routes static operations through class that can be shadowed via * Robolectric to solve JCE encryption compatibility issues * * @author Aliza Stone (astone@dimagi.com) */ public class ByteEncrypter { private ByteEncrypter() { } public static byte[] wrapByteArrayWithString(byte[] bytes, String wrappingString) { return (new ByteEncrypter()).wrap(bytes, wrappingString); } public byte[] wrap(byte[] bytes, String wrappingString) { // NOTE: implementation is exposed for overriding in test harness due // to java encryption limitations (JCE) try { return CryptUtil.encrypt(bytes, CryptUtil.encodingCipher(wrappingString)); } catch (InvalidKeySpecException | NoSuchAlgorithmException | InvalidKeyException e) { throw new RuntimeException(e); } catch (NoSuchPaddingException e) { return null; } } public static byte[] unwrapByteArrayWithString(byte[] wrapped, String wrappingString) { return (new ByteEncrypter()).unwrap(wrapped, wrappingString); } public byte[] unwrap(byte[] wrapped, String wrappingString) { // NOTE: implementation is exposed for overriding in test harness due // to java encryption limitations (JCE) try { Cipher cipher = CryptUtil.decodingCipher(wrappingString); return CryptUtil.decrypt(wrapped, cipher); } catch (NoSuchAlgorithmException | InvalidKeySpecException | InvalidKeyException e) { throw new RuntimeException(e); } catch (NoSuchPaddingException e) { return null; } } }
package org.commcare.views.widgets; import android.app.Activity; import android.content.pm.ActivityInfo; import android.content.res.Configuration; import android.graphics.Rect; import android.media.MediaRecorder; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.widget.Button; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.content.DialogInterface; import android.widget.TextView; import com.liulishuo.magicprogresswidget.MagicProgressCircle; import org.commcare.dalvik.R; import org.javarosa.core.services.locale.Localization; import java.io.IOException; public class RecordingFragment extends android.support.v4.app.DialogFragment{ private String fileName; private final String FILE_EXT = "/Android/data/org.commcare.dalvik/temp/Custom Recording.mp4"; public static final int MAX_DURATION_MS = 120000; private ImageButton toggleRecording; private LinearLayout layout; private Button saveRecording; private TextView instruction; private MediaRecorder recorder; private RecordingCompletionListener listener; private MagicProgressCircle mpc; public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ layout = (LinearLayout) inflater.inflate(R.layout.recording_fragment, container); enableScreenRotation(); prepareButtons(); prepareText(); setWindowSize(); fileName = Environment.getExternalStorageDirectory().getAbsolutePath() + FILE_EXT; return layout; } protected void setWindowSize() { Rect displayRectangle = new Rect(); Window window = getActivity().getWindow(); window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle); layout.setMinimumWidth((int)(displayRectangle.width() * 0.9f)); getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE); } protected void prepareText() { TextView header = (TextView) layout.findViewById(R.id.recording_header); instruction = (TextView) layout.findViewById(R.id.recording_instruction); header.setText(Localization.get("recording.header")); instruction.setText(Localization.get("before.recording")); } private void prepareButtons() { toggleRecording = (ImageButton) layout.findViewById(R.id.startrecording); saveRecording = (Button) layout.findViewById(R.id.saverecording); toggleRecording.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startRecording(); } }); saveRecording.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { saveRecording(); } }); saveRecording.setText(Localization.get("save")); mpc = (MagicProgressCircle) layout.findViewById(R.id.demo_mpc); } private void startRecording(){ disableScreenRotation(); if(recorder == null){ recorder = new MediaRecorder(); } setupRecorder(); recorder.start(); toggleRecording.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { stopRecording(); } }); toggleRecording.setBackgroundResource(R.drawable.record_in_progress); instruction.setText(Localization.get("during.recording")); mpc.setVisibility(View.VISIBLE); mpc.setSmoothPercent(new Float(1.0), MAX_DURATION_MS); } private void setupRecorder() { recorder.setAudioSource(MediaRecorder.AudioSource.MIC); recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4); recorder.setOutputFile(fileName); recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB); recorder.setMaxDuration(MAX_DURATION_MS); recorder.setOnInfoListener(new MediaRecorder.OnInfoListener() { @Override public void onInfo(MediaRecorder mr, int what, int extra) { if(what == MediaRecorder.MEDIA_RECORDER_INFO_MAX_DURATION_REACHED){ stopRecording(); } } }); try{ recorder.prepare(); }catch(IOException e){ Log.d("Recorder", "Failed to prepare media recorder"); } } private void stopRecording(){ mpc.setPercent(mpc.getPercent()); mpc.setStartColor(getResources().getColor(R.color.blue_grey)); mpc.setEndColor(getResources().getColor(R.color.blue_grey)); recorder.stop(); toggleRecording.setEnabled(false); toggleRecording.setBackgroundResource(R.drawable.record_complete); saveRecording.setEnabled(true); instruction.setText(Localization.get("after.recording")); saveRecording.setTextColor(getResources().getColor(R.color.white)); saveRecording.setBackgroundColor(getResources().getColor(R.color.cc_attention_positive_color)); } public void saveRecording(){ if(listener != null){ listener.onCompletion(); } dismiss(); } public interface RecordingCompletionListener { void onCompletion(); } public void setListener(RecordingCompletionListener listener){ this.listener = listener; } @Override public void onDismiss(DialogInterface dialog){ super.onDismiss(dialog); if(recorder != null){ recorder.release(); this.recorder = null; } } public String getFileName(){ return fileName; } private void disableScreenRotation() { int currentOrientation = getResources().getConfiguration().orientation; if (currentOrientation == Configuration.ORIENTATION_LANDSCAPE) { ((Activity) getContext()).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE); } else { ((Activity) getContext()).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT); } } private void enableScreenRotation() { ((Activity) getContext()).setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR); } }
package com.bouye.gw2.sab.query; import api.web.gw2.mapping.core.APILevel; import api.web.gw2.mapping.core.CoinAmount; import api.web.gw2.mapping.core.EnumValueFactory; import api.web.gw2.mapping.v2.account.Account; import api.web.gw2.mapping.v2.characters.Character; import api.web.gw2.mapping.v2.account.AccountAccessType; import api.web.gw2.mapping.v2.account.bank.BankSlot; import api.web.gw2.mapping.v2.account.wallet.CurrencyAmount; import api.web.gw2.mapping.v2.backstory.answers.BackstoryAnswer; import api.web.gw2.mapping.v2.characters.CharacterProfession; import api.web.gw2.mapping.v2.currencies.Currency; import api.web.gw2.mapping.v2.items.Item; import api.web.gw2.mapping.v2.items.ItemRarity; import api.web.gw2.mapping.v2.items.ItemType; import api.web.gw2.mapping.v2.skills.Skill; import api.web.gw2.mapping.v2.skills.SkillType; import api.web.gw2.mapping.v2.skins.Skin; import api.web.gw2.mapping.v2.skins.SkinRarity; import api.web.gw2.mapping.v2.skins.SkinType; import api.web.gw2.mapping.v2.wvw.MapType; import api.web.gw2.mapping.v2.wvw.abilities.Ability; import api.web.gw2.mapping.v2.wvw.objectives.Objective; import api.web.gw2.mapping.v2.wvw.objectives.ObjectiveType; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.time.ZonedDateTime; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.OptionalInt; import java.util.Properties; import java.util.function.Function; import static org.junit.Assert.*; import org.junit.After; import org.junit.AfterClass; import org.junit.Test; import org.junit.Before; import org.junit.BeforeClass; import static org.hamcrest.CoreMatchers.is; public class APITest { public APITest() { } private static final Properties SETTINGS = new Properties(); @BeforeClass public static void setUpClass() throws IOException { final File file = new File("settings.properties"); // NOI18N. assertTrue(file.exists()); assertTrue(file.canRead()); try (final InputStream input = new FileInputStream(file)) { SETTINGS.load(input); } assertNotNull(SETTINGS.getProperty("app.key")); // NOI18N. } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } @Test public void testAccount() { System.out.println("testAccount"); final String expId = SETTINGS.getProperty("account.id"); // NOI18N. final String expName = SETTINGS.getProperty("account.name"); // NOI18N. final ZonedDateTime expCreated = ZonedDateTime.parse(SETTINGS.getProperty("account.created")); // NOI18N. final int expWorld = Integer.parseInt(SETTINGS.getProperty("account.world")); // NOI18N. final AccountAccessType expAccess = EnumValueFactory.INSTANCE.mapEnumValue(AccountAccessType.class, SETTINGS.getProperty("account.access")); // NOI18N. final boolean expCommander = Boolean.parseBoolean(SETTINGS.getProperty("account.commander")); // NOI18N. final int expFractal = Integer.parseInt(SETTINGS.getProperty("account.fractal_level")); // NOI18N. assertNotNull(expId); assertNotNull(expName); final Optional<Account> value = GW2APIClient.create() .applicationKey(SETTINGS.getProperty("app.key")) // NOI18N. .apiLevel(APILevel.V2) .endPoint("account") // NOI18N. .queryObject(Account.class); assertTrue(value.isPresent()); assertEquals(expId, value.get().getId()); assertEquals(expName, value.get().getName()); assertEquals(expCreated, value.get().getCreated()); assertEquals(expWorld, value.get().getWorld()); assertEquals(expAccess, value.get().getAccess()); assertEquals(expCommander, value.get().isCommander()); assertEquals(expFractal, value.get().getFractalLevel()); } @Test public void testCharacters() { System.out.println("testCharacters"); final List<String> expNames = Arrays.asList(SETTINGS.getProperty("characters.names").split(",")); // NOI18N. final List<String> value = GW2APIClient.create() .applicationKey(SETTINGS.getProperty("app.key")) // NOI18N. .apiLevel(APILevel.V2) .endPoint("characters") // NOI18N. .queryArray(String.class); // Order is not important. assertThat(new HashSet<>(value), is(new HashSet<>(expNames))); } @Test public void testCharacter() { System.out.println("testCharacter"); final String expName = SETTINGS.getProperty("character.name"); // NOI18N. final int expLevel = Integer.parseInt(SETTINGS.getProperty("character.level")); // NOI18N. final CharacterProfession expProfession = EnumValueFactory.INSTANCE.mapEnumValue(CharacterProfession.class, SETTINGS.getProperty("character.profession")); // NOI18N. assertNotNull(expName); final String id = SETTINGS.getProperty("character.name"); // NOI18N. final Optional<Character> value = GW2APIClient.create() .applicationKey(SETTINGS.getProperty("app.key")) // NOI18N. .apiLevel(APILevel.V2) .endPoint("characters") // NOI18N. .id(id) .queryObject(Character.class); assertTrue(value.isPresent()); assertEquals(expName, value.get().getName()); assertEquals(expLevel, value.get().getLevel()); assertEquals(expProfession, value.get().getProfession()); } @Test public void testItems() { System.out.println("testItems"); // NOI18N. final int[] ids = Arrays.stream(SETTINGS.getProperty("items.ids").split(",")) // NOI18N. .mapToInt(Integer::parseInt) .toArray(); Arrays.stream(ids) .forEach(this::testItem); } private void testItem(final int idToTest) { System.out.printf("testItem(%d)%n", idToTest); // NOI18N. final String prefix = String.format("item.%d.", idToTest); // NOI18N. final int expId = Integer.parseInt(SETTINGS.getProperty(prefix + "id")); // NOI18N. final String expName = SETTINGS.getProperty(prefix + "name"); // NOI18N. final Optional<String> expDescription = getOptional(prefix + "description", value -> value); // NOI18N. final ItemType expType = EnumValueFactory.INSTANCE.mapEnumValue(ItemType.class, SETTINGS.getProperty(prefix + "type")); // NOI18N. final int expLevel = Integer.parseInt(SETTINGS.getProperty(prefix + "level")); // NOI18N. final ItemRarity expRarity = EnumValueFactory.INSTANCE.mapEnumValue(ItemRarity.class, SETTINGS.getProperty(prefix + "rarity")); // NOI18N.\ final CoinAmount expVendorValue = CoinAmount.ofCopper(Integer.parseInt(SETTINGS.getProperty(prefix + "vendor_value"))); // NOI18N.) final OptionalInt expDefaultSkin = getOptionalInt(prefix + "default_skin"); // NOI18N. assertNotNull(expName); final String lang = SETTINGS.getProperty("lang"); // NOI18N. final Optional<Item> value = GW2APIClient.create() .apiLevel(APILevel.V2) .endPoint("items") // NOI18N. .language(lang) .id(idToTest) .queryObject(Item.class); assertTrue(value.isPresent()); assertEquals(expId, value.get().getId()); assertEquals(expName, value.get().getName()); assertEquals(expDescription, value.get().getDescription()); assertEquals(expType, value.get().getType()); assertEquals(expLevel, value.get().getLevel()); assertEquals(expRarity, value.get().getRarity()); assertEquals(expVendorValue, value.get().getVendorValue()); assertEquals(expDefaultSkin, value.get().getDefaultSkin()); } @Test public void testSkins() { System.out.println("testSkins"); // NOI18N. final int[] ids = Arrays.stream(SETTINGS.getProperty("skins.ids").split(",")) // NOI18N. .mapToInt(Integer::parseInt) .toArray(); Arrays.stream(ids) .forEach(this::testSkin); } private void testSkin(final int idToTest) { System.out.printf("testSkin(%d)%n", idToTest); // NOI18N. final String prefix = String.format("skin.%d.", idToTest); // NOI18N. final int expId = Integer.parseInt(SETTINGS.getProperty(prefix + "id")); // NOI18N. final String expName = SETTINGS.getProperty(prefix + "name"); // NOI18N. final Optional<String> expDescription = getOptional(prefix + "description", value -> value); // NOI18N. final SkinType expType = EnumValueFactory.INSTANCE.mapEnumValue(SkinType.class, SETTINGS.getProperty(prefix + "type")); // NOI18N. final SkinRarity expRarity = EnumValueFactory.INSTANCE.mapEnumValue(SkinRarity.class, SETTINGS.getProperty(prefix + "rarity")); // NOI18N.\ assertNotNull(expName); final String lang = SETTINGS.getProperty("lang"); // NOI18N. final Optional<Skin> value = GW2APIClient.create() .apiLevel(APILevel.V2) .endPoint("skins") // NOI18N. .language(lang) .id(idToTest) .queryObject(Skin.class); assertTrue(value.isPresent()); assertEquals(expId, value.get().getId()); assertEquals(expName, value.get().getName()); assertEquals(expDescription, value.get().getDescription()); assertEquals(expType, value.get().getType()); assertEquals(expRarity, value.get().getRarity()); } @Test public void testSkills() { System.out.println("testSkills"); // NOI18N. final int[] ids = Arrays.stream(SETTINGS.getProperty("skills.ids").split(",")) // NOI18N. .mapToInt(Integer::parseInt) .toArray(); Arrays.stream(ids) .forEach(this::testSkill); } private void testSkill(final int idToTest) { System.out.printf("testSkill(%d)%n", idToTest); // NOI18N. final String prefix = String.format("skill.%d.", idToTest); // NOI18N. final int expId = Integer.parseInt(SETTINGS.getProperty(prefix + "id")); // NOI18N. final String expName = SETTINGS.getProperty(prefix + "name"); // NOI18N. final Optional<String> expDescription = getOptional(prefix + "description", value -> value); // NOI18N. final SkillType expType = EnumValueFactory.INSTANCE.mapEnumValue(SkillType.class, SETTINGS.getProperty(prefix + "type")); // NOI18N. assertNotNull(expName); final String lang = SETTINGS.getProperty("lang"); // NOI18N. final Optional<Skill> value = GW2APIClient.create() .apiLevel(APILevel.V2) .endPoint("skills") // NOI18N. .language(lang) .id(idToTest) .queryObject(Skill.class); assertTrue(value.isPresent()); assertEquals(expId, value.get().getId()); assertEquals(expName, value.get().getName()); assertEquals(expDescription, value.get().getDescription()); assertEquals(expType, value.get().getType()); } @Test public void testAbilities() { System.out.println("testAbilities"); // NOI18N. final int[] ids = Arrays.stream(SETTINGS.getProperty("abilities.ids").split(",")) // NOI18N. .mapToInt(Integer::parseInt) .toArray(); Arrays.stream(ids) .forEach(this::testAbility); } private void testAbility(final int idToTest) { System.out.printf("testAbility(%d)%n", idToTest); // NOI18N. final String prefix = String.format("ability.%d.", idToTest); // NOI18N. final int expId = Integer.parseInt(SETTINGS.getProperty(prefix + "id")); // NOI18N. final String expName = SETTINGS.getProperty(prefix + "name"); // NOI18N. final String expDescription = SETTINGS.getProperty(prefix + "description"); // NOI18N. assertNotNull(expName); final String lang = SETTINGS.getProperty("lang"); // NOI18N. final Optional<Ability> value = GW2APIClient.create() .apiLevel(APILevel.V2) .endPoint("wvw/abilities") // NOI18N. .language(lang) .id(idToTest) .queryObject(Ability.class); assertTrue(value.isPresent()); assertEquals(expId, value.get().getId()); assertEquals(expName, value.get().getName()); assertEquals(expDescription, value.get().getDescription()); } @Test public void testObjectives() { System.out.println("testObjectives"); // NOI18N. final String[] ids = SETTINGS.getProperty("objectives.ids").split(","); // NOI18N. Arrays.stream(ids) .forEach(this::testObjective); } private void testObjective(final String idToTest) { System.out.printf("testObjective(%s)%n", idToTest); // NOI18N. final String prefix = String.format("objective.%s.", idToTest); // NOI18N. final String expId = SETTINGS.getProperty(prefix + "id"); // NOI18N. final String expName = SETTINGS.getProperty(prefix + "name"); // NOI18N. final int expSectorId = Integer.parseInt(SETTINGS.getProperty(prefix + "sector_id")); // NOI18N. final ObjectiveType expType = EnumValueFactory.INSTANCE.mapEnumValue(ObjectiveType.class, SETTINGS.getProperty(prefix + "type")); // NOI18N. final MapType expMapType = EnumValueFactory.INSTANCE.mapEnumValue(MapType.class, SETTINGS.getProperty(prefix + "map_type")); // NOI18N. final int expMapId = Integer.parseInt(SETTINGS.getProperty(prefix + "map_id")); // NOI18N. assertNotNull(expId); assertNotNull(expName); final String lang = SETTINGS.getProperty("lang"); // NOI18N. final Optional<Objective> value = GW2APIClient.create() .apiLevel(APILevel.V2) .endPoint("wvw/objectives") // NOI18N. .language(lang) .id(idToTest) .queryObject(Objective.class); assertTrue(value.isPresent()); assertEquals(expId, value.get().getId()); assertEquals(expName, value.get().getName()); assertEquals(expSectorId, value.get().getSectorId()); assertEquals(expType, value.get().getType()); assertEquals(expMapType, value.get().getMapType()); assertEquals(expMapId, value.get().getMapId()); } @Test public void testBank() { System.out.println("testBank"); // NOI18N. final int expSlotNumber = Integer.parseInt(SETTINGS.getProperty("bank.slot_number")); // NOI18N. final List<BankSlot> value = GW2APIClient.create() .apiLevel(APILevel.V2) .applicationKey(SETTINGS.getProperty("app.key")) // NOI18N. .endPoint("account/bank") // NOI18N. .queryArray(BankSlot.class); assertFalse(value.isEmpty()); assertEquals(expSlotNumber, value.size()); } @Test public void testWallet() { System.out.println("testWallet"); // NOI18N. final List<CurrencyAmount> value = GW2APIClient.create() .apiLevel(APILevel.V2) .applicationKey(SETTINGS.getProperty("app.key")) // NOI18N. .endPoint("account/wallet") // NOI18N. .queryArray(CurrencyAmount.class); assertFalse(value.isEmpty()); } @Test public void testCurrencies() { System.out.println("testCurrencies"); // NOI18N. final String lang = SETTINGS.getProperty("lang"); // NOI18N. final List<Currency> value = GW2APIClient.create() .apiLevel(APILevel.V2) .language(lang) .endPoint("currencies") // NOI18N. .queryArray(Currency.class); assertFalse(value.isEmpty()); } @Test public void testBackstoryAnswers() { System.out.println("testBackstoryAnswers"); // NOI18N. final String[] ids = SETTINGS.getProperty("backstory.answers.ids").split(","); // NOI18N. Arrays.stream(ids) .forEach(this::testBackstoryAnswer); } private void testBackstoryAnswer(final String idToTest) { System.out.printf("testBackstoryAnswer(%s)%n", idToTest); // NOI18N. final String prefix = String.format("backstory.answer.%s.", idToTest); // NOI18N. final String expId = SETTINGS.getProperty(prefix + "id"); // NOI18N. assertNotNull(expId); final String lang = SETTINGS.getProperty("lang"); // NOI18N. final Optional<BackstoryAnswer> value = GW2APIClient.create() .apiLevel(APILevel.V2) .endPoint("backstory/answers") // NOI18N. .language(lang) .id(idToTest) .queryObject(BackstoryAnswer.class); assertTrue(value.isPresent()); assertEquals(expId, value.get().getId()); } private <T> Optional<T> getOptional(final String property, Function<String, T> converter) { final String value = SETTINGS.getProperty(property); return (value == null) ? Optional.empty() : Optional.of(converter.apply(value)); } private OptionalInt getOptionalInt(final String property) { final String value = SETTINGS.getProperty(property); return (value == null) ? OptionalInt.empty() : OptionalInt.of(Integer.parseInt(value)); } }
package hex.quantile; import hex.ModelBuilder; import hex.ModelCategory; import water.Key; import water.MRTask; import water.H2O; import water.Scope; import water.fvec.*; import water.util.ArrayUtils; import water.util.Log; import java.util.Arrays; /** * Quantile model builder... building a simple QuantileModel */ public class Quantile extends ModelBuilder<QuantileModel,QuantileModel.QuantileParameters,QuantileModel.QuantileOutput> { private int _ncols; @Override protected boolean logMe() { return false; } // Called from Nano thread; start the Quantile Job on a F/J thread public Quantile( QuantileModel.QuantileParameters parms ) { super(parms); init(false); } @Override public Driver trainModelImpl() { return new QuantileDriver(); } @Override public long progressUnits() { return train().numCols()*_parms._probs.length; } @Override public ModelCategory[] can_build() { return new ModelCategory[]{ModelCategory.Unknown}; } // any number of chunks is fine - don't rebalance - it's not worth it for a few passes over the data (at most) @Override protected int desiredChunks(final Frame original_fr, boolean local) { return 1; } /** Initialize the ModelBuilder, validating all arguments and preparing the * training frame. This call is expected to be overridden in the subclasses * and each subclass will start with "super.init();". This call is made * by the front-end whenever the GUI is clicked, and needs to be fast; * heavy-weight prep needs to wait for the trainModel() call. * * Validate the probs. */ @Override public void init(boolean expensive) { super.init(expensive); for( double p : _parms._probs ) if( p < 0.0 || p > 1.0 ) error("_probs","Probabilities must be between 0 and 1"); _ncols = train().numCols()-numSpecialCols(); //offset/weights/nfold - should only ever be weights if ( numSpecialCols() == 1 && _weights == null) throw new IllegalArgumentException("The only special Vec that is supported for Quantiles is observation weights."); if ( numSpecialCols() >1 ) throw new IllegalArgumentException("Cannot handle more than 1 special vec (weights)"); } private static class SumWeights extends MRTask<SumWeights> { double sum; @Override public void map(Chunk c, Chunk w) { for (int i=0;i<c.len();++i) if (!c.isNA(i)) { double wt = w.atd(i); // For now: let the user give small weights, results are probably not very good (same as for wtd.quantile in R) sum += wt; } } @Override public void reduce(SumWeights mrt) { sum+=mrt.sum; } } private class QuantileDriver extends Driver { @Override public void compute2() { QuantileModel model = null; try { Scope.enter(); _parms.read_lock_frames(_job); // Fetch & read-lock source frame init(true); // The model to be built model = new QuantileModel(dest(), _parms, new QuantileModel.QuantileOutput(Quantile.this)); model._output._parameters = _parms; model._output._quantiles = new double[_ncols][_parms._probs.length]; model.delete_and_lock(_job); // Run the main Quantile Loop Vec vecs[] = train().vecs(); for( int n=0; n<_ncols; n++ ) { if( _job.stop_requested() ) return; // Stopped/cancelled Vec vec = vecs[n]; if (vec.isBad()) { model._output._quantiles[n] = new double[_parms._probs.length]; Arrays.fill(model._output._quantiles[n], Double.NaN); continue; } double sumRows=_weights == null ? vec.length()-vec.naCnt() : new SumWeights().doAll(vec, _weights).sum; // Compute top-level histogram Histo h1 = new Histo(vec.min(),vec.max(),0,sumRows,vec.isInt()); h1 = _weights==null ? h1.doAll(vec) : h1.doAll(vec, _weights); // For each probability, see if we have it exactly - or else run // passes until we do. for( int p = 0; p < _parms._probs.length; p++ ) { double prob = _parms._probs[p]; Histo h = h1; // Start from the first global histogram model._output._iterations++; // At least one iter per-prob-per-column while( Double.isNaN(model._output._quantiles[n][p] = h.findQuantile(prob,_parms._combine_method)) ) { h = _weights == null ? h.refinePass(prob).doAll(vec) : h.refinePass(prob).doAll(vec, _weights); // Full pass at higher resolution model._output._iterations++; // also count refinement iterations } // Update the model model.update(_job); // Update model in K/V store _job.update(1); // One unit of work } StringBuilder sb = new StringBuilder(); sb.append("Quantile: iter: ").append(model._output._iterations).append(" Qs=").append(Arrays.toString(model._output._quantiles[n])); Log.debug(sb); } } finally { if( model != null ) model.unlock(_job); _parms.read_unlock_frames(_job); Scope.exit(model == null ? null : model._key); } tryComplete(); } } public static class StratifiedQuantilesTask extends H2O.H2OCountedCompleter<StratifiedQuantilesTask> { // INPUT final double _prob; final Vec _response; //vec to compute quantile for final Vec _weights; //obs weights final Vec _strata; //continuous integer range mapping into the _quantiles[id][] final QuantileModel.CombineMethod _combine_method; // OUTPUT public double[/*strata*/] _quantiles; public StratifiedQuantilesTask(H2O.H2OCountedCompleter cc, double prob, Vec response, // response Vec weights, // obs weights Vec strata, // stratification (can be null) QuantileModel.CombineMethod combine_method) { super(cc); _response = response; _prob=prob; _combine_method=combine_method; _weights=weights; _strata=strata; } @Override public void compute2() { int nstrata = _strata == null ? 1 : (int) (_strata.max() - _strata.min() + 1); Log.info("Computing quantiles for " + nstrata + " different strata."); _quantiles = new double[nstrata]; Vec weights = _weights != null ? _weights : _response.makeCon(1); for (int i=0;i<nstrata;++i) { //loop over nodes Vec newWeights = weights.makeCopy(); //only keep weights for this stratum (node), set rest to 0 if (_strata!=null) new ZeroOutWeights((int) (_strata.min() + i)).doAll(_strata, newWeights); double sumRows = new SumWeights().doAll(_response, newWeights).sum; Histo h = new Histo(_response.min(), _response.max(), 0, sumRows, _response.isInt()); h.doAll(_response, newWeights); while (Double.isNaN(_quantiles[i] = h.findQuantile(_prob, _combine_method))) { h = h.refinePass(_prob).doAll(_response, newWeights); } newWeights.remove(); } if (_weights != weights) weights.remove(); tryComplete(); } private static class ZeroOutWeights extends MRTask<ZeroOutWeights> { ZeroOutWeights(int stratumToKeep) { this.stratumToKeep = stratumToKeep; } int stratumToKeep; @Override public void map(Chunk strata, Chunk newW) { for (int i=0; i<strata._len; ++i) { // Log.info("NID:" + ((int) strata.at8(i))); if ((int) strata.at8(i) != stratumToKeep) newW.set(i, 0); } } } } private final static class Histo extends MRTask<Histo> { private static final int NBINS = 1024; // Default bin count private final int _nbins; // Actual bin count private final double _lb; // Lower bound of bin[0] private final double _step; // Step-size per-bin private final double _start_row; // Starting cumulative count of weighted rows for this lower-bound private final double _nrows; // Total datasets (weighted) rows private final boolean _isInt; // Column only holds ints // Big Data output result double _bins[/*nbins*/]; // Weighted count of rows in each bin double _mins[/*nbins*/]; // Smallest element in bin double _maxs[/*nbins*/]; // Largest element in bin private Histo(double lb, double ub, double start_row, double nrows, boolean isInt) { boolean is_int = (isInt && (ub - lb < NBINS)); _nbins = is_int ? (int) (ub - lb + 1) : NBINS; _lb = lb; double ulp = Math.ulp(Math.max(Math.abs(lb), Math.abs(ub))); _step = is_int ? 1 : (ub + ulp - lb) / _nbins; _start_row = start_row; _nrows = nrows; _isInt = isInt; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("range : " + _lb + " ... " + (_lb + _nbins * _step)); sb.append("\npsum0 : " + _start_row); sb.append("\ncounts: " + Arrays.toString(_bins)); sb.append("\nmaxs : " + Arrays.toString(_maxs)); sb.append("\nmins : " + Arrays.toString(_mins)); sb.append("\n"); return sb.toString(); } @Override public void map(Chunk chk, Chunk weight) { _bins = new double[_nbins]; _mins = new double[_nbins]; _maxs = new double[_nbins]; Arrays.fill(_mins, Double.MAX_VALUE); Arrays.fill(_maxs, -Double.MAX_VALUE); double d; for (int row = 0; row < chk._len; row++) { double w = weight.atd(row); if (w == 0) continue; if (!Double.isNaN(d = chk.atd(row))) { // na.rm=true double idx = (d - _lb) / _step; if (!(0.0 <= idx && idx < _bins.length)) continue; int i = (int) idx; if (_bins[i] == 0) _mins[i] = _maxs[i] = d; // Capture unique value else { if (d < _mins[i]) _mins[i] = d; if (d > _maxs[i]) _maxs[i] = d; } _bins[i] += w; // Bump row counts by row weight } } } @Override public void map(Chunk chk) { map(chk, new C0DChunk(1, chk.len())); } @Override public void reduce(Histo h) { for (int i = 0; i < _nbins; i++) { // Keep min/max if (_mins[i] > h._mins[i]) _mins[i] = h._mins[i]; if (_maxs[i] < h._maxs[i]) _maxs[i] = h._maxs[i]; } ArrayUtils.add(_bins, h._bins); } /** @return Quantile for probability prob, or NaN if another pass is needed. */ double findQuantile( double prob, QuantileModel.CombineMethod method ) { double p2 = prob*(_nrows-1); // Desired fractional row number for this probability long r2 = (long)p2; int loidx = findBin(r2); // Find bin holding low value double lo = (loidx == _nbins) ? binEdge(_nbins) : _maxs[loidx]; if( loidx<_nbins && r2==p2 && _mins[loidx]==lo ) return lo; // Exact row number, exact bin? Then quantile is exact long r3 = r2+1; int hiidx = findBin(r3); // Find bin holding high value double hi = (hiidx == _nbins) ? binEdge(_nbins) : _mins[hiidx]; if( loidx==hiidx ) // Somewhere in the same bin? return (lo==hi) ? lo : Double.NaN; // Only if bin is constant, otherwise must refine the bin // Split across bins - the interpolate between the hi of the lo bin, and // the lo of the hi bin return computeQuantile(lo,hi,r2,_nrows,prob,method); } private double binEdge( int idx ) { return _lb+_step*idx; } // bin for row; can be _nbins if just off the end (normally expect 0 to nbins-1) // row == position in (weighted) population private int findBin( double row ) { long sum = (long)_start_row; for( int i=0; i<_nbins; i++ ) if( (long)row < (sum += _bins[i]) ) return i; return _nbins; } // Run another pass over the data, with refined endpoints, to home in on // the exact elements for this probability. Histo refinePass( double prob ) { double prow = prob*(_nrows-1); // Desired fractional row number for this probability long lorow = (long)prow; // Lower integral row number int loidx = findBin(lorow); // Find bin holding low value // If loidx is the last bin, then high must be also the last bin - and we // have an exact quantile (equal to the high bin) and we didn't need // another refinement pass assert loidx < _nbins; double lo = _mins[loidx]; // Lower end of range to explore // If probability does not hit an exact row, we need the elements on // either side - so the next row up from the low row long hirow = lorow==prow ? lorow : lorow+1; int hiidx = findBin(hirow); // Find bin holding high value // Upper end of range to explore - except at the very high end cap double hi = hiidx==_nbins ? binEdge(_nbins) : _maxs[hiidx]; long sum = (long)_start_row; for( int i=0; i<loidx; i++ ) sum += _bins[i]; return new Histo(lo,hi,sum,_nrows,_isInt); } } /** Compute the correct final quantile from these 4 values. If the lo and hi * elements are equal, use them. However if they differ, then there is no * single value which exactly matches the desired quantile. There are * several well-accepted definitions in this case - including picking either * the lo or the hi, or averaging them, or doing a linear interpolation. * @param lo the highest element less than or equal to the desired quantile * @param hi the lowest element greater than or equal to the desired quantile * @param row row number (zero based) of the lo element; high element is +1 * @return desired quantile. */ static double computeQuantile( double lo, double hi, double row, double nrows, double prob, QuantileModel.CombineMethod method ) { if( lo==hi ) return lo; // Equal; pick either if( method == null ) method= QuantileModel.CombineMethod.INTERPOLATE; switch( method ) { case INTERPOLATE: return linearInterpolate(lo,hi,row,nrows,prob); case AVERAGE: return 0.5*(hi+lo); case LOW: return lo; case HIGH: return hi; default: Log.info("Unknown even sample size quantile combination type: " + method + ". Doing linear interpolation."); return linearInterpolate(lo,hi,row,nrows,prob); } } private static double linearInterpolate(double lo, double hi, double row, double nrows, double prob) { // Unequal, linear interpolation double plo = (row+0)/(nrows-1); // Note that row numbers are inclusive on the end point, means we need a -1 double phi = (row+1)/(nrows-1); // Passed in the row number for the low value, high is the next row, so +1 assert plo <= prob && prob <= phi; return lo + (hi-lo)*(prob-plo)/(phi-plo); // Classic linear interpolation } }
package water.util; import water.*; import water.fvec.*; import java.text.DecimalFormat; import java.util.*; import static java.lang.StrictMath.sqrt; import static water.util.RandomUtils.getRNG; /* Bulk Array Utilities */ public class ArrayUtils { private static final byte[] EMPTY_BYTE_ARRAY = new byte[] {}; public static int[] cumsum(final int[] from) { int arryLen = from.length; int[] cumsumR = new int[arryLen]; int result = 0; for (int index = 0; index < arryLen; index++) { result += result+from[index]; cumsumR[index] = result; } return cumsumR; } // Sum elements of an array public static long sum(final long[] from) { long result = 0; for (long d: from) result += d; return result; } public static long sum(final long[] from, int startIdx, int endIdx) { long result = 0; for (int i = startIdx; i < endIdx; i++) result += from[i]; return result; } public static int sum(final int[] from) { int result = 0; for( int d : from ) result += d; return result; } public static long suml(final int[] from) { long result = 0; for( int d : from ) result += d; return result; } public static float sum(final float[] from) { float result = 0; for (float d: from) result += d; return result; } public static double sum(final double[] from) { double result = 0; for (double d: from) result += d; return result; } public static float[] reduceMin(float[] a, float[] b) { for (int i=0; i<a.length; ++i) a[i] = Math.min(a[i], b[i]); return a; } public static float[] reduceMax(float[] a, float[] b) { for (int i=0; i<a.length; ++i) a[i] = Math.max(a[i], b[i]); return a; } public static double[] reduceMin(double[] a, double[] b) { if (a == null) return b; if (b == null) return a; if (a.length <= b.length) { for (int i=0; i<a.length; ++i) a[i] = Math.min(a[i], b[i]); return a; } else { for (int i=0; i<b.length; ++i) b[i] = Math.min(b[i], a[i]); return b; } } public static double[] reduceMax(double[] a, double[] b) { if (a == null) return b; if (b == null) return a; if (a.length >= b.length) { for (int i=0; i<a.length; ++i) a[i] = Math.max(a[i], b[i]); return a; } else { for (int i=0; i<b.length; ++i) b[i] = Math.max(b[i], a[i]); return b; } } public static Vec reduceMin(Vec a, Vec b) { return new MRTask() { @Override public void map(Chunk[] cs){ Chunk ca = cs[0]; Chunk cb = cs[1]; for(int row = 0; row < ca._len; ++row) { ca.set(row, Math.min(ca.atd(row), cb.atd(row))); } } }.doAll(a, b)._fr.vecs()[0]; } public static Vec reduceMax(Vec a, Vec b) { return new MRTask() { @Override public void map(Chunk[] cs){ Chunk ca = cs[0]; Chunk cb = cs[1]; for(int row = 0; row < ca._len; ++row) { ca.set(row, Math.max(ca.atd(row), cb.atd(row))); } } }.doAll(a, b)._fr.vecs()[0]; } public static double innerProduct(double [] x, double [] y){ double result = 0; for (int i = 0; i < x.length; i++) result += x[i] * y[i]; return result; } public static double innerProductPartial(double [] x, int[] x_index, double [] y){ double result = 0; for (int i = 0; i < y.length; i++) result += x[x_index[i]] * y[i]; return result; } public static double [] mmul(double [][] M, double [] V) { double [] res = new double[M.length]; for(int i = 0; i < M.length; ++i) { double d = 0; for (int j = 0; j < V.length; ++j) { d += M[i][j] * V[j]; } res[i] = d; } return res; } public static double[][] outerProduct(double[] x, double[] y){ double[][] result = new double[x.length][y.length]; for(int i = 0; i < x.length; i++) { for(int j = 0; j < y.length; j++) result[i][j] = x[i] * y[j]; } return result; } public static<T extends Comparable<T>> int indexOf(T[] arr, T val) { int highIndex = arr.length-1; int compare0 = val.compareTo(arr[0]); // small shortcut if (compare0 == 0) return 0; int compareLast = val.compareTo(arr[highIndex]); if (compareLast==0) return highIndex; if (val.compareTo(arr[0])<0 || val.compareTo(arr[highIndex])>0) // end shortcut return -1; int count = 0; int numBins = arr.length; int lowIndex = 0; while (count < numBins) { int tryBin = (int) Math.floor((highIndex+lowIndex)*0.5); double compareVal = val.compareTo(arr[tryBin]); if (compareVal==0) return tryBin; else if (compareVal>0) lowIndex = tryBin; else highIndex = tryBin; count++; } return -1; } // return the sqrt of each element of the array. Will overwrite the original array in this case public static double[] sqrtArr(double [] x){ assert (x != null); int len = x.length; for (int index = 0; index < len; index++) { assert (x[index]>=0.0); x[index] = sqrt(x[index]); } return x; } public static double l2norm2(double [] x){ return l2norm2(x, false); } public static double l2norm2(double [][] xs, boolean skipLast){ double res = 0; for(double [] x:xs) res += l2norm2(x,skipLast); return res; } public static double l2norm2(double [] x, boolean skipLast){ double sum = 0; int last = x.length - (skipLast?1:0); for(int i = 0; i < last; ++i) sum += x[i]*x[i]; return sum; } public static double l2norm2(double[] x, double[] y) { // Computes \sum_{i=1}^n (x_i - y_i)^2 assert x.length == y.length; double sse = 0; for(int i = 0; i < x.length; i++) { double diff = x[i] - y[i]; sse += diff * diff; } return sse; } public static double l2norm2(double[][] x, double[][] y) { assert x.length == y.length && x[0].length == y[0].length; double sse = 0; for(int i = 0; i < x.length; i++) sse += l2norm2(x[i], y[i]); return sse; } public static double l1norm(double [] x){ return l1norm(x, false); } public static double l1norm(double [] x, boolean skipLast){ double sum = 0; int last = x.length -(skipLast?1:0); for(int i = 0; i < last; ++i) sum += x[i] >= 0?x[i]:-x[i]; return sum; } /** * Like the R norm for matrices, this function will calculate the maximum absolute col sum if type='o' or * return the maximum absolute row sum otherwise * @param arr * @param type * @return */ public static double rNorm(double[][] arr, char type) { double rnorm = Double.NEGATIVE_INFINITY; int numArr = arr.length; for (int rind = 0; rind < numArr; rind++) { double tempSum = 0.0; for (int cind = 0; cind < numArr; cind++) { tempSum += type == 'o' ? Math.abs(arr[rind][cind]) : Math.abs(arr[cind][rind]); } if (tempSum > rnorm) rnorm = tempSum; } return rnorm; } public static double linfnorm(double [] x, boolean skipLast){ double res = Double.NEGATIVE_INFINITY; int last = x.length -(skipLast?1:0); for(int i = 0; i < last; ++i) { if(x[i] > res) res = x[i]; if(-x[i] > res) res = -x[i]; } return res; } public static double l2norm(double[] x) { return Math.sqrt(l2norm2(x)); } public static double l2norm(double [] x, boolean skipLast){ return Math.sqrt(l2norm2(x, skipLast)); } public static double l2norm(double[] x, double[] y) { return Math.sqrt(l2norm2(x,y)); } public static double l2norm(double[][] x, double[][] y) { return Math.sqrt(l2norm2(x,y)); } // Add arrays, element-by-element public static byte[] add(byte[] a, byte[] b) { for(int i = 0; i < a.length; i++ ) a[i] += b[i]; return a; } public static int[] add(int[] a, int[] b) { for(int i = 0; i < a.length; i++ ) a[i] += b[i]; return a; } public static int[][] add(int[][] a, int[][] b) { for(int i = 0; i < a.length; i++ ) add(a[i],b[i]); return a; } public static long[] add(long[] a, long[] b) { if( b==null ) return a; for(int i = 0; i < a.length; i++ ) a[i] += b[i]; return a; } public static long[][] add(long[][] a, long[][] b) { for(int i = 0; i < a.length; i++ ) add(a[i],b[i]); return a; } public static long[][][] add(long[][][] a, long[][][] b) { for(int i = 0; i < a.length; i++ ) add(a[i],b[i]); return a; } public static float[] add(float[] a, float[] b) { if( b==null ) return a; for(int i = 0; i < a.length; i++ ) a[i] += b[i]; return a; } public static float[] add(float ca, float[] a, float cb, float[] b) { for(int i = 0; i < a.length; i++ ) a[i] = (ca * a[i]) + (cb * b[i]); return a; } public static float[][] add(float[][] a, float[][] b) { for(int i = 0; i < a.length; i++ ) add(a[i],b[i]); return a; } public static boolean[] or(boolean[] a, boolean[] b) { if (b==null)return a; for (int i = 0; i < a.length; i++) a[i] |= b[i]; return a; } public static double[][] deepClone(double [][] ary){ double [][] res = ary.clone(); for(int i = 0 ; i < res.length; ++i) res[i] = ary[i].clone(); return res; } public static <T extends Iced> T[][] deepClone(T [][] ary){ T [][] res = ary.clone(); for(int i = 0 ; i < res.length; ++i) res[i] = deepClone(res[i]); return res; } public static <T extends Iced> T[] deepClone(T [] ary){ T [] res = ary.clone(); for(int j = 0; j < res.length; ++j) if(res[j] != null) res[j] = (T)res[j].clone(); return res; } public static double[] add(double[] a, double[] b) { if( a==null ) return b; for(int i = 0; i < a.length; i++ ) a[i] += b[i]; return a; } public static double[] add(double[] a, double b) { for(int i = 0; i < a.length; i++ ) a[i] += b; return a; } public static int[] add(int[] a, int b) { for(int i = 0; i < a.length; i++ ) a[i] += b; return a; } public static double[] wadd(double[] a, double[] b, double w) { if( a==null ) return b; for(int i = 0; i < a.length; i++ ) a[i] += w*b[i]; return a; } public static double[] wadd(double[] a, double[] b, double [] c, double w) { if( a==null ) return b; for(int i = 0; i < a.length; i++ ) c[i] = a[i] + w*b[i]; return c; } // a <- b + c public static double[] add(double[] a, double[] b, double [] c) { for(int i = 0; i < a.length; i++ ) a[i] = b[i] + c[i]; return a; } public static double[][] add(double[][] a, double[][] b) { if (a == null) return b; for(int i = 0; i < a.length; i++ ) a[i] = add(a[i], b[i]); return a; } public static double[][][] add(double[][][] a, double[][][] b) { for(int i = 0; i < a.length; i++ ) a[i] = add(a[i],b[i]); return a; } public static double avg(double[] nums) { double sum = 0; for(double n: nums) sum+=n; return sum/nums.length; } public static double avg(long[] nums) { long sum = 0; for(long n: nums) sum+=n; return sum/nums.length; } public static long[] add(long[] nums, long a) { for (int i=0;i<nums.length;i++) nums[i] += a; return nums; } public static float[] div(float[] nums, int n) { for (int i=0; i<nums.length; i++) nums[i] /= n; return nums; } public static float[] div(float[] nums, float n) { assert !Float.isInfinite(n) : "Trying to divide " + Arrays.toString(nums) + " by " + n; // Almost surely not what you want for (int i=0; i<nums.length; i++) nums[i] /= n; return nums; } public static double[] div(double[] nums, double n) { assert !Double.isInfinite(n) : "Trying to divide " + Arrays.toString(nums) + " by " + n; // Almost surely not what you want for (int i=0; i<nums.length; i++) nums[i] /= n; return nums; } public static double[][] div(double[][] ds, long[] n) { for (int i=0; i<ds.length; i++) div(ds[i],n[i]); return ds; } public static double[][] div(double[][] ds, double[] n) { for (int i=0; i<ds.length; i++) div(ds[i],n[i]); return ds; } public static double[] div(double[] ds, long[] n) { for (int i=0; i<ds.length; i++) ds[i]/=n[i]; return ds; } public static double[] div(double[] ds, double[] n) { for (int i=0; i<ds.length; i++) ds[i]/=n[i]; return ds; } public static double[][] mult(double[][] ds, double[] n) { for (int i=0; i<ds.length; i++) mult(ds[i],n[i]); return ds; } public static float[] mult(float[] nums, float n) { // assert !Float.isInfinite(n) : "Trying to multiply " + Arrays.toString(nums) + " by " + n; // Almost surely not what you want for (int i=0; i<nums.length; i++) nums[i] *= n; return nums; } public static double[] mult(double[] nums, double n) { // assert !Double.isInfinite(n) : "Trying to multiply " + Arrays.toString(nums) + " by " + n; // Almost surely not what you want for (int i=0; i<nums.length; i++) nums[i] *= n; return nums; } public static double[][] mult(double[][] ary, double n) { if(ary == null) return null; for (double[] row : ary) mult(row, n); return ary; } public static double[] mult(double[] nums, double[] nums2) { for (int i=0; i<nums.length; i++) nums[i] *= nums2[i]; return nums; } public static double[] invert(double[] ary) { if(ary == null) return null; for(int i=0;i<ary.length;i++) ary[i] = 1. / ary[i]; return ary; } public static double[] multArrVec(double[][] ary, double[] nums) { if(ary == null) return null; double[] res = new double[ary.length]; return multArrVec(ary, nums, res); } public static double[] multArrVecPartial(double[][] ary, double[] nums, int[] numColInd) { if(ary == null) return null; double[] res = new double[ary.length]; for (int ind = 0; ind < ary.length; ind++) { res[ind] = innerProductPartial(nums, numColInd, ary[ind]); } return res; } public static double[] diagArray(double[][] ary) { if(ary == null) return null; int arraylen = ary.length; double[] res = new double[ary.length]; for (int index=0; index < arraylen; index++) res[index] = ary[index][index]; return res; } public static double[] multArrVec(double[][] ary, double[] nums, double[] res) { if(ary == null || nums == null) return null; assert ary[0].length == nums.length : "Inner dimensions must match: Got " + ary[0].length + " != " + nums.length; for(int i = 0; i < ary.length; i++) res[i] = innerProduct(ary[i], nums); return res; } public static double[] multVecArr(double[] nums, double[][] ary) { if(ary == null || nums == null) return null; assert nums.length == ary.length : "Inner dimensions must match: Got " + nums.length + " != " + ary.length; double[] res = new double[ary[0].length]; // number of columns for(int j = 0; j < ary[0].length; j++) { // go through each column res[j] = 0; for(int i = 0; i < ary.length; i++) // inner product of nums with each column of ary res[j] += nums[i] * ary[i][j]; } return res; } /* with no memory allocation for results. We assume the memory is already allocated. */ public static double[][] multArrArr(double[][] ary1, double[][] ary2, double[][] res) { if(ary1 == null || ary2 == null) return null; // Inner dimensions must match assert ary1[0].length == ary2.length : "Inner dimensions must match: Got " + ary1[0].length + " != " + ary2.length; for(int i = 0; i < ary1.length; i++) { for(int j = 0; j < ary2[0].length; j++) { double tmp = 0; for(int k = 0; k < ary1[0].length; k++) tmp += ary1[i][k] * ary2[k][j]; res[i][j] = tmp; } } return res; } /* with memory allocation for results */ public static double[][] multArrArr(double[][] ary1, double[][] ary2) { if(ary1 == null || ary2 == null) return null; double[][] res = new double[ary1.length][ary2[0].length]; return multArrArr(ary1, ary2, res); } public static double[][] transpose(double[][] ary) { if(ary == null) return null; double[][] res = new double[ary[0].length][ary.length]; for(int i = 0; i < res.length; i++) { for(int j = 0; j < res[0].length; j++) res[i][j] = ary[j][i]; } return res; } /*** * This function will perform transpose of triangular matrices only. If the original matrix is lower triangular, * the return matrix will be upper triangular and vice versa. * * @param ary * @return */ public static double[][] transposeTriangular(double[][] ary, boolean upperTriangular) { if(ary == null) return null; int rowNums = ary.length; double[][] res = new double[ary.length][]; // allocate as many rows as original matrix for (int rowIndex=0; rowIndex < rowNums; rowIndex++) { int colNum = upperTriangular?(rowIndex+1):(rowNums-rowIndex); res[rowIndex] = new double[colNum]; for (int colIndex=0; colIndex < colNum; colIndex++) res[rowIndex][colIndex] = ary[colIndex+rowIndex][rowIndex]; } return res; } public static <T> T[] cloneOrNull(T[] ary){return ary == null?null:ary.clone();} public static <T> T[][] transpose(T[][] ary) { if(ary == null|| ary.length == 0) return ary; T [][] res = Arrays.copyOf(ary,ary[0].length); for(int i = 0; i < res.length; ++i) res[i] = Arrays.copyOf(ary[0],ary.length); for(int i = 0; i < res.length; i++) { for(int j = 0; j < res[0].length; j++) res[i][j] = ary[j][i]; } return res; } /** * Provide array from start to end in steps of 1 * @param start beginning value (inclusive) * @param end ending value (exclusive) * @return specified range of integers */ public static int[] range(int start, int end) { int[] r = new int[end-start+1]; for(int i=0;i<r.length;i++) r[i] = i+start; return r; } /** * Given a n by k matrix X, form its Gram matrix * @param x Matrix of real numbers * @param transpose If true, compute n by n Gram of rows = XX' * If false, compute k by k Gram of cols = X'X * @return A symmetric positive semi-definite Gram matrix */ public static double[][] formGram(double[][] x, boolean transpose) { if (x == null) return null; int dim_in = transpose ? x[0].length : x.length; int dim_out = transpose ? x.length : x[0].length; double[][] xgram = new double[dim_out][dim_out]; // Compute all entries on and above diagonal if(transpose) { for (int i = 0; i < dim_in; i++) { // Outer product = x[i] * x[i]', where x[i] is col i for (int j = 0; j < dim_out; j++) { for (int k = j; k < dim_out; k++) xgram[j][k] += x[j][i] * x[k][i]; } } } else { for (int i = 0; i < dim_in; i++) { // Outer product = x[i]' * x[i], where x[i] is row i for (int j = 0; j < dim_out; j++) { for (int k = j; k < dim_out; k++) xgram[j][k] += x[i][j] * x[i][k]; } } } // Fill in entries below diagonal since Gram is symmetric for (int i = 0; i < dim_in; i++) { for (int j = 0; j < dim_out; j++) { for (int k = 0; k < j; k++) xgram[j][k] = xgram[k][j]; } } return xgram; } public static double[][] formGram(double[][] x) { return formGram(x, false); } public static double[] permute(double[] vec, int[] idx) { if(vec == null) return null; assert vec.length == idx.length : "Length of vector must match permutation vector length: Got " + vec.length + " != " + idx.length; double[] res = new double[vec.length]; for(int i = 0; i < vec.length; i++) res[i] = vec[idx[i]]; return res; } public static double[][] permuteCols(double[][] ary, int[] idx) { if(ary == null) return null; assert ary[0].length == idx.length : "Number of columns must match permutation vector length: Got " + ary[0].length + " != " + idx.length; double[][] res = new double[ary.length][ary[0].length]; for(int j = 0; j < ary[0].length; j++) { for(int i = 0; i < ary.length; i++) res[i][j] = ary[i][idx[j]]; } return res; } public static double[][] permuteRows(double[][] ary, int[] idx) { if(ary == null) return null; assert ary.length == idx.length : "Number of rows must match permutation vector length: Got " + ary.length + " != " + idx.length; double[][] res = new double[ary.length][ary[0].length]; for(int i = 0; i < ary.length; i++) res[i] = permute(ary[i], idx); return res; } public static double [][] generateLineSearchVecs(double [] srcVec, double [] gradient, int n, final double step) { double [][] res = new double[n][]; double x = step; for(int i = 0; i < res.length; ++i) { res[i] = MemoryManager.malloc8d(srcVec.length); for(int j = 0; j < res[i].length; ++j) res[i][j] = srcVec[j] + gradient[j] * x; x *= step; } return res; } public static String arrayToString(int[] ary) { if (ary == null || ary.length==0 ) return ""; int m = ary.length - 1; StringBuilder sb = new StringBuilder(); for (int i = 0; ; i++) { sb.append(ary[i]); if (i == m) return sb.toString(); sb.append(", "); } } // Convert array of primitives to an array of Strings. public static String[] toString(long[] dom) { String[] result = new String[dom.length]; for (int i=0; i<dom.length; i++) result[i] = String.valueOf(dom[i]); return result; } public static String[] toString(int[] dom) { String[] result = new String[dom.length]; for (int i=0; i<dom.length; i++) result[i] = String.valueOf(dom[i]); return result; } public static String[] toString(Object[] ary) { String[] result = new String[ary.length]; for (int i=0; i<ary.length; i++) { Object o = ary[i]; if (o != null && o.getClass().isArray()) { Class klazz = ary[i].getClass(); result[i] = byte[].class.equals(klazz) ? Arrays.toString((byte[]) o) : short[].class.equals(klazz) ? Arrays.toString((short[]) o) : int[].class.equals(klazz) ? Arrays.toString((int[]) o) : long[].class.equals(klazz) ? Arrays.toString((long[]) o) : boolean[].class.equals(klazz) ? Arrays.toString((boolean[]) o) : float[].class.equals(klazz) ? Arrays.toString((float[]) o) : double[].class.equals(klazz) ? Arrays.toString((double[]) o) : Arrays.toString((Object[]) o); } else { result[i] = String.valueOf(o); } } return result; } public static <T> boolean contains(T[] arr, T target) { if (null == arr) return false; for (T t : arr) { if (t == target) return true; if (t != null && t.equals(target)) return true; } return false; } static public boolean contains(byte[] a, byte d) { for (byte anA : a) if (anA == d) return true; return false; } static public boolean contains(int[] a, int d) { for (int anA : a) if (anA == d) return true; return false; } public static byte[] subarray(byte[] a, int off, int len) { return Arrays.copyOfRange(a,off,off+len); } public static <T> T[] subarray(T[] a, int off, int len) { return Arrays.copyOfRange(a,off,off+len); } public static <T> T[][] subarray2DLazy(T[][] a, int columnOffset, int len) { return Arrays.copyOfRange(a, columnOffset, columnOffset + len); } /** Returns the index of the largest value in the array. * In case of a tie, an the index is selected randomly. */ public static int maxIndex(int[] from, Random rand) { assert rand != null; int result = 0; int maxCount = 0; // count of maximal element for a 1 item reservoir sample for( int i = 1; i < from.length; ++i ) { if( from[i] > from[result] ) { result = i; maxCount = 1; } else if( from[i] == from[result] ) { if( rand.nextInt(++maxCount) == 0 ) result = i; } } return result; } public static int maxIndex(float[] from, Random rand) { assert rand != null; int result = 0; int maxCount = 0; // count of maximal element for a 1 item reservoir sample for( int i = 1; i < from.length; ++i ) { if( from[i] > from[result] ) { result = i; maxCount = 1; } else if( from[i] == from[result] ) { if( rand.nextInt(++maxCount) == 0 ) result = i; } } return result; } public static int maxIndex(double[] from, Random rand) { assert rand != null; int result = 0; int maxCount = 0; // count of maximal element for a 1 item reservoir sample for( int i = 1; i < from.length; ++i ) { if( from[i] > from[result] ) { result = i; maxCount = 1; } else if( from[i] == from[result] ) { if( rand.nextInt(++maxCount) == 0 ) result = i; } } return result; } public static int maxIndex(int[] from) { int result = 0; for (int i = 1; i<from.length; ++i) if (from[i]>from[result]) result = i; return result; } public static int maxIndex(long[] from) { int result = 0; for (int i = 1; i<from.length; ++i) if (from[i]>from[result]) result = i; return result; } public static int maxIndex(long[] from, int off) { int result = off; for (int i = off+1; i<from.length; ++i) if (from[i]>from[result]) result = i; return result; } public static int maxIndex(float[] from) { int result = 0; for (int i = 1; i<from.length; ++i) if (from[i]>from[result]) result = i; return result; } public static int maxIndex(double[] from) { int result = 0; for (int i = 1; i<from.length; ++i) if (from[i]>from[result]) result = i; return result; } public static int minIndex(int[] from) { int result = 0; for (int i = 1; i<from.length; ++i) if (from[i]<from[result]) result = i; return result; } public static int minIndex(float[] from) { int result = 0; for (int i = 1; i<from.length; ++i) if (from[i]<from[result]) result = i; return result; } public static int minIndex(double[] from) { int result = 0; for (int i = 1; i<from.length; ++i) if (from[i]<from[result]) result = i; return result; } public static double maxValue(double[] ary) { return maxValue(ary,0,ary.length); } public static double maxValue(double[] ary, int from, int to) { double result = ary[from]; for (int i = from+1; i<to; ++i) if (ary[i]>result) result = ary[i]; return result; } public static float maxValue(float[] ary) { return maxValue(ary,0,ary.length); } public static float maxValue(float[] ary, int from, int to) { float result = ary[from]; for (int i = from+1; i<to; ++i) if (ary[i]>result) result = ary[i]; return result; } public static float minValue(float[] from) { float result = from[0]; for (int i = 1; i<from.length; ++i) if (from[i]<result) result = from[i]; return result; } public static double minValue(double[] ary, int from, int to) { double result = ary[from]; for (int i = from+1; i<to; ++i) if (ary[i]<result) result = ary[i]; return result; } public static double minValue(double[] from) { double result = from[0]; for (int i = 1; i<from.length; ++i) if (from[i]<result) result = from[i]; return result; } public static long maxValue(long[] from) { long result = from[0]; for (int i = 1; i<from.length; ++i) if (from[i]>result) result = from[i]; return result; } public static long maxValue(int[] from) { int result = from[0]; for (int i = 1; i<from.length; ++i) if (from[i]>result) result = from[i]; return result; } public static long minValue(long[] from) { long result = from[0]; for (int i = 1; i<from.length; ++i) if (from[i]<result) result = from[i]; return result; } public static long minValue(int[] from) { int result = from[0]; for (int i = 1; i<from.length; ++i) if (from[i]<result) result = from[i]; return result; } // Find an element with linear search & return it's index, or -1 public static <T> int find(T[] ts, T elem) {return find(ts,elem,0);} // Find an element with linear search & return it's index, or -1 public static <T> int find(T[] ts, T elem, int off) { for (int i = off; i < ts.length; i++) if (elem == ts[i] || elem.equals(ts[i])) return i; return -1; } public static int find(long[] ls, long elem) { for(int i=0; i<ls.length; ++i ) if( elem==ls[i] ) return i; return -1; } public static int find(int[] ls, int elem) { for(int i=0; i<ls.length; ++i ) if( elem==ls[i] ) return i; return -1; } // behaves like Arrays.binarySearch, but is slower -> Just good for tiny arrays (length<20) public static int linearSearch(double[] vals, double v) { final int N=vals.length; for (int i=0; i<N; ++i) { if (vals[i]==v) return i; if (vals[i]>v) return -i-1; } return -1; } private static final DecimalFormat default_dformat = new DecimalFormat("0. public static String pprint(double[][] arr){ return pprint(arr, default_dformat); } // pretty print Matrix(2D array of doubles) public static String pprint(double[][] arr,DecimalFormat dformat) { int colDim = 0; for( double[] line : arr ) colDim = Math.max(colDim, line.length); StringBuilder sb = new StringBuilder(); int max_width = 0; int[] ilengths = new int[colDim]; Arrays.fill(ilengths, -1); for( double[] line : arr ) { for( int c = 0; c < line.length; ++c ) { double d = line[c]; String dStr = dformat.format(d); if( dStr.indexOf('.') == -1 ) dStr += ".0"; ilengths[c] = Math.max(ilengths[c], dStr.indexOf('.')); int prefix = (d >= 0 ? 1 : 2); max_width = Math.max(dStr.length() + prefix, max_width); } } for( double[] line : arr ) { for( int c = 0; c < line.length; ++c ) { double d = line[c]; String dStr = dformat.format(d); if( dStr.indexOf('.') == -1 ) dStr += ".0"; for( int x = dStr.indexOf('.'); x < ilengths[c] + 1; ++x ) sb.append(' '); sb.append(dStr); if( dStr.indexOf('.') == -1 ) sb.append('.'); for( int i = dStr.length() - Math.max(0, dStr.indexOf('.')); i <= 5; ++i ) sb.append('0'); } sb.append("\n"); } return sb.toString(); } public static int[] unpackInts(long... longs) { int len = 2*longs.length; int result[] = new int[len]; int i = 0; for (long l : longs) { result[i++] = (int) (l & 0xffffffffL); result[i++] = (int) (l>>32); } return result; } private static void swap(long[] a, int i, int change) { long helper = a[i]; a[i] = a[change]; a[change] = helper; } private static void swap(int[] a, int i, int change) { int helper = a[i]; a[i] = a[change]; a[change] = helper; } /** * Extract a shuffled array of integers * @param a input array * @param n number of elements to extract * @param result array to store the results into (will be of size n) * @param seed random number seed * @param startIndex offset into a * @return result */ public static int[] shuffleArray(int[] a, int n, int result[], long seed, int startIndex) { if (n<=0) return result; Random random = getRNG(seed); if (result == null || result.length != n) result = new int[n]; result[0] = a[startIndex]; for (int i = 1; i < n; i++) { int j = random.nextInt(i+1); if (j!=i) result[i] = result[j]; result[j] = a[startIndex+i]; } for (int i = 0; i < n; ++i) assert(ArrayUtils.contains(result, a[startIndex+i])); return result; } public static void shuffleArray(int[] a, Random rng) { int n = a.length; for (int i = 0; i < n; i++) { int change = i + rng.nextInt(n - i); swap(a, i, change); } } // Generate a n by m array of random numbers drawn from the standard normal distribution public static double[][] gaussianArray(int n, int m) { return gaussianArray(n, m, System.currentTimeMillis()); } public static double[][] gaussianArray(int n, int m, long seed) { if(n <= 0 || m <= 0) return null; double[][] result = new double[n][m]; Random random = getRNG(seed); for(int i = 0; i < n; i++) { for(int j = 0; j < m; j++) result[i][j] = random.nextGaussian(); } return result; } public static double[] gaussianVector(int n) { return gaussianVector(n, System.currentTimeMillis()); } public static double[] gaussianVector(int n, long seed) { return gaussianVector(n, getRNG(seed)); } public static double[] gaussianVector(int n, Random random) { return gaussianVector(n, random, 0); } public static double[] gaussianVector(int n, long seed, int zeroNum) {return gaussianVector(n, getRNG(seed), zeroNum); } /** * Make a new array initialized to random Gaussian N(0,1) values with the given seed. * Make randomly selected {@code zeroNum} items zeros. Used in Extended isolation forest. * * @param n length of generated vector * @param zeroNum set randomly selected {@code zeroNum} items of vector to zero * @return array with gaussian values. Randomly selected {@code zeroNum} item values are zeros. */ public static double[] gaussianVector(int n, Random random, int zeroNum) { if(n <= 0) return null; double[] result = new double[n]; // ToDo: Get rid of this new action. for(int i = 0; i < n; i++) result[i] = random.nextGaussian(); for (int i = 0; i < zeroNum; i++) { int randomItem = Math.abs(random.nextInt()); randomItem = randomItem % n; result[randomItem] = 0; } return result; } /** Remove the array allocation in this one */ public static double[] gaussianVector(long seed, double[] vseed) { if (vseed == null) return null; Random random = getRNG(seed); int arraySize = vseed.length; for (int i=0; i < arraySize; i++) { vseed[i] = random.nextGaussian(); } return vseed; } /** Returns number of strings which represents a number. */ public static int numInts(String... a) { int cnt = 0; for(String s : a) if (isInt(s)) cnt++; return cnt; } public static boolean isInt(String... ary) { for(String s:ary) { if (s == null || s.isEmpty()) return false; int i = s.charAt(0) == '-' ? 1 : 0; for (; i < s.length(); i++) if (!Character.isDigit(s.charAt(i))) return false; } return true; } public static int[] toInt(String[] a, int off, int len) { int[] res = new int[len]; for(int i=0; i<len; i++) res[i] = Integer.valueOf(a[off + i]); return res; } public static Integer[] toIntegers(int[] a, int off, int len) { Integer [] res = new Integer[len]; for(int i = 0; i < len; ++i) res[i] = a[off+i]; return res; } public static int[] toInt(Integer[] a, int off, int len) { int [] res = new int[len]; for(int i = 0; i < len; ++i) res[i] = a[off+i]; return res; } /** Clever union of String arrays. * * For union of numeric arrays (strings represent integers) it is expecting numeric ordering. * For pure string domains it is expecting lexicographical ordering. * For mixed domains it always expects lexicographical ordering since such a domain were produce * by a parser which sort string with Array.sort(). * * PRECONDITION - string domain was sorted by Array.sort(String[]), integer domain by Array.sort(int[]) and switched to Strings !!! * * @param a a set of strings * @param b a set of strings * @return union of arrays * // TODO: add tests */ public static String[] domainUnion(String[] a, String[] b) { if (a == null) return b; if (b == null) return a; int cIinA = numInts(a); int cIinB = numInts(b); // Trivial case - all strings or ints, sorted if (cIinA==0 && cIinB==0 // only strings || cIinA==a.length && cIinB==b.length ) // only integers return union(a, b, cIinA==0); // Be little bit clever here: sort string representing numbers first and append // a,b were sorted by Array.sort() but can contain some numbers. // So sort numbers in numeric way, and then string in lexicographical order int[] ai = toInt(a, 0, cIinA); Arrays.sort(ai); // extract int part but sort it in numeric order int[] bi = toInt(b, 0, cIinB); Arrays.sort(bi); String[] ri = toString(union(ai,bi)); // integer part String[] si = union(a, b, cIinA, a.length - cIinA, cIinB, b.length - cIinB, true); return join(ri, si); } /** Union of given String arrays. * * The method expects ordering of domains in given order (lexicographical, numeric) * * @param a first array * @param b second array * @param lexo - true if domains are sorted in lexicographical order or false for numeric domains * @return union of values in given arrays. * * precondition lexo ? a,b are lexicographically sorted : a,b are sorted numerically * precondition a!=null &amp;&amp; b!=null */ public static String[] union(String[] a, String[] b, boolean lexo) { if (a == null) return b; if (b == null) return a; return union(a, b, 0, a.length, 0, b.length, lexo); } public static String[] union(String[] a, String[] b, int aoff, int alen, int boff, int blen, boolean lexo) { assert a!=null && b!=null : "Union expect non-null input!"; String[] r = new String[alen+blen]; int ia = aoff, ib = boff, i = 0; while (ia < aoff+alen && ib < boff+blen) { int c = lexo ? a[ia].compareTo(b[ib]) : Integer.valueOf(a[ia]).compareTo(Integer.valueOf(b[ib])); if ( c < 0) r[i++] = a[ia++]; else if (c == 0) { r[i++] = a[ia++]; ib++; } else r[i++] = b[ib++]; } if (ia < aoff+alen) while (ia<aoff+alen) r[i++] = a[ia++]; if (ib < boff+blen) while (ib<boff+blen) r[i++] = b[ib++]; return Arrays.copyOf(r, i); } /** Returns a union of given sorted arrays. */ public static int[] union(int[] a, int[] b) { assert a!=null && b!=null : "Union expect non-null input!"; int[] r = new int[a.length+b.length]; int ia = 0, ib = 0, i = 0; while (ia < a.length && ib < b.length) { int c = a[ia]-b[ib]; if ( c < 0) r[i++] = a[ia++]; else if (c == 0) { r[i++] = a[ia++]; ib++; } else r[i++] = b[ib++]; } if (ia < a.length) while (ia<a.length) r[i++] = a[ia++]; if (ib < b.length) while (ib<b.length) r[i++] = b[ib++]; return Arrays.copyOf(r, i); } public static long[] join(long[] a, long[] b) { long[] res = Arrays.copyOf(a, a.length+b.length); System.arraycopy(b, 0, res, a.length, b.length); return res; } public static float [] join(float[] a, float[] b) { float[] res = Arrays.copyOf(a, a.length+b.length); System.arraycopy(b, 0, res, a.length, b.length); return res; } public static <T> T[] join(T[] a, T[] b) { T[] res = Arrays.copyOf(a, a.length+b.length); System.arraycopy(b, 0, res, a.length, b.length); return res; } public static boolean hasNaNsOrInfs(double [] ary){ for(double d:ary) if(Double.isNaN(d) || Double.isInfinite(d)) return true; return false; } public static boolean hasNaNs(double [] ary){ for(double d:ary) if(Double.isNaN(d)) return true; return false; } public static boolean hasNaNsOrInfs(float [] ary){ for(float d:ary) if(Double.isNaN(d) || Double.isInfinite(d)) return true; return false; } /** Generates sequence (start, stop) of integers: (start, start+1, ...., stop-1) */ static public int[] seq(int start, int stop) { assert start<stop; int len = stop-start; int[] res = new int[len]; for(int i=start; i<stop;i++) res[i-start] = i; return res; } // warning: Non-Symmetric! Returns all elements in a that are not in b (but NOT the other way around) static public int[] difference(int a[], int b[]) { if (a == null) return new int[]{}; if (b == null) return a.clone(); int[] r = new int[a.length]; int cnt = 0; for (int x : a) { if (!contains(b, x)) r[cnt++] = x; } return Arrays.copyOf(r, cnt); } // warning: Non-Symmetric! Returns all elements in a that are not in b (but NOT the other way around) static public String[] difference(String a[], String b[]) { if (a == null) return new String[]{}; if (b == null) return a.clone(); String[] r = new String[a.length]; int cnt = 0; for (String s : a) { if (!contains(b, s)) r[cnt++] = s; } return Arrays.copyOf(r, cnt); } static public double[][] append( double[][] a, double[][] b ) { if( a==null ) return b; if( b==null ) return a; if( a.length==0 ) return b; if( b.length==0 ) return a; assert a[0].length==b[0].length; double[][] c = Arrays.copyOf(a,a.length+b.length); System.arraycopy(b,0,c,a.length,b.length); return c; } static public byte[] append( byte[] a, byte[] b ) { if( a==null ) return b; if( b==null ) return a; if( a.length==0 ) return b; if( b.length==0 ) return a; byte[] c = Arrays.copyOf(a,a.length+b.length); System.arraycopy(b,0,c,a.length,b.length); return c; } static public int[] append( int[] a, int[] b ) { if( a==null ) return b; if( b==null ) return a; if( a.length==0 ) return b; if( b.length==0 ) return a; int[] c = Arrays.copyOf(a,a.length+b.length); System.arraycopy(b,0,c,a.length,b.length); return c; } static public long[] append( long[] a, long[] b ) { if( a==null ) return b; if( b==null ) return a; if( a.length==0 ) return b; if( b.length==0 ) return a; long[] c = Arrays.copyOf(a,a.length+b.length); System.arraycopy(b,0,c,a.length,b.length); return c; } static public double[] append( double[] a, double[] b ) { if( a==null ) return b; if( b==null ) return a; if( a.length==0 ) return b; if( b.length==0 ) return a; double[] c = Arrays.copyOf(a,a.length+b.length); System.arraycopy(b,0,c,a.length,b.length); return c; } static public String[] append( String[] a, String[] b ) { if( a==null ) return b; if( b==null ) return a; if( a.length==0 ) return b; if( b.length==0 ) return a; String[] c = Arrays.copyOf(a,a.length+b.length); System.arraycopy(b,0,c,a.length,b.length); return c; } // Java7+ @SafeVarargs public static <T> T[] append(T[] a, T... b) { if( a==null ) return b; T[] tmp = Arrays.copyOf(a,a.length+b.length); System.arraycopy(b,0,tmp,a.length,b.length); return tmp; } public static int[] append(int[] a, int b) { if( a==null || a.length == 0) return new int[]{b}; int[] tmp = Arrays.copyOf(a,a.length+1); tmp[a.length] = b; return tmp; } static public String[] prepend(String[] ary, String s) { if (ary==null) return new String[] { s }; String[] nary = new String[ary.length+1]; nary[0] = s; System.arraycopy(ary,0,nary,1,ary.length); return nary; } static public <T> T[] copyAndFillOf(T[] original, int newLength, T padding) { if(newLength < 0) throw new NegativeArraySizeException("The array size is negative."); T[] newArray = Arrays.copyOf(original, newLength); if(original.length < newLength) { System.arraycopy(original, 0, newArray, 0, original.length); Arrays.fill(newArray, original.length, newArray.length, padding); } else System.arraycopy(original, 0, newArray, 0, newLength); return newArray; } static public double[] copyAndFillOf(double[] original, int newLength, double padding) { if(newLength < 0) throw new NegativeArraySizeException("The array size is negative."); double[] newArray = new double[newLength]; if(original.length < newLength) { System.arraycopy(original, 0, newArray, 0, original.length); Arrays.fill(newArray, original.length, newArray.length, padding); } else System.arraycopy(original, 0, newArray, 0, newLength); return newArray; } static public long[] copyAndFillOf(long[] original, int newLength, long padding) { if(newLength < 0) throw new NegativeArraySizeException("The array size is negative."); long[] newArray = new long[newLength]; if(original.length < newLength) { System.arraycopy(original, 0, newArray, 0, original.length); Arrays.fill(newArray, original.length, newArray.length, padding); } else System.arraycopy(original, 0, newArray, 0, newLength); return newArray; } static public int[] copyAndFillOf(int[] original, int newLength, int padding) { if(newLength < 0) throw new NegativeArraySizeException("The array size is negative."); int[] newArray = new int[newLength]; if(original.length < newLength) { System.arraycopy(original, 0, newArray, 0, original.length); Arrays.fill(newArray, original.length, newArray.length, padding); } else System.arraycopy(original, 0, newArray, 0, newLength); return newArray; } static public double[] copyFromIntArray(int[] a) { double[] da = new double[a.length]; for(int i=0;i<a.length;++i) da[i] = a[i]; return da; } public static int [] sortedMerge(int[] a, int [] b) { int [] c = MemoryManager.malloc4(a.length + b.length); int i = 0, j = 0; for(int k = 0; k < c.length; ++k){ if(i == a.length) c[k] = b[j++]; else if(j == b.length)c[k] = a[i++]; else if(b[j] < a[i]) c[k] = b[j++]; else c[k] = a[i++]; } return c; } public static double [] sortedMerge(double[] a, double [] b) { double [] c = MemoryManager.malloc8d(a.length + b.length); int i = 0, j = 0; for(int k = 0; k < c.length; ++k){ if(i == a.length) c[k] = b[j++]; else if(j == b.length)c[k] = a[i++]; else if(b[j] < a[i]) c[k] = b[j++]; else c[k] = a[i++]; } return c; } // sparse sortedMerge (ids and vals) public static void sortedMerge(int[] aIds, double [] aVals, int[] bIds, double [] bVals, int [] resIds, double [] resVals) { int i = 0, j = 0; for(int k = 0; k < resIds.length; ++k){ if(i == aIds.length){ System.arraycopy(bIds,j,resIds,k,resIds.length-k); System.arraycopy(bVals,j,resVals,k,resVals.length-k); j = bIds.length; break; } if(j == bIds.length) { System.arraycopy(aIds,i,resIds,k,resIds.length-k); System.arraycopy(aVals,i,resVals,k,resVals.length-k); i = aIds.length; break; } if(aIds[i] > bIds[j]) { resIds[k] = bIds[j]; resVals[k] = bVals[j]; ++j; } else { resIds[k] = aIds[i]; resVals[k] = aVals[i]; ++i; } } assert i == aIds.length && j == bIds.length; } public static String[] select(String[] ary, int[] idxs) { String [] res = new String[idxs.length]; for(int i = 0; i < res.length; ++i) res[i] = ary[idxs[i]]; return res; } public static String[] select(String[] ary, byte[] idxs) { String [] res = new String[idxs.length]; for(int i = 0; i < res.length; ++i) res[i] = ary[idxs[i]]; return res; } public static double[] select(double[] ary, int[] idxs) { double [] res = MemoryManager.malloc8d(idxs.length); for(int i = 0; i < res.length; ++i) res[i] = ary[idxs[i]]; return res; } public static int[] select(int[] ary, int[] idxs) { int [] res = MemoryManager.malloc4(idxs.length); for(int i = 0; i < res.length; ++i) res[i] = ary[idxs[i]]; return res; } public static byte[] select(byte[] array, int[] idxs) { byte[] res = MemoryManager.malloc1(idxs.length); for(int i = 0; i < res.length; ++i) res[i] = array[idxs[i]]; return res; } public static double [] expandAndScatter(double [] ary, int N, int [] ids) { assert ary.length == ids.length:"ary.length = " + ary.length + " != " + ids.length + " = ids.length"; double [] res = MemoryManager.malloc8d(N); for(int i = 0; i < ids.length; ++i) res[ids[i]] = ary[i]; return res; } /** * Sort an integer array of indices based on values * Updates indices in place, keeps values the same * @param idxs indices * @param values values */ public static void sort(final int[] idxs, final double[] values) { sort(idxs, values, 500); } public static void sort(final int[] idxs, final double[] values, int cutoff) { if (idxs.length < cutoff) { //hand-rolled insertion sort for (int i = 0; i < idxs.length; i++) { for (int j = i; j > 0 && values[idxs[j - 1]] > values[idxs[j]]; j int tmp = idxs[j]; idxs[j] = idxs[j - 1]; idxs[j - 1] = tmp; } } } else { Integer[] d = new Integer[idxs.length]; for (int i = 0; i < idxs.length; ++i) d[i] = idxs[i]; // Arrays.parallelSort(d, new Comparator<Integer>() { Arrays.sort(d, new Comparator<Integer>() { @Override public int compare(Integer x, Integer y) { return values[x] < values[y] ? -1 : (values[x] > values[y] ? 1 : 0); } }); for (int i = 0; i < idxs.length; ++i) idxs[i] = d[i]; } } public static double [] subtract (double [] a, double [] b) { double [] c = MemoryManager.malloc8d(a.length); subtract(a,b,c); return c; } public static double[] subtract (double [] a, double [] b, double [] c) { for(int i = 0; i < a.length; ++i) c[i] = a[i] - b[i]; return c; } /** Flatenize given array (skips null arrays) * * Example: [[1,2], null, [3,null], [4]] -> [1,2,3,null,4] * @param arr array of arrays * @param <T> any type * @return flattened array, if input was null return null, if input was empty return null */ public static <T> T[] flat(T[][] arr) { if (arr == null) return null; if (arr.length == 0) return null; int tlen = 0; for (T[] t : arr) tlen += (t != null) ? t.length : 0; T[] result = Arrays.copyOf(arr[0], tlen); int j = arr[0].length; for (int i = 1; i < arr.length; i++) { if (arr[i] == null) continue; System.arraycopy(arr[i], 0, result, j, arr[i].length); j += arr[i].length; } return result; } public static double [][] convertTo2DMatrix(double [] x, int N) { assert x.length % N == 0: "number of coefficient should be divisible by number of coefficients per class "; int len = x.length/N; // N is number of coefficients per class double [][] res = new double[len][]; for(int i = 0; i < len; ++i) { // go through each class res[i] = MemoryManager.malloc8d(N); System.arraycopy(x,i*N,res[i],0,N); } return res; } public static Object[][] zip(Object[] a, Object[] b) { if (a.length != b.length) throw new IllegalArgumentException("Cannot zip arrays of different lengths!"); Object[][] result = new Object[a.length][2]; for (int i = 0; i < a.length; i++) { result[i][0] = a[i]; result[i][1] = b[i]; } return result; } public static <K, V> int crossProductSize(Map<K, V[]> hyperSpace) { int size = 1; for (Map.Entry<K,V[]> entry : hyperSpace.entrySet()) { V[] value = entry.getValue(); size *= value != null ? value.length : 1; } return size; } public static Integer[] interval(Integer start, Integer end) { return interval(start, end, 1); } public static Integer[] interval(Integer start, Integer end, Integer step) { int len = 1 + (end - start) / step; // Include both ends of interval Integer[] result = new Integer[len]; for(int i = 0, value = start; i < len; i++, value += step) { result[i] = value; } return result; } public static Float[] interval(Float start, Float end, Float step) { int len = 1 + (int)((end - start) / step); // Include both ends of interval Float[] result = new Float[len]; Float value = start; for(int i = 0; i < len; i++, value = start + i*step) { result[i] = value; } return result; } public static Double[] interval(Double start, Double end, Double step) { int len = 1 + (int)((end - start) / step); // Include both ends of interval Double[] result = new Double[len]; Double value = start; for(int i = 0; i < len; i++, value = start + i*step) { result[i] = value; } return result; } public static String [] remove(String [] ary, String s) { if(s == null)return ary; int cnt = 0; int idx = find(ary,s); while(idx >= 0) { ++cnt; idx = find(ary,s,++idx); } if(cnt == 0)return ary; String [] res = new String[ary.length-cnt]; int j = 0; for(String x:ary) if(!x.equals(s)) res[j++] = x; return res; } public static int[] sorted_set_diff(int[] x, int[] y) { assert isSorted(x); assert isSorted(y); int [] res = new int[x.length]; int j = 0, k = 0; for(int i = 0; i < x.length; i++){ while(j < y.length && y[j] < x[i])j++; if(j == y.length || y[j] != x[i]) res[k++] = x[i]; } return Arrays.copyOf(res,k); } /* This class is written to copy the contents of a frame to a 2-D double array. */ public static class FrameToArray extends MRTask<FrameToArray> { int _startColIndex; // first column index to extract int _endColIndex; // last column index to extract int _rowNum; // number of columns in public double[][] _frameContent; public FrameToArray(int startCol, int endCol, long rowNum, double[][] frameContent) { assert ((startCol >= 0) && (endCol >= startCol) && (rowNum > 0)); _startColIndex = startCol; _endColIndex = endCol; _rowNum = (int) rowNum; int colNum = endCol-startCol+1; if (frameContent == null) { // allocate memory here if user has not provided one _frameContent = MemoryManager.malloc8d(_rowNum, colNum); } else { // make sure we are passed the correct size 2-D double array assert (_rowNum == frameContent.length && frameContent[0].length == colNum); for (int index = 0; index < colNum; index++) { // zero fill use array Arrays.fill(frameContent[index], 0.0); } _frameContent = frameContent; } } @Override public void map(Chunk[] c) { assert _endColIndex < c.length; int endCol = _endColIndex+1; int rowOffset = (int) c[0].start(); // real row index int chkRows = c[0]._len; for (int rowIndex = 0; rowIndex < chkRows; rowIndex++) { for (int colIndex = _startColIndex; colIndex < endCol; colIndex++) { _frameContent[rowIndex+rowOffset][colIndex-_startColIndex] = c[colIndex].atd(rowIndex); } } } @Override public void reduce(FrameToArray other) { ArrayUtils.add(_frameContent, other._frameContent); } public double[][] getArray() { return _frameContent; } } /* This class is written to a 2-D array to the frame instead of allocating new memory every time. */ public static class CopyArrayToFrame extends MRTask<CopyArrayToFrame> { int _startColIndex; // first column index to extract int _endColIndex; // last column index to extract int _rowNum; // number of columns in public double[][] _frameContent; public CopyArrayToFrame(int startCol, int endCol, long rowNum, double[][] frameContent) { assert ((startCol >= 0) && (endCol >= startCol) && (rowNum > 0)); _startColIndex = startCol; _endColIndex = endCol; _rowNum = (int) rowNum; int colNum = endCol-startCol+1; assert (_rowNum == frameContent.length && frameContent[0].length == colNum); _frameContent = frameContent; } @Override public void map(Chunk[] c) { assert _endColIndex < c.length; int endCol = _endColIndex+1; int rowOffset = (int) c[0].start(); // real row index int chkRows = c[0]._len; for (int rowIndex = 0; rowIndex < chkRows; rowIndex++) { for (int colIndex = _startColIndex; colIndex < endCol; colIndex++) { c[colIndex].set(rowIndex, _frameContent[rowIndex+rowOffset][colIndex-_startColIndex]); } } } } /** Create a new frame based on given row data. * @param key Key for the frame * @param names names of frame columns * @param rows data given in the form of rows * @return new frame which contains columns named according given names and including given data */ public static Frame frame(Key<Frame> key, String[] names, double[]... rows) { assert names == null || names.length == rows[0].length; Futures fs = new Futures(); Vec[] vecs = new Vec[rows[0].length]; Key<Vec>[] keys = Vec.VectorGroup.VG_LEN1.addVecs(vecs.length); int rowLayout = -1; for( int c = 0; c < vecs.length; c++ ) { AppendableVec vec = new AppendableVec(keys[c], Vec.T_NUM); NewChunk chunk = new NewChunk(vec, 0); for (double[] row : rows) chunk.addNum(row[c]); chunk.close(0, fs); if( rowLayout== -1) rowLayout = vec.compute_rowLayout(); vecs[c] = vec.close(rowLayout,fs); } fs.blockForPending(); Frame fr = new Frame(key, names, vecs); if( key != null ) DKV.put(key, fr); return fr; } public static Frame frame(double[]... rows) { return frame(null, rows); } public static Frame frame(String[] names, double[]... rows) { return frame(Key.<Frame>make(), names, rows); } public static Frame frame(String name, Vec vec) { Frame f = new Frame(); f.add(name, vec); return f; } /** * Remove b from a, both a,b are assumed to be sorted. */ public static int[] removeSorted(int [] a, int [] b) { int [] indeces = new int[b.length]; indeces[0] = Arrays.binarySearch(a,0,a.length,b[0]); if(indeces[0] < 0) throw new NoSuchElementException("value " + b[0] + " not found in the first array."); for(int i = 1; i < b.length; ++i) { indeces[i] = Arrays.binarySearch(a,indeces[i-1],a.length,b[i]); if(indeces[i] < 0) throw new NoSuchElementException("value " + b[i] + " not found in the first array."); } return removeIds(a,indeces); } public static int[] removeIds(int[] x, int[] ids) { int [] res = new int[x.length-ids.length]; int j = 0; for(int i = 0; i < x.length; ++i) if(j == ids.length || i != ids[j]) res[i-j] = x[i]; else ++j; return res; } public static double[] removeIds(double[] x, int[] ids) { double [] res = new double[x.length-ids.length]; int j = 0; for(int i = 0; i < x.length; ++i) if(j == ids.length || i != ids[j]) res[i-j] = x[i]; else ++j; return res; } public static boolean hasNzs(double[] x) { if(x == null) return false; for(double d:x) if(d != 0) return true; return false; } public static int countNonzeros(double[] beta) { int res = 0; for(double d:beta) if(d != 0)++res; return res; } public static long[] subtract(long n, long[] nums) { for (int i=0; i<nums.length; i++) nums[i] = n - nums[i]; return nums; } public static <T> T[] remove( T[] ary, int id) { if(id < 0 || id >= ary.length) return Arrays.copyOf(ary,ary.length); if(id == ary.length-1) return Arrays.copyOf(ary,id); if(id == 0) return Arrays.copyOfRange(ary,1,ary.length); return append(Arrays.copyOf(ary,id), Arrays.copyOfRange(ary,id+1,ary.length)); } public static byte[] remove(byte[] ary, int id) { if(id < 0 || id >= ary.length) return Arrays.copyOf(ary,ary.length); if(id == ary.length-1) return Arrays.copyOf(ary,id); if(id == 0) return Arrays.copyOfRange(ary,1,ary.length); return append(Arrays.copyOf(ary,id), Arrays.copyOfRange(ary,id+1,ary.length)); } public static int[] remove(int[] ary, int id) { if(id < 0 || id >= ary.length) return Arrays.copyOf(ary,ary.length); if(id == ary.length-1) return Arrays.copyOf(ary,id); if(id == 0) return Arrays.copyOfRange(ary,1,ary.length); return append(Arrays.copyOf(ary,id), Arrays.copyOfRange(ary,id+1,ary.length)); } public static long[] remove(long[] ary, int id) { if(id < 0 || id >= ary.length) return Arrays.copyOf(ary,ary.length); if(id == ary.length-1) return Arrays.copyOf(ary,id); if(id == 0) return Arrays.copyOfRange(ary,1,ary.length); return append(Arrays.copyOf(ary,id), Arrays.copyOfRange(ary,id+1,ary.length)); } public static double[] padUniformly(double[] origPoints, int newLength) { int origLength = origPoints.length; if (newLength <= origLength || origLength<=1) return origPoints; int extraPoints = newLength - origLength; int extraPointsPerBin = extraPoints/(origLength-1); double[] res = new double[newLength]; int pos=0; int rem = extraPoints - extraPointsPerBin*(origLength-1); for (int i=0;i<origLength-1;++i) { double startPos = origPoints[i]; double delta = origPoints[i+1]-startPos; int ext = extraPointsPerBin + (i<rem ? 1 : 0); res[pos++] = startPos; for (int j=0;j<ext;++j) res[pos++] = startPos + (j+0.5) / ext * delta; } res[pos] = origPoints[origLength-1]; return res; } // See HistogramTest JUnit for tests public static double[] makeUniqueAndLimitToRange(double[] splitPoints, double min, double maxEx) { double last= splitPoints[0]; double[] uniqueValidPoints = new double[splitPoints.length+2]; int count=0; // keep all unique points that are minimally overlapping with min..maxEx for (int i = 0; i< splitPoints.length; ++i) { double pos = splitPoints[i]; // first one if (pos >= min && count==0) { uniqueValidPoints[count++]= min; if (pos> min) uniqueValidPoints[count++]=pos; last=pos; } //last one else if (pos > maxEx) { break; } // regular case: add to uniques else if (pos > min && pos < maxEx && (i==0 || pos != last)) { uniqueValidPoints[count++] = pos; last = pos; } } if (count==0) { return new double[]{min}; } return Arrays.copyOfRange(uniqueValidPoints,0,count); } // See HistogramTest JUnit for tests public static double[] limitToRange(double[] sortedSplitPoints, double min, double maxEx) { int start=Arrays.binarySearch(sortedSplitPoints, min); if (start<0) start=-start-1; // go back one more to return at least one value if (start==sortedSplitPoints.length) start // go back one more to include the min (inclusive) if (sortedSplitPoints[start] > min && start>0) start assert(start>=0); assert(sortedSplitPoints[start] <= min); int end=Arrays.binarySearch(sortedSplitPoints, maxEx); if (end<0) end=-end-1; assert(end>0 && end<= sortedSplitPoints.length): "End index ("+end+") should be > 0 and <= split points size ("+sortedSplitPoints.length+"). "+collectArrayInfo(sortedSplitPoints); assert(end>=start): "End index ("+end+") should be >= start index ("+start+"). " + collectArrayInfo(sortedSplitPoints); assert(sortedSplitPoints[end-1] < maxEx): "Split valued at index end-1 ("+sortedSplitPoints[end-1]+") should be < maxEx value ("+maxEx+"). "+collectArrayInfo(sortedSplitPoints); return Arrays.copyOfRange(sortedSplitPoints,start,end); } private static String collectArrayInfo(double[] array){ StringBuilder info = new StringBuilder("Array info - length: "+array.length + " values: "); for(double value: array){ info.append(value+" "); } return info.toString(); } public static double[] extractCol(int i, double[][] ary) { double [] res = new double[ary.length]; for(int j = 0; j < ary.length; ++j) res[j] = ary[j][i]; return res; } public static long encodeAsLong(byte[] b) { return encodeAsLong(b, 0, b.length); } public static long encodeAsLong(byte[] b, int off, int len) { assert len <= 8 : "Cannot encode more then 8 bytes into long: len = " + len; long r = 0; int shift = 0; for(int i = 0; i < len; i++) { r |= (b[i + off] & 0xFFL) << shift; shift += 8; } return r; } public static int encodeAsInt(byte[] b) { assert b.length == 4 : "Cannot encode more than 4 bytes into int: len = " + b.length; return (b[0]&0xFF)+((b[1]&0xFF)<<8)+((b[2]&0xFF)<<16)+((b[3]&0xFF)<<24); } public static int encodeAsInt(byte[] bs, int at) { if (at + 4 > bs.length) throw new IndexOutOfBoundsException("Cannot encode more than 4 bytes into int: len = " + bs.length + ", pos=" + at); return (bs[at]&0xFF)+((bs[at+1]&0xFF)<<8)+((bs[at+2]&0xFF)<<16)+((bs[at+3]&0xFF)<<24); } public static byte[] decodeAsInt(int what, byte[] bs, int at) { if (bs.length < at + 4) throw new IndexOutOfBoundsException("Wrong position " + at + ", array length is " + bs.length); for (int i = at; i < at+4 && i < bs.length; i++) { bs[i] = (byte)(what&0xFF); what >>= 8; } return bs; } /** Transform given long numbers into byte array. * Highest 8-bits of the first long will stored in the first field of returned byte array. * * Example: * 0xff18000000000000L -> new byte[] { 0xff, 0x18, 0, 0, 0, 0, 0, 0} */ public static byte[] toByteArray(long ...nums) { if (nums == null || nums.length == 0) return EMPTY_BYTE_ARRAY; byte[] result = new byte[8*nums.length]; int c = 0; for (long n : nums) { for (int i = 0; i < 8; i++) { result[c*8 + i] = (byte) ((n >>> (56 - 8 * i)) & 0xFF); } c++; } return result; } public static byte[] toByteArray(int[] ary) { byte[] r = new byte[ary.length]; for (int i = 0; i < ary.length; i++) { r[i] = (byte) (ary[i] & 0xff); } return r; } public static boolean equalsAny(long value, long...lhs) { if (lhs == null || lhs.length == 0) return false; for (long lhValue : lhs) { if (value == lhValue) return true; } return false; } /** * Convert an array of primitive types into an array of corresponding boxed types. Due to quirks of Java language * this cannot be done in any generic way -- there should be a separate function for each use case... * @param arr input array of `char`s * @return output array of `Character`s */ public static Character[] box(char[] arr) { Character[] res = new Character[arr.length]; for (int i = 0; i < arr.length; i++) res[i] = arr[i]; return res; } /** * Convert an ArrayList of Integers to a primitive int[] array. */ public static int[] toPrimitive(ArrayList<Integer> arr) { int[] res = new int[arr.size()]; for (int i = 0; i < res.length; i++) res[i] = arr.get(i); return res; } public static boolean isSorted(int[] vals) { for (int i = 1; i < vals.length; ++i) if (vals[i - 1] > vals[i]) return false; return true; } public static boolean isSorted(double[] vals) { for (int i = 1; i < vals.length; ++i) if (vals[i - 1] > vals[i]) return false; return true; } public static byte[] constAry(int len, byte b) { byte[] ary = new byte[len]; Arrays.fill(ary, b); return ary; } public static double[] constAry(int len, double c) { double[] ary = new double[len]; Arrays.fill(ary, c); return ary; } public static double[] toDouble(float[] floats) { if (floats == null) return null; double[] ary = new double[floats.length]; for (int i = 0; i < floats.length; i++) ary[i] = floats[i]; return ary; } public static double[] toDouble(int[] ints) { if (ints == null) return null; double[] ary = new double[ints.length]; for (int i = 0; i < ints.length; i++) ary[i] = ints[i]; return ary; } public static boolean isInstance(Object object, Class[] comparedClasses) { for (Class c : comparedClasses) { if (c.isInstance(object)) return true; } return false; } /** * Count number of occurrences of element in given array. * * @param array array in which number of occurrences should be counted. * @param element element whose occurrences should be counted. * * @return number of occurrences of element in given array. */ public static int occurrenceCount(byte[] array, byte element) { int cnt = 0; for (byte b : array) if (b == element) cnt++; return cnt; } }
package imagej; // this interface is for delineating how a data value is represented in storage. an example is Unsigned12Bit. it can be encoded as 12 BITs, 1.5 UBYTEs, // all of one USHORT (wasting 4 bits), or 12/32 of a UINT32 public interface DataEncoding { StorageType getBackingType(); double getNumTypesPerValue(); // For one 12 bit sample using ubyte encoding value == 3.0. // For one 12 bit sample using uncompacted ushort encoding value = 1.0. // For one 12 bit sample using compacted ushort encoding value = 0.75. // lets us know how to handle primitive array contents when changing them // also useful for calculating how much memory is allocated for a given type // would this be better served by having encoding have a "double getBytesPerValue()"??? }
package transform; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class Script { public List<String> m_warnings = new ArrayList<>(); private List<String> m_operations = new ArrayList<>(); // Temporary state, held only during a single MOVE resolution private List<String> head = new ArrayList<>(); private List<String> tail = new ArrayList<>(); private List<String> fromDiff; private List<String> toDiff; @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("# Generated: " + ZonedDateTime.now( ZoneOffset.UTC ) + " (UTC)\n#\n"); sb.append("# WARNINGS:\n#\n"); for (String s : m_warnings) { sb.append(s); sb.append("\n"); } if (m_warnings.isEmpty()) sb.append("# I got 99 problems, but your changes ain't one.\n"); sb.append("\n# SCRIPT:\n\nMODE FRAMED\n\n"); for (String s : m_operations) { sb.append(s); sb.append("\n"); } return sb.toString(); } public void resolveMove(String fromPath, String toPath) { List<String> from = Arrays.asList(fromPath.split(",")); List<String> to = Arrays.asList(toPath.split(",")); // make: // from = head + fromDiff + tail // to = head + toDiff + tail head = new ArrayList<>(); tail = new ArrayList<>(); fromDiff = new ArrayList<>(); toDiff = new ArrayList<>(); int i = 0; while ( from.get(i).equals(to.get(i)) ) head.add( from.get(i++) ); i = 0; while ( from.get( from.size()-i-1 ).equals(to.get( to.size()-i-1 )) ) { tail.add(0, from.get(from.size() - i - 1)); ++i; } fromDiff = from.subList( head.size(), from.size()-tail.size() ); toDiff = to.subList( head.size(), to.size()-tail.size() ); //System.err.println("head: " + head + " tail: " + tail + "\n\tfromDiff: " + fromDiff + "\n\ttoDiff: " + toDiff); if (Collections.frequency(fromDiff, "_list") != Collections.frequency(toDiff, "_list")) { m_warnings.add("# I dare not generate code for this diff, because the paths differ in number of lists.\n" + "# Please resolve the diff manually. (Severity: HIGH)" + "# " + fromPath + "\n# -> " + toPath); return; } List<String> operations = generatePivotPointMoves(); if (!operations.isEmpty()) { m_operations.add("# Resulting from observed grammar diff:\n# " + fromPath + "\n# -> " + toPath); m_operations.addAll(operations); m_operations.add(""); // empty line } } /** * Lists ("_list") forms pivots points of sorts in the transformation. In the diffing part of the path, * each list must be matched up to its transformed equivalence. If the number of "_list"s diff, the change * can't be resolved with any certainty (Which list should be collapsed?). */ private List<String> generatePivotPointMoves() { List<String> resultingOperations = new ArrayList<>(); boolean done; // Generate a move sequence for each _list pivot point do { done = true; int fromIndex = 0, toIndex = 0; while (fromIndex < fromDiff.size() && toIndex < toDiff.size()) { if (fromDiff.get(fromIndex).equals("_list") && toDiff.get(toIndex).equals("_list")) { List<String> sourceList = new ArrayList<>(); sourceList.addAll(head); sourceList.addAll(fromDiff.subList(0, fromIndex)); List<String> targetList = new ArrayList<>(); targetList.addAll(head); targetList.addAll(toDiff.subList(0, toIndex)); // Issue a command to make this move resultingOperations.addAll(generateMoveSequence(sourceList, targetList, 0, 0)); // Keep looking head.addAll(toDiff.subList(0, toIndex+1)); toDiff = toDiff.subList(toIndex+1, toDiff.size()); fromDiff = fromDiff.subList(fromIndex+1, fromDiff.size()); done = false; break; } if (!fromDiff.get(fromIndex).equals("_list")) ++fromIndex; if (!toDiff.get(toIndex).equals("_list")) ++toIndex; } } while (!done); //System.err.println("Remaining: " + fromDiff + " / " + toDiff); // Generate a move sequence for the remainder [last pivotpoint] -> end of toPath List<String> sourceList = new ArrayList<>(); sourceList.addAll(head); sourceList.addAll(fromDiff); List<String> targetList = new ArrayList<>(); targetList.addAll(head); targetList.addAll(toDiff); resultingOperations.addAll(generateMoveSequence(sourceList, targetList, 0, 0)); return resultingOperations; } private List<String> generateMoveSequence(List<String> sourcePath, List<String> targetPath, int startIndex, int indentation) { List<String> resultingOperations = new ArrayList<>(); for (int i = startIndex; i < Integer.min(sourcePath.size(), targetPath.size()); ++i) { if (sourcePath.get(i).equals("_list") && targetPath.get(i).equals("_list")) { List<String> newSourcePath = new ArrayList<>(); newSourcePath.addAll(sourcePath.subList(0, i)); newSourcePath.add("it"+indentation); newSourcePath.addAll(sourcePath.subList(i+1, sourcePath.size())); List<String> newTargetPath = new ArrayList<>(); newTargetPath.addAll(targetPath.subList(0, i)); newTargetPath.add("it"+indentation); newTargetPath.addAll(targetPath.subList(i+1, targetPath.size())); String tabs = ""; for (int j = 0; j < indentation; ++j) tabs += " "; String tabsP1 = ""; for (int j = 0; j < indentation+1; ++j) tabsP1 += " "; resultingOperations.add(tabs + "FOREACH it" + indentation + " : " + String.join(",", sourcePath.subList(0, i))); resultingOperations.add(tabs + "{"); List<String> nestedOps = generateMoveSequence(newSourcePath, newTargetPath, startIndex+1, indentation+1); resultingOperations.addAll(nestedOps); if (nestedOps.isEmpty()) resultingOperations.add(tabsP1 + "MOVE " + String.join(",",newSourcePath) + "\n" + tabsP1 + "-> " + String.join(",",newTargetPath)); resultingOperations.add(tabs + "}"); break; } } return resultingOperations; } }
package org.exist.messaging.xquery; import java.io.ByteArrayInputStream; import java.math.BigDecimal; import java.math.BigInteger; import java.util.Enumeration; import java.util.Properties; import javax.jms.BytesMessage; import javax.jms.Connection; import javax.jms.ConnectionFactory; import javax.jms.Destination; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.MessageConsumer; import javax.jms.MessageListener; import javax.jms.ObjectMessage; import javax.jms.Session; import javax.jms.TextMessage; import javax.naming.Context; import javax.naming.InitialContext; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.apache.log4j.Logger; import org.exist.Namespaces; import org.exist.dom.NodeProxy; import org.exist.memtree.DocumentImpl; import org.exist.memtree.SAXAdapter; import org.exist.messaging.configuration.JmsConfiguration; import org.exist.storage.BrokerPool; import org.exist.storage.DBBroker; import org.exist.validation.ValidationReport; import org.exist.xquery.XPathException; import org.exist.xquery.XQueryContext; import org.exist.xquery.functions.map.MapType; import org.exist.xquery.value.AtomicValue; import org.exist.xquery.value.Base64BinaryValueType; import org.exist.xquery.value.BinaryValue; import org.exist.xquery.value.BinaryValueFromInputStream; import org.exist.xquery.value.BooleanValue; import org.exist.xquery.value.DecimalValue; import org.exist.xquery.value.DoubleValue; import org.exist.xquery.value.FloatValue; import org.exist.xquery.value.FunctionReference; import org.exist.xquery.value.IntegerValue; import org.exist.xquery.value.Item; import org.exist.xquery.value.NodeValue; import org.exist.xquery.value.Sequence; import org.exist.xquery.value.StringValue; import org.exist.xquery.value.ValueSequence; import org.w3c.dom.Document; import org.w3c.dom.Node; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; /** * * @author wessels */ public class Receiver { private final static Logger LOG = Logger.getLogger(Receiver.class); private MyJMSListener myListener = new MyJMSListener(); private FunctionReference ref; private JmsConfiguration config; private XQueryContext context; Receiver(FunctionReference ref, JmsConfiguration config, XQueryContext context) { this.ref = ref; this.config = config; this.context = context; } /** * Start listener */ void start() { try { // Setup listener myListener.setFunctionReference(ref); myListener.setXQueryContext(context); // Setup Context Properties props = new Properties(); props.setProperty(Context.INITIAL_CONTEXT_FACTORY, config.getInitialContextFactory()); props.setProperty(Context.PROVIDER_URL, config.getProviderURL()); Context context = new InitialContext(props); // Setup connection ConnectionFactory connectionFactory = (ConnectionFactory) context.lookup(config.getConnectionFactory()); Connection connection = connectionFactory.createConnection(); // Setup session Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); // Setup destination Destination destination = (Destination) context.lookup(config.getDestination()); LOG.info("Destination=" + destination); // Setup consumer MessageConsumer messageConsumer = session.createConsumer(destination); messageConsumer.setMessageListener(myListener); // Start listener connection.start(); LOG.info("Receiver is ready"); } catch (Throwable t) { LOG.error(t.getMessage(), t); } } private static class MyJMSListener implements MessageListener { private FunctionReference functionReference; private XQueryContext xqueryContext; public MyJMSListener(){ // NOP } public MyJMSListener(FunctionReference functionReference, XQueryContext xqueryContext) { super(); this.functionReference=functionReference; this.xqueryContext=xqueryContext; } @Override public void onMessage(Message msg) { try { BrokerPool bp = BrokerPool.getInstance(); DBBroker broker1=bp.getBroker(); DBBroker broker2=bp.getBroker(); broker2.release(); broker1.release(); bp.release(broker2); bp.release(broker1); LOG.info(String.format("msgId='%s'", msg.getJMSMessageID())); // Copy property values into Maptype MapType msgProperties = getMessageProperties(msg, xqueryContext); MapType jmsProperties = getJmsProperties(msg, xqueryContext); // Show content Sequence content = null; if (msg instanceof TextMessage) { LOG.info("TextMessage"); content = new StringValue(((TextMessage) msg).getText()); } else if (msg instanceof ObjectMessage) { Object obj = ((ObjectMessage) msg).getObject(); LOG.info(obj.getClass().getCanonicalName()); if (obj instanceof BigInteger) { content = new IntegerValue((BigInteger) obj); } else if (obj instanceof Double) { content = new DoubleValue((Double) obj); } else if (obj instanceof BigDecimal) { content = new DecimalValue((BigDecimal) obj); } else if (obj instanceof Boolean) { content = new BooleanValue((Boolean) obj); } else if (obj instanceof Float) { content = new FloatValue((Float) obj); } else { LOG.error(String.format("Unable to convert %s", obj.toString())); } } else if(msg instanceof BytesMessage){ BytesMessage bm = (BytesMessage) msg; byte[] data = new byte[(int) bm.getBodyLength()]; bm.readBytes(data); // if XML(fragment) if ("xml".equalsIgnoreCase(bm.getStringProperty("exist.data.type"))) { ByteArrayInputStream bais = new ByteArrayInputStream(data); final ValidationReport report = new ValidationReport(); final SAXAdapter adapter = new SAXAdapter(xqueryContext); final SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); final InputSource src = new InputSource(bais); final SAXParser parser = factory.newSAXParser(); XMLReader xr = parser.getXMLReader(); xr.setErrorHandler(report); xr.setContentHandler(adapter); xr.setProperty(Namespaces.SAX_LEXICAL_HANDLER, adapter); xr.parse(src); if (report.isValid()){ //content=new NodeProxy(doc.); content = (DocumentImpl) adapter.getDocument(); } else { String txt = "Received document is not valid: " + report.toString(); throw new XPathException(txt); } } else { ByteArrayInputStream bais = new ByteArrayInputStream(data); BinaryValue bv = BinaryValueFromInputStream.getInstance(xqueryContext, new Base64BinaryValueType(), bais); content=bv; } } else { LOG.info(msg.getClass().getCanonicalName()); //content = msg.toString(); } LOG.info(String.format("content='%s' type='%s'", content, msg.getJMSType())); // Setup parameters callback function Sequence params[] = new Sequence[3]; params[0] = content; params[1] = msgProperties; params[2] = jmsProperties; // Execute callback function functionReference.evalFunction(null, null, params); } catch (JMSException ex) { LOG.error(ex); ex.printStackTrace(); } catch (XPathException ex) { LOG.error(ex); ex.printStackTrace(); } catch (Throwable ex) { LOG.error(ex); ex.printStackTrace(); } } public void setFunctionReference(FunctionReference ref) { this.functionReference = ref; } public void setXQueryContext(XQueryContext context) { this.xqueryContext = context; } private MapType getMessageProperties(Message msg, XQueryContext xqueryContext) throws XPathException, JMSException { // Copy property values into Maptype MapType map = new MapType(xqueryContext); Enumeration props = msg.getPropertyNames(); while (props.hasMoreElements()) { String elt = (String) props.nextElement(); String value = msg.getStringProperty(elt); add(map, elt, value); } return map; } private MapType getJmsProperties(Message msg, XQueryContext xqueryContext) throws XPathException, JMSException { // Copy property values into Maptype MapType map = new MapType(xqueryContext); add(map, "JMSMessageID", msg.getJMSMessageID()); add(map, "JMSCorrelationID", msg.getJMSCorrelationID()); add(map, "JMSType", msg.getJMSType()); add(map, "JMSPriority", ""+msg.getJMSPriority()); add(map, "JMSExpiration", ""+msg.getJMSExpiration()); add(map, "JMSTimestamp", ""+msg.getJMSTimestamp()); return map; } private void add(MapType map, String key, String value) throws XPathException { if (map != null && key != null && !key.isEmpty() && value != null) { map.add(new StringValue(key), new ValueSequence(new StringValue(value))); } } } }
// modification, are permitted provided that the following conditions are met: // documentation and/or other materials provided with the distribution. // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. package jodd.core; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.util.LinkedHashSet; import java.util.Set; /** * Methods that requires different implementations on various Java Platforms. */ public class JavaBridge { public static URL[] getURLs(Class clazz) { return getURLs(clazz.getClassLoader(), clazz); } /** * Returns urls for the classloader * * @param classLoader classloader in which to find urls * @return list of urls or {@code null} if not found */ public static URL[] getURLs(final ClassLoader classLoader) { return getURLs(classLoader, JavaBridge.class); } private static URL[] getURLs(ClassLoader classLoader, final Class clazz) { final Set<URL> urls = new LinkedHashSet<>(); while (classLoader != null) { if (classLoader instanceof URLClassLoader) { URLClassLoader urlClassLoader = (URLClassLoader) classLoader; return urlClassLoader.getURLs(); } URL url = classModuleUrl(classLoader, clazz); if (url != null) { urls.add(url); } classLoader = classLoader.getParent(); } return urls.toArray(new URL[urls.size()]); } private static URL classModuleUrl(ClassLoader classLoader, Class clazz) { if (clazz == null) { return null; } final String name = clazz.getName().replace('.', '/') + ".class"; URL url = classLoader.getResource(name); if (url == null) { return null; } // use root String urlString = url.toString(); int ndx = urlString.indexOf(name); urlString = urlString.substring(0, ndx) + urlString.substring(ndx + name.length()); try { return new URL(urlString); } catch (MalformedURLException ignore) { return null; } } }
/* * $Log$ * Revision 1.5 2000/03/15 12:53:02 apr * WatchCD off/on in answer method * * Revision 1.4 2000/03/14 12:58:49 apr * Autoanswer with ATS0=1 instead of RING+ATA * * Revision 1.3 2000/03/14 00:00:12 apr * Added answer method * * Revision 1.2 2000/03/01 14:44:45 apr * Changed package name to org.jpos * * Revision 1.1 2000/01/11 01:25:01 apr * moved non ISO-8583 related classes from jpos.iso to jpos.util package * (AntiHog LeasedLineModem LogEvent LogListener LogProducer * Loggeable Logger Modem RotateLogListener SimpleAntiHog SimpleDialupModem * SimpleLogListener SimpleLogProducer SystemMonitor V24) * * Revision 1.1 1999/11/24 18:08:56 apr * Added VISA 1 Support * */ package org.jpos.util; import java.io.*; import javax.comm.*; /** * Implements DialupModem * * @author <a href="mailto:apr@cs.com.uy">Alejandro P. Revilla</a> * @version $Revision$ $Date$ */ public class SimpleDialupModem implements Modem { V24 v24; String dialPrefix = "DT"; public final String[] resultCodes = { "OK\r", "CONNECT\r", "RING\r", "NO CARRIER\r", "ERROR\r", "CONNECT", "NO DIALTONE\r", "BUSY\r", "NO ANSWER\r" }; public SimpleDialupModem (V24 v24) { super(); this.v24 = v24; } public void setDialPrefix (String dialPrefix) { this.dialPrefix = dialPrefix; } private boolean checkAT() throws IOException { return v24.waitfor ("AT\r", resultCodes, 10000) == 0; } private void reset() throws IOException { try { v24.send ("AT\r"); Thread.sleep (250); if (v24.waitfor ("ATE1Q0V1H0\r", resultCodes, 1000) == 0) return; v24.dtr (false); Thread.sleep (1000); v24.dtr (true); Thread.sleep (1000); v24.send ("+++"); Thread.sleep (1000); } catch (InterruptedException e) { } v24.flushAndLog(); if (!checkAT()) throw new IOException ("Unable to reset"); } public void dial (String phoneNumber, long aproxTimeout) throws IOException { int rc; long expire = System.currentTimeMillis() + aproxTimeout; while (System.currentTimeMillis() < expire) { try { reset(); Thread.sleep (250); rc = v24.waitfor ( "ATB0M1X4L1"+dialPrefix+phoneNumber +"\r", resultCodes,45000 ); if (rc == 5) { Thread.sleep (500); // CD debouncing/settlement time break; } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { } } } public void hangup () throws IOException { reset(); if (v24.isConnected()) throw new IOException ("Could not hangup"); } public boolean isConnected() { return v24.isConnected(); } public void answer () throws IOException { v24.setWatchCD (false); v24.setAutoFlushReceiver(false); if (!checkAT()) throw new IOException ("unable to initialize modem (0)"); if (v24.waitfor ("ATB0V1Q0S0=1\r", resultCodes, 10000) != 0) throw new IOException ("unable to initialize modem (1)"); if (v24.waitfor ("CONNECT", 10*60*1000) != 0) throw new IOException ("NO CALLS so far - reinitializing"); v24.setAutoFlushReceiver(true); try { Thread.sleep (1000); } catch (InterruptedException e) { } v24.setAutoFlushReceiver(false); v24.setWatchCD (true); } }
package replicant; import arez.Disposable; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Objects; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; import javax.annotation.Nullable; import org.intellij.lang.annotations.Language; import org.realityforge.guiceyloops.shared.ValueUtil; import org.testng.annotations.Test; import replicant.messages.ChangeSet; import replicant.messages.ChannelChange; import replicant.messages.EntityChange; import replicant.messages.EntityChangeData; import replicant.messages.EntityChannel; import replicant.spy.AreaOfInterestStatusUpdatedEvent; import replicant.spy.ConnectFailureEvent; import replicant.spy.ConnectedEvent; import replicant.spy.DataLoadStatus; import replicant.spy.DisconnectFailureEvent; import replicant.spy.DisconnectedEvent; import replicant.spy.MessageProcessFailureEvent; import replicant.spy.MessageProcessedEvent; import replicant.spy.MessageReadFailureEvent; import replicant.spy.RestartEvent; import replicant.spy.SubscribeCompletedEvent; import replicant.spy.SubscribeFailedEvent; import replicant.spy.SubscribeRequestQueuedEvent; import replicant.spy.SubscribeStartedEvent; import replicant.spy.SubscriptionCreatedEvent; import replicant.spy.SubscriptionDisposedEvent; import replicant.spy.SubscriptionUpdateCompletedEvent; import replicant.spy.SubscriptionUpdateFailedEvent; import replicant.spy.SubscriptionUpdateRequestQueuedEvent; import replicant.spy.SubscriptionUpdateStartedEvent; import replicant.spy.UnsubscribeCompletedEvent; import replicant.spy.UnsubscribeFailedEvent; import replicant.spy.UnsubscribeRequestQueuedEvent; import replicant.spy.UnsubscribeStartedEvent; import static org.mockito.Mockito.*; import static org.testng.Assert.*; @SuppressWarnings( { "NonJREEmulationClassesInClientCode", "Duplicates" } ) public class ConnectorTest extends AbstractReplicantTest { @Test public void construct() throws Exception { final Disposable schedulerLock = pauseScheduler(); final ReplicantRuntime runtime = Replicant.context().getRuntime(); safeAction( () -> assertEquals( runtime.getConnectors().size(), 0 ) ); final SystemSchema schema = new SystemSchema( ValueUtil.randomInt(), ValueUtil.randomString(), new ChannelSchema[ 0 ], new EntitySchema[ 0 ] ); final TestConnector connector = TestConnector.create( schema ); assertEquals( connector.getSchema(), schema ); safeAction( () -> assertEquals( runtime.getConnectors().size(), 1 ) ); assertEquals( connector.getReplicantRuntime(), runtime ); safeAction( () -> assertEquals( connector.getReplicantContext().getSchemaService().contains( schema ), true ) ); safeAction( () -> assertEquals( connector.getState(), ConnectorState.DISCONNECTED ) ); schedulerLock.dispose(); safeAction( () -> assertEquals( connector.getState(), ConnectorState.CONNECTING ) ); } @Test public void dispose() { final ReplicantRuntime runtime = Replicant.context().getRuntime(); safeAction( () -> assertEquals( runtime.getConnectors().size(), 0 ) ); final TestConnector connector = TestConnector.create(); safeAction( () -> assertEquals( runtime.getConnectors().size(), 1 ) ); Disposable.dispose( connector ); safeAction( () -> assertEquals( runtime.getConnectors().size(), 0 ) ); } @Test public void testToString() throws Exception { final TestConnector connector = TestConnector.create(); assertEquals( connector.toString(), "Connector[Rose]" ); ReplicantTestUtil.disableNames(); assertEquals( connector.toString(), "replicant.Arez_TestConnector@" + Integer.toHexString( connector.hashCode() ) ); } @Test public void setConnection_whenConnectorProcessingMessage() throws Exception { final TestConnector connector = TestConnector.create(); final Connection connection = newConnection( connector ); pauseScheduler(); connector.pauseMessageScheduler(); final MessageResponse response = new MessageResponse( ValueUtil.randomString() ); connection.setCurrentMessageResponse( response ); final ChannelAddress address = new ChannelAddress( connector.getSchema().getId(), 0 ); final Subscription subscription = createSubscription( address, null, true ); connector.onConnection( ValueUtil.randomString() ); // Connection not swapped yet but will do one MessageProcess completes assertEquals( Disposable.isDisposed( subscription ), false ); assertEquals( connector.getConnection(), connection ); assertNotNull( connector.getPostMessageResponseAction() ); } @Test public void connect() { pauseScheduler(); final TestConnector connector = TestConnector.create(); safeAction( () -> assertEquals( connector.getState(), ConnectorState.DISCONNECTED ) ); safeAction( connector::connect ); verify( connector.getTransport() ).connect( any( Transport.OnConnect.class ), any( Transport.OnError.class ) ); safeAction( () -> assertEquals( connector.getState(), ConnectorState.CONNECTING ) ); } @Test public void connect_causesError() { pauseScheduler(); final TestConnector connector = TestConnector.create(); safeAction( () -> assertEquals( connector.getState(), ConnectorState.DISCONNECTED ) ); final IllegalStateException exception = new IllegalStateException(); doAnswer( i -> { throw exception; } ).when( connector.getTransport() ).connect( any( Transport.OnConnect.class ), any( Transport.OnError.class ) ); final IllegalStateException actual = expectThrows( IllegalStateException.class, () -> safeAction( connector::connect ) ); assertEquals( actual, exception ); safeAction( () -> assertEquals( connector.getState(), ConnectorState.ERROR ) ); } @Test public void disconnect() { pauseScheduler(); final TestConnector connector = TestConnector.create(); safeAction( () -> connector.setState( ConnectorState.CONNECTED ) ); safeAction( connector::disconnect ); verify( connector.getTransport() ).disconnect( any( SafeProcedure.class ), any( Transport.OnError.class ) ); safeAction( () -> assertEquals( connector.getState(), ConnectorState.DISCONNECTING ) ); } @Test public void disconnect_causesError() { pauseScheduler(); final TestConnector connector = TestConnector.create(); safeAction( () -> connector.setState( ConnectorState.CONNECTED ) ); final IllegalStateException exception = new IllegalStateException(); doAnswer( i -> { throw exception; } ).when( connector.getTransport() ).disconnect( any( SafeProcedure.class ), any( Transport.OnError.class ) ); final IllegalStateException actual = expectThrows( IllegalStateException.class, () -> safeAction( connector::disconnect ) ); assertEquals( actual, exception ); safeAction( () -> assertEquals( connector.getState(), ConnectorState.ERROR ) ); } @Test public void onDisconnected() { final TestConnector connector = TestConnector.create(); safeAction( () -> connector.setState( ConnectorState.CONNECTING ) ); safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(), RuntimeState.CONNECTING ) ); // Pause scheduler so runtime does not try to update state pauseScheduler(); safeAction( connector::onDisconnected ); safeAction( () -> assertEquals( connector.getState(), ConnectorState.DISCONNECTED ) ); safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(), RuntimeState.DISCONNECTED ) ); } @Test public void onDisconnected_generatesSpyMessage() throws Exception { final TestConnector connector = TestConnector.create(); safeAction( () -> connector.setState( ConnectorState.CONNECTING ) ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); // Pause scheduler so runtime does not try to update state pauseScheduler(); safeAction( connector::onDisconnected ); handler.assertEventCount( 1 ); handler.assertNextEvent( DisconnectedEvent.class, e -> assertEquals( e.getSchemaId(), connector.getSchema().getId() ) ); } @Test public void onDisconnectFailure() throws Exception { final TestConnector connector = TestConnector.create(); safeAction( () -> connector.setState( ConnectorState.CONNECTING ) ); safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(), RuntimeState.CONNECTING ) ); final Throwable error = new Throwable(); // Pause scheduler so runtime does not try to update state pauseScheduler(); safeAction( () -> connector.onDisconnectFailure( error ) ); safeAction( () -> assertEquals( connector.getState(), ConnectorState.ERROR ) ); safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(), RuntimeState.ERROR ) ); } @Test public void onDisconnectFailure_generatesSpyMessage() throws Exception { final TestConnector connector = TestConnector.create(); safeAction( () -> connector.setState( ConnectorState.CONNECTING ) ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); final Throwable error = new Throwable(); // Pause scheduler so runtime does not try to update state pauseScheduler(); safeAction( () -> connector.onDisconnectFailure( error ) ); handler.assertEventCount( 1 ); handler.assertNextEvent( DisconnectFailureEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getError(), error ); } ); } @Test public void onConnected() throws Exception { final TestConnector connector = TestConnector.create(); final Connection connection = new Connection( connector, ValueUtil.randomString() ); safeAction( () -> connector.setState( ConnectorState.CONNECTING ) ); safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(), RuntimeState.CONNECTING ) ); // Pause scheduler so runtime does not try to update state pauseScheduler(); final Field field = Connector.class.getDeclaredField( "_connection" ); field.setAccessible( true ); field.set( connector, connection ); safeAction( connector::onConnected ); safeAction( () -> assertEquals( connector.getState(), ConnectorState.CONNECTED ) ); safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(), RuntimeState.CONNECTED ) ); verify( connector.getTransport() ).bind( connection.getTransportContext() ); } @Test public void onConnected_generatesSpyMessage() throws Exception { final TestConnector connector = TestConnector.create(); newConnection( connector ); safeAction( () -> connector.setState( ConnectorState.CONNECTING ) ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); safeAction( connector::onConnected ); handler.assertEventCount( 1 ); handler.assertNextEvent( ConnectedEvent.class, e -> assertEquals( e.getSchemaId(), connector.getSchema().getId() ) ); } @Test public void onConnectFailure() throws Exception { final TestConnector connector = TestConnector.create(); safeAction( () -> connector.setState( ConnectorState.CONNECTING ) ); safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(), RuntimeState.CONNECTING ) ); final Throwable error = new Throwable(); // Pause scheduler so runtime does not try to update state pauseScheduler(); safeAction( () -> connector.onConnectFailure( error ) ); safeAction( () -> assertEquals( connector.getState(), ConnectorState.ERROR ) ); safeAction( () -> assertEquals( connector.getReplicantRuntime().getState(), RuntimeState.ERROR ) ); } @Test public void onConnectFailure_generatesSpyMessage() throws Exception { final TestConnector connector = TestConnector.create(); safeAction( () -> connector.setState( ConnectorState.CONNECTING ) ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); final Throwable error = new Throwable(); // Pause scheduler so runtime does not try to update state pauseScheduler(); safeAction( () -> connector.onConnectFailure( error ) ); handler.assertEventCount( 1 ); handler.assertNextEvent( ConnectFailureEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getError(), error ); } ); } @Test public void onMessageReceived() throws Exception { final TestConnector connector = TestConnector.create(); final Connection connection = newConnection( connector ); final String rawJsonData = ValueUtil.randomString(); pauseScheduler(); connector.pauseMessageScheduler(); assertEquals( connection.getUnparsedResponses().size(), 0 ); assertEquals( connector.isSchedulerActive(), false ); connector.onMessageReceived( rawJsonData ); assertEquals( connection.getUnparsedResponses().size(), 1 ); assertEquals( connection.getUnparsedResponses().get( 0 ).getRawJsonData(), rawJsonData ); assertEquals( connector.isSchedulerActive(), true ); } @Test public void onMessageProcessed() throws Exception { final TestConnector connector = TestConnector.create(); safeAction( () -> connector.setState( ConnectorState.CONNECTING ) ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); final DataLoadStatus status = new DataLoadStatus( ValueUtil.randomInt(), ValueUtil.randomInt(), ValueUtil.getRandom().nextInt( 10 ), ValueUtil.getRandom().nextInt( 10 ), ValueUtil.getRandom().nextInt( 10 ), ValueUtil.getRandom().nextInt( 100 ), ValueUtil.getRandom().nextInt( 100 ), ValueUtil.getRandom().nextInt( 10 ) ); safeAction( () -> connector.onMessageProcessed( status ) ); verify( connector.getTransport() ).onMessageProcessed(); handler.assertEventCount( 1 ); handler.assertNextEvent( MessageProcessedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getDataLoadStatus(), status ); } ); } @Test public void onMessageProcessFailure() throws Exception { final TestConnector connector = TestConnector.create(); safeAction( () -> connector.setState( ConnectorState.CONNECTED ) ); final Throwable error = new Throwable(); // Pause scheduler so runtime does not try to update state pauseScheduler(); safeAction( () -> connector.onMessageProcessFailure( error ) ); safeAction( () -> assertEquals( connector.getState(), ConnectorState.DISCONNECTING ) ); } @Test public void onMessageProcessFailure_generatesSpyMessage() throws Exception { final TestConnector connector = TestConnector.create(); safeAction( () -> connector.setState( ConnectorState.CONNECTING ) ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); final Throwable error = new Throwable(); safeAction( () -> connector.onMessageProcessFailure( error ) ); handler.assertEventCount( 1 ); handler.assertNextEvent( MessageProcessFailureEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getError(), error ); } ); } @Test public void disconnectIfPossible() throws Exception { final TestConnector connector = TestConnector.create(); safeAction( () -> connector.setState( ConnectorState.CONNECTED ) ); final Throwable error = new Throwable(); safeAction( () -> connector.disconnectIfPossible( error ) ); safeAction( () -> assertEquals( connector.getState(), ConnectorState.DISCONNECTING ) ); } @Test public void disconnectIfPossible_noActionAsConnecting() throws Exception { final TestConnector connector = TestConnector.create(); safeAction( () -> connector.setState( ConnectorState.CONNECTING ) ); final Throwable error = new Throwable(); final TestSpyEventHandler handler = registerTestSpyEventHandler(); safeAction( () -> connector.disconnectIfPossible( error ) ); handler.assertEventCount( 0 ); safeAction( () -> assertEquals( connector.getState(), ConnectorState.CONNECTING ) ); } @Test public void disconnectIfPossible_generatesSpyEvent() throws Exception { final TestConnector connector = TestConnector.create(); safeAction( () -> connector.setState( ConnectorState.CONNECTED ) ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); final Throwable error = new Throwable(); safeAction( () -> connector.disconnectIfPossible( error ) ); handler.assertEventCount( 1 ); handler.assertNextEvent( RestartEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getError(), error ); } ); } @Test public void onMessageReadFailure() throws Exception { final TestConnector connector = TestConnector.create(); safeAction( () -> connector.setState( ConnectorState.CONNECTED ) ); final Throwable error = new Throwable(); // Pause scheduler so runtime does not try to update state pauseScheduler(); safeAction( () -> connector.onMessageReadFailure( error ) ); safeAction( () -> assertEquals( connector.getState(), ConnectorState.DISCONNECTING ) ); } @Test public void onMessageReadFailure_generatesSpyMessage() throws Exception { final TestConnector connector = TestConnector.create(); safeAction( () -> connector.setState( ConnectorState.CONNECTING ) ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); final Throwable error = new Throwable(); safeAction( () -> connector.onMessageReadFailure( error ) ); handler.assertEventCount( 1 ); handler.assertNextEvent( MessageReadFailureEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getError(), error ); } ); } @Test public void onSubscribeStarted() throws Exception { final TestConnector connector = TestConnector.create(); final ChannelAddress address = new ChannelAddress( 1, 0 ); final AreaOfInterest areaOfInterest = safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) ); safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) ); safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) ); safeAction( () -> assertEquals( areaOfInterest.getError(), null ) ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); safeAction( () -> connector.onSubscribeStarted( address ) ); safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.LOADING ) ); safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) ); safeAction( () -> assertEquals( areaOfInterest.getError(), null ) ); handler.assertEventCount( 2 ); handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class, e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) ); handler.assertNextEvent( SubscribeStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address ); } ); } @Test public void onSubscribeCompleted() throws Exception { final TestConnector connector = TestConnector.create(); final ChannelAddress address = new ChannelAddress( 1, 0 ); final AreaOfInterest areaOfInterest = safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) ); safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) ); safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) ); safeAction( () -> assertEquals( areaOfInterest.getError(), null ) ); final Subscription subscription = createSubscription( address, null, true ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); safeAction( () -> connector.onSubscribeCompleted( address ) ); safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.LOADED ) ); safeAction( () -> assertEquals( areaOfInterest.getSubscription(), subscription ) ); safeAction( () -> assertEquals( areaOfInterest.getError(), null ) ); handler.assertEventCount( 2 ); handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class, e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) ); handler.assertNextEvent( SubscribeCompletedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address ); } ); } @Test public void onSubscribeFailed() throws Exception { final TestConnector connector = TestConnector.create(); final ChannelAddress address = new ChannelAddress( 1, 0 ); final AreaOfInterest areaOfInterest = safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) ); safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) ); safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) ); safeAction( () -> assertEquals( areaOfInterest.getError(), null ) ); final Throwable error = new Throwable(); final TestSpyEventHandler handler = registerTestSpyEventHandler(); safeAction( () -> connector.onSubscribeFailed( address, error ) ); safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.LOAD_FAILED ) ); safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) ); safeAction( () -> assertEquals( areaOfInterest.getError(), error ) ); handler.assertEventCount( 2 ); handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class, e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) ); handler.assertNextEvent( SubscribeFailedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address ); assertEquals( e.getError(), error ); } ); } @Test public void onUnsubscribeStarted() throws Exception { final TestConnector connector = TestConnector.create(); final ChannelAddress address = new ChannelAddress( 1, 0 ); final AreaOfInterest areaOfInterest = safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) ); safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) ); safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) ); safeAction( () -> assertEquals( areaOfInterest.getError(), null ) ); final Subscription subscription = createSubscription( address, null, true ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); safeAction( () -> connector.onUnsubscribeStarted( address ) ); safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.UNLOADING ) ); safeAction( () -> assertEquals( areaOfInterest.getSubscription(), subscription ) ); safeAction( () -> assertEquals( areaOfInterest.getError(), null ) ); handler.assertEventCount( 2 ); handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class, e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) ); handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address ); } ); } @Test public void onUnsubscribeCompleted() throws Exception { final TestConnector connector = TestConnector.create(); final ChannelAddress address = new ChannelAddress( 1, 0 ); final AreaOfInterest areaOfInterest = safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) ); safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) ); safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) ); safeAction( () -> assertEquals( areaOfInterest.getError(), null ) ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); safeAction( () -> connector.onUnsubscribeCompleted( address ) ); safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.UNLOADED ) ); safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) ); safeAction( () -> assertEquals( areaOfInterest.getError(), null ) ); handler.assertEventCount( 2 ); handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class, e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) ); handler.assertNextEvent( UnsubscribeCompletedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address ); } ); } @Test public void onUnsubscribeFailed() throws Exception { final TestConnector connector = TestConnector.create(); final ChannelAddress address = new ChannelAddress( 1, 0 ); final AreaOfInterest areaOfInterest = safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) ); safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) ); safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) ); safeAction( () -> assertEquals( areaOfInterest.getError(), null ) ); final Throwable error = new Throwable(); final TestSpyEventHandler handler = registerTestSpyEventHandler(); safeAction( () -> connector.onUnsubscribeFailed( address, error ) ); safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.UNLOADED ) ); safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) ); safeAction( () -> assertEquals( areaOfInterest.getError(), null ) ); handler.assertEventCount( 2 ); handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class, e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) ); handler.assertNextEvent( UnsubscribeFailedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address ); assertEquals( e.getError(), error ); } ); } @Test public void onSubscriptionUpdateStarted() throws Exception { final TestConnector connector = TestConnector.create(); final ChannelAddress address = new ChannelAddress( 1, 0 ); final AreaOfInterest areaOfInterest = safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) ); safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) ); safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) ); safeAction( () -> assertEquals( areaOfInterest.getError(), null ) ); final Subscription subscription = createSubscription( address, null, true ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); safeAction( () -> connector.onSubscriptionUpdateStarted( address ) ); safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.UPDATING ) ); safeAction( () -> assertEquals( areaOfInterest.getSubscription(), subscription ) ); safeAction( () -> assertEquals( areaOfInterest.getError(), null ) ); handler.assertEventCount( 2 ); handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class, e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) ); handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address ); } ); } @Test public void onSubscriptionUpdateCompleted() throws Exception { final TestConnector connector = TestConnector.create(); final ChannelAddress address = new ChannelAddress( 1, 0 ); final AreaOfInterest areaOfInterest = safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) ); safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) ); safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) ); safeAction( () -> assertEquals( areaOfInterest.getError(), null ) ); final Subscription subscription = createSubscription( address, null, true ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); safeAction( () -> connector.onSubscriptionUpdateCompleted( address ) ); safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.UPDATED ) ); safeAction( () -> assertEquals( areaOfInterest.getSubscription(), subscription ) ); safeAction( () -> assertEquals( areaOfInterest.getError(), null ) ); handler.assertEventCount( 2 ); handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class, e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) ); handler.assertNextEvent( SubscriptionUpdateCompletedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address ); } ); } @Test public void onSubscriptionUpdateFailed() throws Exception { final TestConnector connector = TestConnector.create(); final ChannelAddress address = new ChannelAddress( 1, 0 ); final AreaOfInterest areaOfInterest = safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, null ) ); safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.NOT_ASKED ) ); safeAction( () -> assertEquals( areaOfInterest.getSubscription(), null ) ); safeAction( () -> assertEquals( areaOfInterest.getError(), null ) ); final Throwable error = new Throwable(); final Subscription subscription = createSubscription( address, null, true ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); safeAction( () -> connector.onSubscriptionUpdateFailed( address, error ) ); safeAction( () -> assertEquals( areaOfInterest.getStatus(), AreaOfInterest.Status.UPDATE_FAILED ) ); safeAction( () -> assertEquals( areaOfInterest.getSubscription(), subscription ) ); safeAction( () -> assertEquals( areaOfInterest.getError(), error ) ); handler.assertEventCount( 2 ); handler.assertNextEvent( AreaOfInterestStatusUpdatedEvent.class, e -> assertEquals( e.getAreaOfInterest(), areaOfInterest ) ); handler.assertNextEvent( SubscriptionUpdateFailedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address ); assertEquals( e.getError(), error ); } ); } @Test public void areaOfInterestRequestPendingQueries() { final TestConnector connector = TestConnector.create(); final ChannelAddress address = new ChannelAddress( 1, 0 ); final String filter = ValueUtil.randomString(); assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.ADD, address, filter ), false ); assertEquals( connector.lastIndexOfPendingAreaOfInterestRequest( AreaOfInterestRequest.Type.ADD, address, filter ), -1 ); final Connection connection = newConnection( connector ); assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.ADD, address, filter ), false ); assertEquals( connector.lastIndexOfPendingAreaOfInterestRequest( AreaOfInterestRequest.Type.ADD, address, filter ), -1 ); connection.requestSubscribe( address, filter ); assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.ADD, address, filter ), true ); assertEquals( connector.lastIndexOfPendingAreaOfInterestRequest( AreaOfInterestRequest.Type.ADD, address, filter ), 1 ); } @Test public void connection() { final TestConnector connector = TestConnector.create(); assertEquals( connector.getConnection(), null ); final Connection connection = newConnection( connector ); final Subscription subscription1 = createSubscription( new ChannelAddress( 1, 0 ), null, true ); assertEquals( connector.getConnection(), connection ); assertEquals( connector.ensureConnection(), connection ); assertEquals( Disposable.isDisposed( subscription1 ), false ); connector.onDisconnection(); assertEquals( connector.getConnection(), null ); assertEquals( Disposable.isDisposed( subscription1 ), true ); } @Test public void ensureConnection_WhenNoConnection() { final TestConnector connector = TestConnector.create(); final IllegalStateException exception = expectThrows( IllegalStateException.class, connector::ensureConnection ); assertEquals( exception.getMessage(), "Replicant-0031: Connector.ensureConnection() when no connection is present." ); } @Test public void purgeSubscriptions() { final TestConnector connector1 = TestConnector.create( newSchema( 1 ) ); TestConnector.create( newSchema( 2 ) ); final Subscription subscription1 = createSubscription( new ChannelAddress( 1, 0 ), null, true ); final Subscription subscription2 = createSubscription( new ChannelAddress( 1, 1, 2 ), null, true ); // The next two are from a different Connector final Subscription subscription3 = createSubscription( new ChannelAddress( 2, 0, 1 ), null, true ); final Subscription subscription4 = createSubscription( new ChannelAddress( 2, 0, 2 ), null, true ); assertEquals( Disposable.isDisposed( subscription1 ), false ); assertEquals( Disposable.isDisposed( subscription2 ), false ); assertEquals( Disposable.isDisposed( subscription3 ), false ); assertEquals( Disposable.isDisposed( subscription4 ), false ); connector1.purgeSubscriptions(); assertEquals( Disposable.isDisposed( subscription1 ), true ); assertEquals( Disposable.isDisposed( subscription2 ), true ); assertEquals( Disposable.isDisposed( subscription3 ), false ); assertEquals( Disposable.isDisposed( subscription4 ), false ); } @Test public void progressMessages() { final TestConnector connector = TestConnector.create(); final Connection connection = newConnection( connector ); final MessageResponse response = new MessageResponse( ValueUtil.randomString() ); connection.setCurrentMessageResponse( response ); response.recordChangeSet( ChangeSet.create( ValueUtil.randomInt(), null, null ), null ); assertNull( connector.getSchedulerLock() ); connector.resumeMessageScheduler(); //response needs worldValidated final boolean result1 = connector.progressMessages(); assertEquals( result1, true ); final Disposable schedulerLock1 = connector.getSchedulerLock(); assertNotNull( schedulerLock1 ); final boolean result2 = connector.progressMessages(); assertEquals( result2, true ); assertNotNull( connector.getSchedulerLock() ); // Current message should be nulled and completed processing now assertNull( connection.getCurrentMessageResponse() ); final boolean result3 = connector.progressMessages(); assertEquals( result3, false ); assertNull( connector.getSchedulerLock() ); assertTrue( Disposable.isDisposed( schedulerLock1 ) ); } @Test public void progressMessages_withError() { final TestConnector connector = TestConnector.create(); final Connection connection = newConnection( connector ); connection.injectCurrentAreaOfInterestRequest( new AreaOfInterestRequest( new ChannelAddress( 0, 0 ), AreaOfInterestRequest.Type.REMOVE, null ) ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); connector.resumeMessageScheduler(); final boolean result2 = connector.progressMessages(); assertEquals( result2, false ); assertNull( connector.getSchedulerLock() ); handler.assertEventCountAtLeast( 1 ); handler.assertNextEvent( MessageProcessFailureEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getError().getMessage(), "Replicant-0046: Request to unsubscribe from channel at address 0.0 but not subscribed to channel." ); } ); } @Test public void requestSubscribe() { final TestConnector connector = TestConnector.create(); newConnection( connector ); connector.pauseMessageScheduler(); final ChannelAddress address = new ChannelAddress( 1, 0 ); assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.ADD, address, null ), false ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); connector.requestSubscribe( address, null ); assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.ADD, address, null ), true ); handler.assertEventCount( 1 ); handler.assertNextEvent( SubscribeRequestQueuedEvent.class, e -> assertEquals( e.getAddress(), address ) ); } @Test public void requestSubscriptionUpdate() { final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), true, ChannelSchema.FilterType.DYNAMIC, ( f, e ) -> true, false, true ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[ 0 ] ); final TestConnector connector = TestConnector.create( schema ); newConnection( connector ); connector.pauseMessageScheduler(); final ChannelAddress address = new ChannelAddress( 1, 0 ); assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.UPDATE, address, null ), false ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); connector.requestSubscriptionUpdate( address, null ); assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.UPDATE, address, null ), true ); handler.assertEventCount( 1 ); handler.assertNextEvent( SubscriptionUpdateRequestQueuedEvent.class, e -> assertEquals( e.getAddress(), address ) ); } @Test public void requestSubscriptionUpdate_ChannelNot_DYNAMIC_Filter() { final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), true, ChannelSchema.FilterType.STATIC, null, false, true ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[ 0 ] ); final TestConnector connector = TestConnector.create( schema ); newConnection( connector ); connector.pauseMessageScheduler(); final ChannelAddress address = new ChannelAddress( 1, 0 ); assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.UPDATE, address, null ), false ); final IllegalStateException exception = expectThrows( IllegalStateException.class, () -> connector.requestSubscriptionUpdate( address, null ) ); assertEquals( exception.getMessage(), "Replicant-0082: Connector.requestSubscriptionUpdate invoked for channel 1.0 but channel does not have a dynamic filter." ); } @Test public void requestUnsubscribe() throws Exception { final TestConnector connector = TestConnector.create(); pauseScheduler(); connector.pauseMessageScheduler(); newConnection( connector ); final ChannelAddress address = new ChannelAddress( 1, 0 ); createSubscription( address, null, true ); assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.REMOVE, address, null ), false ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); connector.requestUnsubscribe( address ); Thread.sleep( 100 ); assertEquals( connector.isAreaOfInterestRequestPending( AreaOfInterestRequest.Type.REMOVE, address, null ), true ); handler.assertEventCount( 1 ); handler.assertNextEvent( UnsubscribeRequestQueuedEvent.class, e -> assertEquals( e.getAddress(), address ) ); } @Test public void updateSubscriptionForFilteredEntities() { final SubscriptionUpdateEntityFilter filter = ( f, entity ) -> entity.getId() > 0; final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), true, ChannelSchema.FilterType.DYNAMIC, filter, true, true ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[ 0 ] ); final TestConnector connector = TestConnector.create( schema ); newConnection( connector ); final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 ); final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 ); final Subscription subscription1 = createSubscription( address1, ValueUtil.randomString(), true ); final Subscription subscription2 = createSubscription( address2, ValueUtil.randomString(), true ); // Use Integer and String as arbitrary types for our entities... // Anything with id below 0 will be removed during update ... final Entity entity1 = findOrCreateEntity( Integer.class, -1 ); final Entity entity2 = findOrCreateEntity( Integer.class, -2 ); final Entity entity3 = findOrCreateEntity( Integer.class, -3 ); final Entity entity4 = findOrCreateEntity( Integer.class, -4 ); final Entity entity5 = findOrCreateEntity( String.class, 5 ); final Entity entity6 = findOrCreateEntity( String.class, 6 ); safeAction( () -> { entity1.linkToSubscription( subscription1 ); entity2.linkToSubscription( subscription1 ); entity3.linkToSubscription( subscription1 ); entity4.linkToSubscription( subscription1 ); entity5.linkToSubscription( subscription1 ); entity6.linkToSubscription( subscription1 ); entity3.linkToSubscription( subscription2 ); entity4.linkToSubscription( subscription2 ); assertEquals( subscription1.getEntities().size(), 2 ); assertEquals( subscription1.findAllEntitiesByType( Integer.class ).size(), 4 ); assertEquals( subscription1.findAllEntitiesByType( String.class ).size(), 2 ); assertEquals( subscription2.getEntities().size(), 1 ); assertEquals( subscription2.findAllEntitiesByType( Integer.class ).size(), 2 ); } ); safeAction( () -> connector.updateSubscriptionForFilteredEntities( subscription1 ) ); safeAction( () -> { assertEquals( Disposable.isDisposed( entity1 ), true ); assertEquals( Disposable.isDisposed( entity2 ), true ); assertEquals( Disposable.isDisposed( entity3 ), false ); assertEquals( Disposable.isDisposed( entity4 ), false ); assertEquals( Disposable.isDisposed( entity5 ), false ); assertEquals( Disposable.isDisposed( entity6 ), false ); assertEquals( subscription1.getEntities().size(), 1 ); assertEquals( subscription1.findAllEntitiesByType( Integer.class ).size(), 0 ); assertEquals( subscription1.findAllEntitiesByType( String.class ).size(), 2 ); assertEquals( subscription2.getEntities().size(), 1 ); assertEquals( subscription2.findAllEntitiesByType( Integer.class ).size(), 2 ); } ); } @Test public void updateSubscriptionForFilteredEntities_badFilterType() { final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), true, ChannelSchema.FilterType.STATIC, null, true, true ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[ 0 ] ); final TestConnector connector = TestConnector.create( schema ); newConnection( connector ); final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 ); final Subscription subscription1 = createSubscription( address1, ValueUtil.randomString(), true ); final IllegalStateException exception = expectThrows( IllegalStateException.class, () -> safeAction( () -> connector.updateSubscriptionForFilteredEntities( subscription1 ) ) ); assertEquals( exception.getMessage(), "Replicant-0079: Connector.updateSubscriptionForFilteredEntities invoked for address 1.0.1 but the channel does not have a DYNAMIC filter." ); } @Test public void toAddress() { final TestConnector connector = TestConnector.create(); assertEquals( connector.toAddress( ChannelChange.create( 0, ChannelChange.Action.ADD, null ) ), new ChannelAddress( 1, 0 ) ); assertEquals( connector.toAddress( ChannelChange.create( 1, 2, ChannelChange.Action.ADD, null ) ), new ChannelAddress( 1, 1, 2 ) ); } @Test public void processEntityChanges() { final int schemaId = 1; final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), true, ChannelSchema.FilterType.NONE, null, false, true ); final EntitySchema entitySchema = new EntitySchema( 0, ValueUtil.randomString(), MyEntity.class ); final SystemSchema schema = new SystemSchema( schemaId, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[]{ entitySchema } ); final TestConnector connector = TestConnector.create( schema ); connector.setLinksToProcessPerTick( 1 ); final Connection connection = newConnection( connector ); final MessageResponse response = new MessageResponse( ValueUtil.randomString() ); connection.setCurrentMessageResponse( response ); final Linkable userObject1 = mock( Linkable.class ); final Linkable userObject2 = mock( Linkable.class ); // Pause scheduler to avoid converge of subscriptions pauseScheduler(); final ChannelAddress address = new ChannelAddress( connector.getSchema().getId(), 1 ); createSubscription( address, null, true ); // This entity is to be updated final Entity entity2 = findOrCreateEntity( MyEntity.class, 2 ); safeAction( () -> entity2.setUserObject( userObject2 ) ); // This entity is to be removed final Entity entity3 = findOrCreateEntity( MyEntity.class, 3 ); final EntityChangeData data1 = mock( EntityChangeData.class ); final EntityChangeData data2 = mock( EntityChangeData.class ); final EntityChange[] entityChanges = { // Update changes EntityChange.create( 1, 0, new EntityChannel[]{ EntityChannel.create( 1 ) }, data1 ), EntityChange.create( 2, 0, new EntityChannel[]{ EntityChannel.create( 1 ) }, data2 ), // Remove change EntityChange.create( 3, 0, new EntityChannel[]{ EntityChannel.create( 1 ) } ) }; final ChangeSet changeSet = ChangeSet.create( ValueUtil.randomInt(), null, entityChanges ); response.recordChangeSet( changeSet, null ); when( connector.getChangeMapper().createEntity( entitySchema, 1, data1 ) ).thenReturn( userObject1 ); assertEquals( response.getUpdatedEntities().size(), 0 ); assertEquals( response.getEntityUpdateCount(), 0 ); assertEquals( response.getEntityRemoveCount(), 0 ); connector.setChangesToProcessPerTick( 1 ); connector.processEntityChanges(); verify( connector.getChangeMapper(), times( 1 ) ).createEntity( entitySchema, 1, data1 ); verify( connector.getChangeMapper(), never() ).updateEntity( entitySchema, userObject1, data1 ); verify( connector.getChangeMapper(), never() ).createEntity( entitySchema, 2, data2 ); verify( connector.getChangeMapper(), never() ).updateEntity( entitySchema, userObject2, data2 ); assertEquals( response.getUpdatedEntities().size(), 1 ); assertEquals( response.getUpdatedEntities().contains( userObject1 ), true ); assertEquals( response.getEntityUpdateCount(), 1 ); assertEquals( response.getEntityRemoveCount(), 0 ); connector.setChangesToProcessPerTick( 2 ); connector.processEntityChanges(); verify( connector.getChangeMapper(), times( 1 ) ).createEntity( entitySchema, 1, data1 ); verify( connector.getChangeMapper(), never() ).updateEntity( entitySchema, userObject1, data1 ); verify( connector.getChangeMapper(), never() ).createEntity( entitySchema, 2, data2 ); verify( connector.getChangeMapper(), times( 1 ) ).updateEntity( entitySchema, userObject2, data2 ); assertEquals( response.getUpdatedEntities().size(), 2 ); assertEquals( response.getUpdatedEntities().contains( userObject1 ), true ); assertEquals( response.getUpdatedEntities().contains( userObject2 ), true ); assertEquals( response.getEntityUpdateCount(), 2 ); assertEquals( response.getEntityRemoveCount(), 1 ); assertEquals( Disposable.isDisposed( entity2 ), false ); assertEquals( Disposable.isDisposed( entity3 ), true ); } @Test public void processEntityChanges_referenceNonExistentSubscription() { final int schemaId = 1; final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), true, ChannelSchema.FilterType.NONE, null, false, true ); final EntitySchema entitySchema = new EntitySchema( 0, ValueUtil.randomString(), MyEntity.class ); final SystemSchema schema = new SystemSchema( schemaId, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[]{ entitySchema } ); final TestConnector connector = TestConnector.create( schema ); connector.setLinksToProcessPerTick( 1 ); final Connection connection = newConnection( connector ); final MessageResponse response = new MessageResponse( ValueUtil.randomString() ); connection.setCurrentMessageResponse( response ); final Linkable userObject1 = mock( Linkable.class ); // Pause scheduler to avoid converge of subscriptions pauseScheduler(); final EntityChangeData data1 = mock( EntityChangeData.class ); final EntityChange[] entityChanges = { EntityChange.create( 1, 0, new EntityChannel[]{ EntityChannel.create( 1 ) }, data1 ) }; final ChangeSet changeSet = ChangeSet.create( 42, null, entityChanges ); response.recordChangeSet( changeSet, null ); when( connector.getChangeMapper().createEntity( entitySchema, 1, data1 ) ).thenReturn( userObject1 ); final IllegalStateException exception = expectThrows( IllegalStateException.class, connector::processEntityChanges ); assertEquals( exception.getMessage(), "Replicant-0069: ChangeSet 42 contained an EntityChange message referencing channel 1.1 but no such subscription exists locally." ); } @Test public void processEntityChanges_deleteNonExistingEntity() { final int schemaId = 1; final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), true, ChannelSchema.FilterType.NONE, null, false, true ); final EntitySchema entitySchema = new EntitySchema( 0, ValueUtil.randomString(), MyEntity.class ); final SystemSchema schema = new SystemSchema( schemaId, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[]{ entitySchema } ); final TestConnector connector = TestConnector.create( schema ); connector.setLinksToProcessPerTick( 1 ); final Connection connection = newConnection( connector ); final MessageResponse response = new MessageResponse( ValueUtil.randomString() ); connection.setCurrentMessageResponse( response ); // Pause scheduler to avoid converge of subscriptions pauseScheduler(); final EntityChange[] entityChanges = { // Remove change EntityChange.create( 3, 0, new EntityChannel[]{ EntityChannel.create( 1 ) } ) }; final ChangeSet changeSet = ChangeSet.create( 23, null, entityChanges ); response.recordChangeSet( changeSet, null ); connector.setChangesToProcessPerTick( 1 ); final IllegalStateException exception = expectThrows( IllegalStateException.class, connector::processEntityChanges ); assertEquals( exception.getMessage(), "Replicant-0068: ChangeSet 23 contained an EntityChange message to delete entity of type 0 and id 3 but no such entity exists locally." ); } @Test public void processEntityLinks() { final TestConnector connector = TestConnector.create(); connector.setLinksToProcessPerTick( 1 ); final Connection connection = newConnection( connector ); final MessageResponse response = new MessageResponse( ValueUtil.randomString() ); connection.setCurrentMessageResponse( response ); final Linkable entity1 = mock( Linkable.class ); final Linkable entity2 = mock( Linkable.class ); final Linkable entity3 = mock( Linkable.class ); final Linkable entity4 = mock( Linkable.class ); response.changeProcessed( entity1 ); response.changeProcessed( entity2 ); response.changeProcessed( entity3 ); response.changeProcessed( entity4 ); verify( entity1, never() ).link(); verify( entity2, never() ).link(); verify( entity3, never() ).link(); verify( entity4, never() ).link(); assertEquals( response.getEntityLinkCount(), 0 ); connector.setLinksToProcessPerTick( 1 ); connector.processEntityLinks(); assertEquals( response.getEntityLinkCount(), 1 ); verify( entity1, times( 1 ) ).link(); verify( entity2, never() ).link(); verify( entity3, never() ).link(); verify( entity4, never() ).link(); connector.setLinksToProcessPerTick( 2 ); connector.processEntityLinks(); assertEquals( response.getEntityLinkCount(), 3 ); verify( entity1, times( 1 ) ).link(); verify( entity2, times( 1 ) ).link(); verify( entity3, times( 1 ) ).link(); verify( entity4, never() ).link(); } @Test public void completeAreaOfInterestRequest() { final TestConnector connector = TestConnector.create(); final Connection connection = newConnection( connector ); connection.injectCurrentAreaOfInterestRequest( new AreaOfInterestRequest( new ChannelAddress( 1, 0 ), AreaOfInterestRequest.Type.ADD, null ) ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); connector.completeAreaOfInterestRequest(); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true ); } @Test public void processChannelChanges_add() { final TestConnector connector = TestConnector.create(); final Connection connection = newConnection( connector ); final MessageResponse response = new MessageResponse( ValueUtil.randomString() ); connection.setCurrentMessageResponse( response ); final int channelId = 0; final int subChannelId = ValueUtil.randomInt(); final String filter = ValueUtil.randomString(); final ChannelChange[] channelChanges = new ChannelChange[]{ ChannelChange.create( channelId, subChannelId, ChannelChange.Action.ADD, filter ) }; response.recordChangeSet( ChangeSet.create( ValueUtil.randomInt(), channelChanges, null ), null ); assertEquals( response.needsChannelChangesProcessed(), true ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); connector.processChannelChanges(); assertEquals( response.needsChannelChangesProcessed(), false ); final ChannelAddress address = new ChannelAddress( 1, channelId, subChannelId ); final Subscription subscription = safeAction( () -> Replicant.context().findSubscription( address ) ); assertNotNull( subscription ); assertEquals( subscription.getAddress(), address ); safeAction( () -> assertEquals( subscription.getFilter(), filter ) ); safeAction( () -> assertEquals( subscription.isExplicitSubscription(), false ) ); handler.assertEventCount( 1 ); handler.assertNextEvent( SubscriptionCreatedEvent.class, e -> { assertEquals( e.getSubscription().getAddress(), address ); safeAction( () -> assertEquals( e.getSubscription().getFilter(), filter ) ); } ); } @Test public void processChannelChanges_addConvertingImplicitToExplicit() { final TestConnector connector = TestConnector.create(); final Connection connection = newConnection( connector ); connector.pauseMessageScheduler(); final MessageResponse response = new MessageResponse( ValueUtil.randomString() ); connection.setCurrentMessageResponse( response ); final ChannelAddress address = new ChannelAddress( 1, 0, ValueUtil.randomInt() ); final int channelId = address.getChannelId(); final int subChannelId = Objects.requireNonNull( address.getId() ); final String filter = ValueUtil.randomString(); safeAction( () -> Replicant.context().createOrUpdateAreaOfInterest( address, filter ) ); final ChannelChange[] channelChanges = new ChannelChange[]{ ChannelChange.create( channelId, subChannelId, ChannelChange.Action.ADD, filter ) }; response.recordChangeSet( ChangeSet.create( ValueUtil.randomInt(), channelChanges, null ), null ); final AreaOfInterestRequest request = new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.ADD, filter ); connection.injectCurrentAreaOfInterestRequest( request ); request.markAsInProgress(); assertEquals( response.needsChannelChangesProcessed(), true ); assertEquals( response.getChannelAddCount(), 0 ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); connector.processChannelChanges(); assertEquals( response.needsChannelChangesProcessed(), false ); assertEquals( response.getChannelAddCount(), 1 ); final Subscription subscription = safeAction( () -> Replicant.context().findSubscription( address ) ); assertNotNull( subscription ); assertEquals( subscription.getAddress(), address ); safeAction( () -> assertEquals( subscription.getFilter(), filter ) ); safeAction( () -> assertEquals( subscription.isExplicitSubscription(), true ) ); handler.assertEventCount( 1 ); handler.assertNextEvent( SubscriptionCreatedEvent.class, e -> { assertEquals( e.getSubscription().getAddress(), address ); safeAction( () -> assertEquals( e.getSubscription().getFilter(), filter ) ); } ); } @Test public void processChannelChanges_remove() { final TestConnector connector = TestConnector.create(); connector.pauseMessageScheduler(); final Connection connection = newConnection( connector ); final MessageResponse response = new MessageResponse( ValueUtil.randomString() ); connection.setCurrentMessageResponse( response ); final ChannelAddress address = new ChannelAddress( 1, 0, ValueUtil.randomInt() ); final int channelId = address.getChannelId(); final int subChannelId = Objects.requireNonNull( address.getId() ); final String filter = ValueUtil.randomString(); final ChannelChange[] channelChanges = new ChannelChange[]{ ChannelChange.create( channelId, subChannelId, ChannelChange.Action.REMOVE, null ) }; response.recordChangeSet( ChangeSet.create( ValueUtil.randomInt(), channelChanges, null ), null ); final Subscription initialSubscription = createSubscription( address, filter, true ); assertEquals( response.needsChannelChangesProcessed(), true ); assertEquals( response.getChannelRemoveCount(), 0 ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); connector.processChannelChanges(); assertEquals( response.needsChannelChangesProcessed(), false ); assertEquals( response.getChannelRemoveCount(), 1 ); final Subscription subscription = safeAction( () -> Replicant.context().findSubscription( address ) ); assertNull( subscription ); assertEquals( Disposable.isDisposed( initialSubscription ), true ); handler.assertEventCount( 1 ); handler.assertNextEvent( SubscriptionDisposedEvent.class, e -> assertEquals( e.getSubscription().getAddress(), address ) ); } @Test public void processChannelChanges_remove_WithMissingSubscription() { final TestConnector connector = TestConnector.create(); final Connection connection = newConnection( connector ); final MessageResponse response = new MessageResponse( ValueUtil.randomString() ); connection.setCurrentMessageResponse( response ); final ChannelAddress address = new ChannelAddress( 1, 0, 72 ); final int channelId = address.getChannelId(); final int subChannelId = Objects.requireNonNull( address.getId() ); final ChannelChange[] channelChanges = new ChannelChange[]{ ChannelChange.create( channelId, subChannelId, ChannelChange.Action.REMOVE, null ) }; response.recordChangeSet( ChangeSet.create( ValueUtil.randomInt(), channelChanges, null ), null ); assertEquals( response.needsChannelChangesProcessed(), true ); assertEquals( response.getChannelRemoveCount(), 0 ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); final IllegalStateException exception = expectThrows( IllegalStateException.class, connector::processChannelChanges ); assertEquals( response.needsChannelChangesProcessed(), true ); assertEquals( response.getChannelRemoveCount(), 0 ); assertEquals( exception.getMessage(), "Replicant-0028: Received ChannelChange of type REMOVE for address 1.0.72 but no such subscription exists." ); handler.assertEventCount( 0 ); } @Test public void processChannelChanges_update() { final SubscriptionUpdateEntityFilter filter = mock( SubscriptionUpdateEntityFilter.class ); final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), true, ChannelSchema.FilterType.DYNAMIC, filter, true, true ); final EntitySchema entitySchema = new EntitySchema( 0, ValueUtil.randomString(), String.class ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[]{ entitySchema } ); final TestConnector connector = TestConnector.create( schema ); connector.pauseMessageScheduler(); final Connection connection = newConnection( connector ); final MessageResponse response = new MessageResponse( ValueUtil.randomString() ); connection.setCurrentMessageResponse( response ); final ChannelAddress address = new ChannelAddress( 1, 0, ValueUtil.randomInt() ); final int channelId = address.getChannelId(); final int subChannelId = Objects.requireNonNull( address.getId() ); final String oldFilter = ValueUtil.randomString(); final String newFilter = ValueUtil.randomString(); final ChannelChange[] channelChanges = new ChannelChange[]{ ChannelChange.create( channelId, subChannelId, ChannelChange.Action.UPDATE, newFilter ) }; response.recordChangeSet( ChangeSet.create( ValueUtil.randomInt(), channelChanges, null ), null ); final Subscription initialSubscription = createSubscription( address, oldFilter, true ); assertEquals( response.needsChannelChangesProcessed(), true ); assertEquals( response.getChannelUpdateCount(), 0 ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); connector.processChannelChanges(); assertEquals( response.needsChannelChangesProcessed(), false ); assertEquals( response.getChannelUpdateCount(), 1 ); final Subscription subscription = safeAction( () -> Replicant.context().findSubscription( address ) ); assertNotNull( subscription ); assertEquals( Disposable.isDisposed( initialSubscription ), false ); handler.assertEventCount( 0 ); } @Test public void processChannelChanges_update_forNonDYNAMICChannel() { final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), true, ChannelSchema.FilterType.NONE, null, true, true ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[ 0 ] ); final TestConnector connector = TestConnector.create( schema ); final Connection connection = newConnection( connector ); final MessageResponse response = new MessageResponse( ValueUtil.randomString() ); connection.setCurrentMessageResponse( response ); final ChannelAddress address = new ChannelAddress( 1, 0, 2223 ); final int channelId = address.getChannelId(); final int subChannelId = Objects.requireNonNull( address.getId() ); final String oldFilter = ValueUtil.randomString(); final String newFilter = ValueUtil.randomString(); final ChannelChange[] channelChanges = new ChannelChange[]{ ChannelChange.create( channelId, subChannelId, ChannelChange.Action.UPDATE, newFilter ) }; response.recordChangeSet( ChangeSet.create( ValueUtil.randomInt(), channelChanges, null ), null ); createSubscription( address, oldFilter, true ); final IllegalStateException exception = expectThrows( IllegalStateException.class, connector::processChannelChanges ); assertEquals( exception.getMessage(), "Replicant-0078: Received ChannelChange of type UPDATE for address 1.0.2223 but the channel does not have a DYNAMIC filter." ); } @Test public void processChannelChanges_update_implicitSubscription() { final TestConnector connector = TestConnector.create(); final Connection connection = newConnection( connector ); final MessageResponse response = new MessageResponse( ValueUtil.randomString() ); connection.setCurrentMessageResponse( response ); final ChannelAddress address = new ChannelAddress( 1, 0, 33 ); final int channelId = address.getChannelId(); final int subChannelId = Objects.requireNonNull( address.getId() ); final String oldFilter = ValueUtil.randomString(); final String newFilter = ValueUtil.randomString(); final ChannelChange[] channelChanges = new ChannelChange[]{ ChannelChange.create( channelId, subChannelId, ChannelChange.Action.UPDATE, newFilter ) }; response.recordChangeSet( ChangeSet.create( ValueUtil.randomInt(), channelChanges, null ), null ); createSubscription( address, oldFilter, false ); assertEquals( response.needsChannelChangesProcessed(), true ); assertEquals( response.getChannelUpdateCount(), 0 ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); final IllegalStateException exception = expectThrows( IllegalStateException.class, connector::processChannelChanges ); assertEquals( response.needsChannelChangesProcessed(), true ); assertEquals( response.getChannelUpdateCount(), 0 ); assertEquals( exception.getMessage(), "Replicant-0029: Received ChannelChange of type UPDATE for address 1.0.33 but subscription is implicitly subscribed." ); handler.assertEventCount( 0 ); } @Test public void processChannelChanges_update_missingSubscription() { final TestConnector connector = TestConnector.create(); final Connection connection = newConnection( connector ); final MessageResponse response = new MessageResponse( ValueUtil.randomString() ); connection.setCurrentMessageResponse( response ); final ChannelAddress address = new ChannelAddress( 1, 0, 42 ); final int channelId = address.getChannelId(); final int subChannelId = Objects.requireNonNull( address.getId() ); final String newFilter = ValueUtil.randomString(); final ChannelChange[] channelChanges = new ChannelChange[]{ ChannelChange.create( channelId, subChannelId, ChannelChange.Action.UPDATE, newFilter ) }; response.recordChangeSet( ChangeSet.create( ValueUtil.randomInt(), channelChanges, null ), null ); assertEquals( response.needsChannelChangesProcessed(), true ); assertEquals( response.getChannelUpdateCount(), 0 ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); final IllegalStateException exception = expectThrows( IllegalStateException.class, connector::processChannelChanges ); assertEquals( response.needsChannelChangesProcessed(), true ); assertEquals( response.getChannelUpdateCount(), 0 ); assertEquals( exception.getMessage(), "Replicant-0033: Received ChannelChange of type UPDATE for address 1.0.42 but no such subscription exists." ); handler.assertEventCount( 0 ); } @Test public void removeExplicitSubscriptions() { // Pause converger pauseScheduler(); final TestConnector connector = TestConnector.create(); final ChannelAddress address1 = new ChannelAddress( 1, 1, 1 ); final ChannelAddress address2 = new ChannelAddress( 1, 1, 2 ); final ChannelAddress address3 = new ChannelAddress( 1, 1, 3 ); final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>(); requests.add( new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null ) ); requests.add( new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.REMOVE, null ) ); requests.add( new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.REMOVE, null ) ); final Subscription subscription1 = createSubscription( address1, null, true ); // Address2 is already implicit ... createSubscription( address2, null, false ); // Address3 has no subscription ... maybe not converged yet safeAction( () -> connector.removeExplicitSubscriptions( requests ) ); safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), false ) ); } @Test public void removeExplicitSubscriptions_passedBadAction() { // Pause converger pauseScheduler(); final TestConnector connector = TestConnector.create(); final ChannelAddress address1 = new ChannelAddress( 1, 1, 1 ); final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>(); requests.add( new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, null ) ); createSubscription( address1, null, true ); final IllegalStateException exception = expectThrows( IllegalStateException.class, () -> safeAction( () -> connector.removeExplicitSubscriptions( requests ) ) ); assertEquals( exception.getMessage(), "Replicant-0034: Connector.removeExplicitSubscriptions() invoked with request with type that is not REMOVE. Request: AreaOfInterestRequest[Type=ADD Address=1.1.1]" ); } @Test public void removeUnneededAddRequests_upgradeExisting() { final TestConnector connector = TestConnector.create(); final ChannelAddress address1 = new ChannelAddress( 1, 1, 1 ); final ChannelAddress address2 = new ChannelAddress( 1, 1, 2 ); final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>(); final AreaOfInterestRequest request1 = new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, null ); final AreaOfInterestRequest request2 = new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.ADD, null ); requests.add( request1 ); requests.add( request2 ); requests.forEach( AreaOfInterestRequest::markAsInProgress ); // Address1 is implicitly subscribed final Subscription subscription1 = createSubscription( address1, null, false ); safeAction( () -> connector.removeUnneededAddRequests( requests ) ); assertEquals( requests.size(), 1 ); assertEquals( requests.contains( request2 ), true ); assertEquals( request1.isInProgress(), false ); assertEquals( request2.isInProgress(), true ); safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) ); } @Test public void removeUnneededAddRequests_explicitAlreadyPresent() { final TestConnector connector = TestConnector.create(); final ChannelAddress address1 = new ChannelAddress( 1, 1, 1 ); final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>(); final AreaOfInterestRequest request1 = new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, null ); requests.add( request1 ); requests.forEach( AreaOfInterestRequest::markAsInProgress ); createSubscription( address1, null, true ); final IllegalStateException exception = expectThrows( IllegalStateException.class, () -> safeAction( () -> connector.removeUnneededAddRequests( requests ) ) ); assertEquals( exception.getMessage(), "Replicant-0030: Request to add channel at address 1.1.1 but already explicitly subscribed to channel." ); } @Test public void removeUnneededRemoveRequests_whenInvariantsDisabled() { final TestConnector connector = TestConnector.create(); final ChannelAddress address1 = new ChannelAddress( 1, 1, 1 ); final ChannelAddress address2 = new ChannelAddress( 1, 1, 2 ); final ChannelAddress address3 = new ChannelAddress( 1, 1, 3 ); final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>(); final AreaOfInterestRequest request1 = new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null ); final AreaOfInterestRequest request2 = new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.REMOVE, null ); final AreaOfInterestRequest request3 = new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.REMOVE, null ); requests.add( request1 ); requests.add( request2 ); requests.add( request3 ); requests.forEach( AreaOfInterestRequest::markAsInProgress ); createSubscription( address1, null, true ); // Address2 is already implicit ... createSubscription( address2, null, false ); // Address3 has no subscription ... maybe not converged yet ReplicantTestUtil.noCheckInvariants(); safeAction( () -> connector.removeUnneededRemoveRequests( requests ) ); assertEquals( requests.size(), 1 ); assertEquals( requests.contains( request1 ), true ); assertEquals( request1.isInProgress(), true ); assertEquals( request2.isInProgress(), false ); assertEquals( request3.isInProgress(), false ); } @Test public void removeUnneededRemoveRequests_noSubscription() { final TestConnector connector = TestConnector.create(); final ChannelAddress address1 = new ChannelAddress( 1, 1, 1 ); final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>(); final AreaOfInterestRequest request1 = new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null ); requests.add( request1 ); requests.forEach( AreaOfInterestRequest::markAsInProgress ); final IllegalStateException exception = expectThrows( IllegalStateException.class, () -> safeAction( () -> connector.removeUnneededRemoveRequests( requests ) ) ); assertEquals( exception.getMessage(), "Replicant-0046: Request to unsubscribe from channel at address 1.1.1 but not subscribed to channel." ); } @Test public void removeUnneededRemoveRequests_implicitSubscription() { final TestConnector connector = TestConnector.create(); final ChannelAddress address1 = new ChannelAddress( 1, 1, 1 ); final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>(); final AreaOfInterestRequest request1 = new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null ); requests.add( request1 ); requests.forEach( AreaOfInterestRequest::markAsInProgress ); createSubscription( address1, null, false ); final IllegalStateException exception = expectThrows( IllegalStateException.class, () -> safeAction( () -> connector.removeUnneededRemoveRequests( requests ) ) ); assertEquals( exception.getMessage(), "Replicant-0047: Request to unsubscribe from channel at address 1.1.1 but subscription is not an explicit subscription." ); } @Test public void removeUnneededUpdateRequests_whenInvariantsDisabled() { final TestConnector connector = TestConnector.create(); final ChannelAddress address1 = new ChannelAddress( 1, 1, 1 ); final ChannelAddress address2 = new ChannelAddress( 1, 1, 2 ); final ChannelAddress address3 = new ChannelAddress( 1, 1, 3 ); final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>(); final AreaOfInterestRequest request1 = new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.UPDATE, null ); final AreaOfInterestRequest request2 = new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.UPDATE, null ); final AreaOfInterestRequest request3 = new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.UPDATE, null ); requests.add( request1 ); requests.add( request2 ); requests.add( request3 ); requests.forEach( AreaOfInterestRequest::markAsInProgress ); createSubscription( address1, null, true ); // Address2 is already implicit ... createSubscription( address2, null, false ); // Address3 has no subscription ... maybe not converged yet ReplicantTestUtil.noCheckInvariants(); safeAction( () -> connector.removeUnneededUpdateRequests( requests ) ); assertEquals( requests.size(), 2 ); assertEquals( requests.contains( request1 ), true ); assertEquals( requests.contains( request2 ), true ); assertEquals( request1.isInProgress(), true ); assertEquals( request2.isInProgress(), true ); assertEquals( request3.isInProgress(), false ); } @Test public void removeUnneededUpdateRequests_noSubscription() { final TestConnector connector = TestConnector.create(); final ChannelAddress address1 = new ChannelAddress( 1, 1, 1 ); final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>(); final AreaOfInterestRequest request1 = new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.UPDATE, null ); requests.add( request1 ); requests.forEach( AreaOfInterestRequest::markAsInProgress ); final IllegalStateException exception = expectThrows( IllegalStateException.class, () -> safeAction( () -> connector.removeUnneededUpdateRequests( requests ) ) ); assertEquals( exception.getMessage(), "Replicant-0048: Request to update channel at address 1.1.1 but not subscribed to channel." ); } @Test public void validateWorld_invalidEntity() { final TestConnector connector = TestConnector.create(); newConnection( connector ); final MessageResponse response = new MessageResponse( ValueUtil.randomString() ); connector.ensureConnection().setCurrentMessageResponse( response ); assertEquals( response.hasWorldBeenValidated(), false ); final EntityService entityService = Replicant.context().getEntityService(); final Entity entity1 = safeAction( () -> entityService.findOrCreateEntity( "MyEntity/1", MyEntity.class, 1 ) ); final Exception error = new Exception(); safeAction( () -> entity1.setUserObject( new MyEntity( error ) ) ); final IllegalStateException exception = expectThrows( IllegalStateException.class, connector::validateWorld ); assertEquals( exception.getMessage(), "Replicant-0065: Entity failed to verify during validation process. Entity = MyEntity/1" ); assertEquals( response.hasWorldBeenValidated(), true ); } @Test public void validateWorld_invalidEntity_ignoredIfCOmpileSettingDisablesValidation() { ReplicantTestUtil.noValidateEntitiesOnLoad(); final TestConnector connector = TestConnector.create(); newConnection( connector ); final MessageResponse response = new MessageResponse( ValueUtil.randomString() ); connector.ensureConnection().setCurrentMessageResponse( response ); assertEquals( response.hasWorldBeenValidated(), true ); final EntityService entityService = Replicant.context().getEntityService(); final Entity entity1 = safeAction( () -> entityService.findOrCreateEntity( "MyEntity/1", MyEntity.class, 1 ) ); final Exception error = new Exception(); safeAction( () -> entity1.setUserObject( new MyEntity( error ) ) ); connector.validateWorld(); assertEquals( response.hasWorldBeenValidated(), true ); } @Test public void validateWorld_validEntity() { final TestConnector connector = TestConnector.create(); newConnection( connector ); final MessageResponse response = new MessageResponse( ValueUtil.randomString() ); connector.ensureConnection().setCurrentMessageResponse( response ); assertEquals( response.hasWorldBeenValidated(), false ); final EntityService entityService = Replicant.context().getEntityService(); safeAction( () -> entityService.findOrCreateEntity( "MyEntity/1", MyEntity.class, 1 ) ); connector.validateWorld(); assertEquals( response.hasWorldBeenValidated(), true ); } static class MyEntity implements Verifiable { @Nullable private final Exception _exception; MyEntity( @Nullable final Exception exception ) { _exception = exception; } @Override public void verify() throws Exception { if ( null != _exception ) { throw _exception; } } } @Test public void parseMessageResponse_basicMessage() { final TestConnector connector = TestConnector.create(); final Connection connection = newConnection( connector ); @Language( "json" ) final String rawJsonData = "{\"last_id\": 1}"; final MessageResponse response = new MessageResponse( rawJsonData ); connection.setCurrentMessageResponse( response ); assertEquals( connection.getPendingResponses().size(), 0 ); connector.parseMessageResponse(); assertEquals( response.getRawJsonData(), null ); final ChangeSet changeSet = response.getChangeSet(); assertNotNull( changeSet ); assertEquals( changeSet.getSequence(), 1 ); assertNull( response.getRequest() ); assertEquals( connection.getPendingResponses().size(), 1 ); assertEquals( connection.getCurrentMessageResponse(), null ); } @Test public void parseMessageResponse_requestPresent() { final TestConnector connector = TestConnector.create(); final Connection connection = newConnection( connector ); final Request request = connection.newRequest( "SomeAction" ); final int requestId = request.getRequestId(); @Language( "json" ) final String rawJsonData = "{\"last_id\": 1, \"requestId\": " + requestId + "}"; final MessageResponse response = new MessageResponse( rawJsonData ); connection.setCurrentMessageResponse( response ); assertEquals( connection.getPendingResponses().size(), 0 ); connector.parseMessageResponse(); assertEquals( response.getRawJsonData(), null ); final ChangeSet changeSet = response.getChangeSet(); assertNotNull( changeSet ); assertEquals( changeSet.getSequence(), 1 ); assertEquals( response.getRequest(), request.getEntry() ); assertEquals( connection.getPendingResponses().size(), 1 ); assertEquals( connection.getCurrentMessageResponse(), null ); } @Test public void parseMessageResponse_cacheResult() { final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), true, ChannelSchema.FilterType.NONE, null, true, true ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[ 0 ] ); final TestConnector connector = TestConnector.create( schema ); final Connection connection = newConnection( connector ); final Request request = connection.newRequest( "SomeAction" ); final int requestId = request.getRequestId(); final String etag = ValueUtil.randomString(); final String rawJsonData = "{\"last_id\": 1" + ", \"requestId\": " + requestId + ", \"etag\": \"" + etag + "\"" + ", \"channel_actions\": [ { \"cid\": 0, \"action\": \"add\"} ] }"; final MessageResponse response = new MessageResponse( rawJsonData ); connection.setCurrentMessageResponse( response ); assertEquals( connection.getPendingResponses().size(), 0 ); final CacheService cacheService = new TestCacheService(); Replicant.context().setCacheService( cacheService ); assertNull( cacheService.lookup( ValueUtil.randomString() ) ); connector.parseMessageResponse(); assertEquals( response.getRawJsonData(), null ); final ChangeSet changeSet = response.getChangeSet(); assertNotNull( changeSet ); assertEquals( changeSet.getSequence(), 1 ); assertEquals( response.getRequest(), request.getEntry() ); assertEquals( connection.getPendingResponses().size(), 1 ); assertEquals( connection.getCurrentMessageResponse(), null ); final String cacheKey = "RC-1.0"; final CacheEntry entry = cacheService.lookup( cacheKey ); assertNotNull( entry ); assertEquals( entry.getKey(), cacheKey ); assertEquals( entry.getETag(), etag ); assertEquals( entry.getContent(), rawJsonData ); } @Test public void parseMessageResponse_eTagWhenNotCacheCandidate() { final TestConnector connector = TestConnector.create(); final Connection connection = newConnection( connector ); final Request request = connection.newRequest( "SomeAction" ); final int requestId = request.getRequestId(); final String etag = ValueUtil.randomString(); final String rawJsonData = "{\"last_id\": 1" + ", \"requestId\": " + requestId + ", \"etag\": \"" + etag + "\"" + ", \"channel_actions\": [ { \"cid\": 0, \"action\": \"add\"}, { \"cid\": 1, \"scid\": 1, \"action\": \"add\"} ] }"; final MessageResponse response = new MessageResponse( rawJsonData ); connection.setCurrentMessageResponse( response ); assertEquals( connection.getPendingResponses().size(), 0 ); final CacheService cacheService = new TestCacheService(); Replicant.context().setCacheService( cacheService ); assertNull( cacheService.lookup( ValueUtil.randomString() ) ); final IllegalStateException exception = expectThrows( IllegalStateException.class, connector::parseMessageResponse ); assertEquals( exception.getMessage(), "Replicant-0072: eTag in reply for ChangeSet 1 but ChangeSet is not a candidate for caching." ); } @Test public void parseMessageResponse_oob() { final TestConnector connector = TestConnector.create(); final Connection connection = newConnection( connector ); final Request request = connection.newRequest( "SomeAction" ); final int requestId = request.getRequestId(); @Language( "json" ) final String rawJsonData = "{\"last_id\": 1, \"requestId\": " + requestId + "}"; final SafeProcedure oobCompletionAction = () -> { }; final MessageResponse response = new MessageResponse( rawJsonData, oobCompletionAction ); connection.setCurrentMessageResponse( response ); assertEquals( connection.getPendingResponses().size(), 0 ); connector.parseMessageResponse(); assertEquals( response.getRawJsonData(), null ); final ChangeSet changeSet = response.getChangeSet(); assertNotNull( changeSet ); assertEquals( changeSet.getSequence(), 1 ); assertNull( response.getRequest() ); assertEquals( connection.getPendingResponses().size(), 1 ); assertEquals( connection.getCurrentMessageResponse(), null ); } @Test public void parseMessageResponse_invalidRequestId() { final TestConnector connector = TestConnector.create(); final Connection connection = newConnection( connector ); @Language( "json" ) final String rawJsonData = "{\"last_id\": 1, \"requestId\": 22}"; final MessageResponse response = new MessageResponse( rawJsonData ); connection.setCurrentMessageResponse( response ); assertEquals( connection.getPendingResponses().size(), 0 ); final IllegalStateException exception = expectThrows( IllegalStateException.class, connector::parseMessageResponse ); assertEquals( exception.getMessage(), "Replicant-0066: Unable to locate request with id '22' specified for ChangeSet with sequence 1. Existing Requests: {}" ); } @Test public void completeMessageResponse() { final TestConnector connector = TestConnector.create(); final Connection connection = newConnection( connector ); final MessageResponse response = new MessageResponse( "" ); final ChangeSet changeSet = ChangeSet.create( 23, null, null ); response.recordChangeSet( changeSet, null ); connection.setLastRxSequence( 22 ); connection.setCurrentMessageResponse( response ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); connector.completeMessageResponse(); assertEquals( connection.getLastRxSequence(), 23 ); assertEquals( connection.getCurrentMessageResponse(), null ); handler.assertEventCount( 1 ); handler.assertNextEvent( MessageProcessedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getSchemaName(), connector.getSchema().getName() ); assertEquals( e.getDataLoadStatus().getSequence(), changeSet.getSequence() ); } ); } @Test public void completeMessageResponse_withPostAction() { final TestConnector connector = TestConnector.create(); final Connection connection = newConnection( connector ); final MessageResponse response = new MessageResponse( "" ); final ChangeSet changeSet = ChangeSet.create( 23, null, null ); response.recordChangeSet( changeSet, null ); connection.setLastRxSequence( 22 ); connection.setCurrentMessageResponse( response ); final AtomicInteger postActionCallCount = new AtomicInteger(); connector.setPostMessageResponseAction( postActionCallCount::incrementAndGet ); assertEquals( postActionCallCount.get(), 0 ); connector.completeMessageResponse(); assertEquals( postActionCallCount.get(), 1 ); } @Test public void completeMessageResponse_OOBMessage() { final TestConnector connector = TestConnector.create(); final Connection connection = newConnection( connector ); final AtomicInteger completionCallCount = new AtomicInteger(); final MessageResponse response = new MessageResponse( "", completionCallCount::incrementAndGet ); final ChangeSet changeSet = ChangeSet.create( 23, 1234, null, null, null ); response.recordChangeSet( changeSet, null ); connection.setLastRxSequence( 22 ); connection.setCurrentMessageResponse( response ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); assertEquals( completionCallCount.get(), 0 ); connector.completeMessageResponse(); assertEquals( completionCallCount.get(), 1 ); assertEquals( connection.getLastRxSequence(), 22 ); assertEquals( connection.getCurrentMessageResponse(), null ); handler.assertEventCount( 1 ); handler.assertNextEvent( MessageProcessedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getSchemaName(), connector.getSchema().getName() ); assertEquals( e.getDataLoadStatus().getSequence(), changeSet.getSequence() ); } ); } @Test public void completeMessageResponse_MessageWithRequest_RPCComplete() { final TestConnector connector = TestConnector.create(); final Connection connection = newConnection( connector ); final Request request = connection.newRequest( "SomeAction" ); final AtomicInteger completionCalled = new AtomicInteger(); final int requestId = request.getRequestId(); final RequestEntry entry = request.getEntry(); entry.setNormalCompletion( true ); entry.setCompletionAction( completionCalled::incrementAndGet ); final MessageResponse response = new MessageResponse( "" ); final ChangeSet changeSet = ChangeSet.create( 23, requestId, null, null, null ); response.recordChangeSet( changeSet, entry ); connection.setLastRxSequence( 22 ); connection.setCurrentMessageResponse( response ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); assertEquals( entry.haveResultsArrived(), false ); assertEquals( completionCalled.get(), 0 ); assertEquals( connection.getRequest( requestId ), entry ); connector.completeMessageResponse(); assertEquals( entry.haveResultsArrived(), true ); assertEquals( connection.getLastRxSequence(), 23 ); assertEquals( connection.getCurrentMessageResponse(), null ); assertEquals( completionCalled.get(), 1 ); assertEquals( connection.getRequest( requestId ), null ); handler.assertEventCount( 1 ); handler.assertNextEvent( MessageProcessedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getSchemaName(), connector.getSchema().getName() ); assertEquals( e.getDataLoadStatus().getSequence(), changeSet.getSequence() ); } ); } @Test public void completeMessageResponse_MessageWithRequest_RPCNotComplete() { final TestConnector connector = TestConnector.create(); final Connection connection = newConnection( connector ); final Request request = connection.newRequest( "SomeAction" ); final AtomicInteger completionCalled = new AtomicInteger(); final int requestId = request.getRequestId(); final RequestEntry entry = request.getEntry(); final MessageResponse response = new MessageResponse( "" ); final ChangeSet changeSet = ChangeSet.create( 23, requestId, null, null, null ); response.recordChangeSet( changeSet, entry ); connection.setLastRxSequence( 22 ); connection.setCurrentMessageResponse( response ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); assertEquals( entry.haveResultsArrived(), false ); assertEquals( completionCalled.get(), 0 ); assertEquals( connection.getRequest( requestId ), entry ); connector.completeMessageResponse(); assertEquals( entry.haveResultsArrived(), true ); assertEquals( connection.getLastRxSequence(), 23 ); assertEquals( connection.getCurrentMessageResponse(), null ); assertEquals( completionCalled.get(), 0 ); assertEquals( connection.getRequest( requestId ), entry ); handler.assertEventCount( 1 ); handler.assertNextEvent( MessageProcessedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getSchemaName(), connector.getSchema().getName() ); assertEquals( e.getDataLoadStatus().getSequence(), changeSet.getSequence() ); } ); } @SuppressWarnings( "ResultOfMethodCallIgnored" ) @Test public void progressResponseProcessing() { /* * This test steps through each stage of a message processing. */ final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), true, ChannelSchema.FilterType.NONE, null, false, true ); final EntitySchema entitySchema = new EntitySchema( 0, ValueUtil.randomString(), MyEntity.class ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[]{ entitySchema } ); final TestConnector connector = TestConnector.create( schema ); final Connection connection = newConnection( connector ); @Language( "json" ) final String rawJsonData = "{" + "\"last_id\": 1, " + // Add Channel 0 "\"channel_actions\": [ { \"cid\": 0, \"action\": \"add\"} ], " + // Add Entity 1 of type 0 from channel 0 "\"changes\": [{\"id\": 1,\"type\":0,\"channels\":[{\"cid\": 0}], \"data\":{}}] " + "}"; connection.enqueueResponse( rawJsonData ); final MessageResponse response = connection.getUnparsedResponses().get( 0 ); { assertEquals( connection.getCurrentMessageResponse(), null ); assertEquals( connection.getUnparsedResponses().size(), 1 ); // Select response assertTrue( connector.progressResponseProcessing() ); assertEquals( connection.getCurrentMessageResponse(), response ); assertEquals( connection.getUnparsedResponses().size(), 0 ); } { assertEquals( response.getRawJsonData(), rawJsonData ); assertThrows( response::getChangeSet ); assertEquals( response.needsParsing(), true ); assertEquals( connection.getPendingResponses().size(), 0 ); // Parse response assertTrue( connector.progressResponseProcessing() ); assertEquals( response.getRawJsonData(), null ); assertNotNull( response.getChangeSet() ); assertEquals( response.needsParsing(), false ); } { assertEquals( connection.getCurrentMessageResponse(), null ); assertEquals( connection.getPendingResponses().size(), 1 ); // Pickup parsed response and set it as current assertTrue( connector.progressResponseProcessing() ); assertEquals( connection.getCurrentMessageResponse(), response ); assertEquals( connection.getPendingResponses().size(), 0 ); } { assertEquals( response.needsChannelChangesProcessed(), true ); // Process Channel Changes in response assertTrue( connector.progressResponseProcessing() ); assertEquals( response.needsChannelChangesProcessed(), false ); } { assertEquals( response.areEntityChangesPending(), true ); when( connector.getChangeMapper().createEntity( any( EntitySchema.class ), anyInt(), any( EntityChangeData.class ) ) ) .thenReturn( mock( Linkable.class ) ); // Process Entity Changes in response assertTrue( connector.progressResponseProcessing() ); assertEquals( response.areEntityChangesPending(), false ); } { assertEquals( response.areEntityLinksPending(), true ); // Process Entity Links in response assertTrue( connector.progressResponseProcessing() ); assertEquals( response.areEntityLinksPending(), false ); } { assertEquals( response.hasWorldBeenValidated(), false ); // Validate World assertTrue( connector.progressResponseProcessing() ); assertEquals( response.hasWorldBeenValidated(), true ); } { assertEquals( connection.getCurrentMessageResponse(), response ); // Complete message assertTrue( connector.progressResponseProcessing() ); assertEquals( connection.getCurrentMessageResponse(), null ); } } @SuppressWarnings( "unchecked" ) @Test public void progressAreaOfInterestAddRequest_onSuccess() { final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), true, ChannelSchema.FilterType.STATIC, null, false, true ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[]{} ); final TestConnector connector = TestConnector.create( schema ); final Connection connection = newConnection( connector ); final ChannelAddress address = new ChannelAddress( 1, 0 ); final String filter = ValueUtil.randomString(); final AreaOfInterestRequest request = new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.ADD, filter ); pauseScheduler(); connection.injectCurrentAreaOfInterestRequest( request ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); final AtomicReference<SafeProcedure> onSuccess = new AtomicReference<>(); final AtomicInteger callCount = new AtomicInteger(); doAnswer( i -> { callCount.incrementAndGet(); assertEquals( i.getArguments()[ 0 ], address ); onSuccess.set( (SafeProcedure) i.getArguments()[ 2 ] ); return null; } ) .when( connector.getTransport() ) .requestSubscribe( eq( address ), eq( filter ), any( SafeProcedure.class ), any() ); assertEquals( callCount.get(), 0 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); connector.progressAreaOfInterestAddRequest( request ); assertEquals( callCount.get(), 1 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); assertNull( safeAction( () -> Replicant.context().findSubscription( address ) ) ); handler.assertEventCount( 1 ); handler.assertNextEvent( SubscribeStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address ); } ); onSuccess.get().call(); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true ); assertNull( safeAction( () -> Replicant.context().findSubscription( address ) ) ); handler.assertEventCount( 2 ); handler.assertNextEvent( SubscribeCompletedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address ); } ); } @SuppressWarnings( "unchecked" ) @Test public void progressAreaOfInterestAddRequest_onSuccess_CachedValueNotInLocalCache() { final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), true, ChannelSchema.FilterType.STATIC, null, true, true ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[]{} ); final TestConnector connector = TestConnector.create( schema ); final Connection connection = newConnection( connector ); pauseScheduler(); connector.pauseMessageScheduler(); final ChannelAddress address = new ChannelAddress( 1, 0 ); final String filter = ValueUtil.randomString(); final AreaOfInterestRequest request = new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.ADD, filter ); connection.injectCurrentAreaOfInterestRequest( request ); Replicant.context().setCacheService( new TestCacheService() ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); final AtomicReference<SafeProcedure> onSuccess = new AtomicReference<>(); final AtomicInteger callCount = new AtomicInteger(); doAnswer( i -> { callCount.incrementAndGet(); assertEquals( i.getArguments()[ 0 ], address ); onSuccess.set( (SafeProcedure) i.getArguments()[ 2 ] ); return null; } ) .when( connector.getTransport() ) .requestSubscribe( eq( address ), eq( filter ), any( SafeProcedure.class ), any() ); assertEquals( callCount.get(), 0 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); connector.progressAreaOfInterestAddRequest( request ); assertEquals( callCount.get(), 1 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); assertNull( safeAction( () -> Replicant.context().findSubscription( address ) ) ); handler.assertEventCount( 1 ); handler.assertNextEvent( SubscribeStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address ); } ); onSuccess.get().call(); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true ); assertNull( safeAction( () -> Replicant.context().findSubscription( address ) ) ); handler.assertEventCount( 2 ); handler.assertNextEvent( SubscribeCompletedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address ); } ); } @SuppressWarnings( "unchecked" ) @Test public void progressAreaOfInterestAddRequest_onSuccess_CachedValueInLocalCache() { final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), true, ChannelSchema.FilterType.STATIC, null, true, true ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[]{} ); final TestConnector connector = TestConnector.create( schema ); final Connection connection = newConnection( connector ); final ChannelAddress address = new ChannelAddress( 1, 0 ); final String filter = ValueUtil.randomString(); final AreaOfInterestRequest request = new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.ADD, filter ); pauseScheduler(); connector.pauseMessageScheduler(); connection.injectCurrentAreaOfInterestRequest( request ); final TestCacheService cacheService = new TestCacheService(); Replicant.context().setCacheService( cacheService ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); final String key = "1.0"; final String eTag = ""; cacheService.store( key, eTag, ValueUtil.randomString() ); final AtomicReference<SafeProcedure> onCacheValid = new AtomicReference<>(); final AtomicInteger callCount = new AtomicInteger(); doAnswer( i -> { callCount.incrementAndGet(); assertEquals( i.getArguments()[ 0 ], address ); assertEquals( i.getArguments()[ 2 ], eTag ); assertNotNull( i.getArguments()[ 3 ] ); onCacheValid.set( (SafeProcedure) i.getArguments()[ 3 ] ); return null; } ) .when( connector.getTransport() ) .requestSubscribe( eq( address ), eq( filter ), any(), any( SafeProcedure.class ), any( SafeProcedure.class ), any() ); assertEquals( callCount.get(), 0 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); connector.progressAreaOfInterestAddRequest( request ); assertEquals( callCount.get(), 1 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); assertNull( safeAction( () -> Replicant.context().findSubscription( address ) ) ); handler.assertEventCount( 1 ); handler.assertNextEvent( SubscribeStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address ); } ); assertEquals( connector.isSchedulerActive(), false ); assertEquals( connection.getOutOfBandResponses().size(), 0 ); onCacheValid.get().call(); assertEquals( connector.isSchedulerActive(), true ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true ); assertEquals( connection.getOutOfBandResponses().size(), 1 ); assertNull( safeAction( () -> Replicant.context().findSubscription( address ) ) ); handler.assertEventCount( 1 ); } @SuppressWarnings( "unchecked" ) @Test public void progressAreaOfInterestAddRequest_onFailure() { final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), true, ChannelSchema.FilterType.STATIC, null, false, true ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[]{} ); final TestConnector connector = TestConnector.create( schema ); final Connection connection = newConnection( connector ); final ChannelAddress address = new ChannelAddress( 1, 0 ); final String filter = ValueUtil.randomString(); final AreaOfInterestRequest request = new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.ADD, filter ); pauseScheduler(); connection.injectCurrentAreaOfInterestRequest( request ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>(); final AtomicInteger callCount = new AtomicInteger(); doAnswer( i -> { callCount.incrementAndGet(); assertEquals( i.getArguments()[ 0 ], address ); onFailure.set( (Consumer<Throwable>) i.getArguments()[ 3 ] ); return null; } ) .when( connector.getTransport() ) .requestSubscribe( eq( address ), eq( filter ), any( SafeProcedure.class ), any() ); assertEquals( callCount.get(), 0 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); connector.progressAreaOfInterestAddRequest( request ); assertEquals( callCount.get(), 1 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); assertNull( safeAction( () -> Replicant.context().findSubscription( address ) ) ); handler.assertEventCount( 1 ); handler.assertNextEvent( SubscribeStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address ); } ); final Throwable error = new Throwable(); onFailure.get().accept( error ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true ); assertNull( safeAction( () -> Replicant.context().findSubscription( address ) ) ); handler.assertEventCount( 2 ); handler.assertNextEvent( SubscribeFailedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address ); assertEquals( e.getError(), error ); } ); } @SuppressWarnings( "unchecked" ) @Test public void progressBulkAreaOfInterestAddRequests_onSuccess() { final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), false, ChannelSchema.FilterType.STATIC, null, false, true ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[]{} ); final TestConnector connector = TestConnector.create( schema ); final Connection connection = newConnection( connector ); final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 ); final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 ); final ChannelAddress address3 = new ChannelAddress( 1, 0, 3 ); final String filter = ValueUtil.randomString(); final AreaOfInterestRequest request1 = new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, filter ); final AreaOfInterestRequest request2 = new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.ADD, filter ); final AreaOfInterestRequest request3 = new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.ADD, filter ); pauseScheduler(); final Subscription subscription1 = createSubscription( address1, null, true ); final Subscription subscription2 = createSubscription( address2, null, true ); final Subscription subscription3 = createSubscription( address3, null, true ); connection.injectCurrentAreaOfInterestRequest( request1 ); connection.injectCurrentAreaOfInterestRequest( request2 ); connection.injectCurrentAreaOfInterestRequest( request3 ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); final AtomicReference<SafeProcedure> onSuccess = new AtomicReference<>(); final AtomicInteger callCount = new AtomicInteger(); doAnswer( i -> { callCount.incrementAndGet(); final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ]; assertEquals( addresses.contains( address1 ), true ); assertEquals( addresses.contains( address2 ), true ); assertEquals( addresses.contains( address3 ), true ); onSuccess.set( (SafeProcedure) i.getArguments()[ 2 ] ); return null; } ) .when( connector.getTransport() ) .requestBulkSubscribe( anyListOf( ChannelAddress.class ), eq( filter ), any( SafeProcedure.class ), any() ); assertEquals( callCount.get(), 0 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); connector.progressBulkAreaOfInterestAddRequests( Arrays.asList( request1, request2, request3 ) ); assertEquals( callCount.get(), 1 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) ); safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) ); safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), true ) ); handler.assertEventCount( 3 ); handler.assertNextEvent( SubscribeStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address1 ); } ); handler.assertNextEvent( SubscribeStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address2 ); } ); handler.assertNextEvent( SubscribeStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address3 ); } ); onSuccess.get().call(); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true ); safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) ); safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) ); safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), true ) ); handler.assertEventCount( 6 ); handler.assertNextEvent( SubscribeCompletedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address1 ); } ); handler.assertNextEvent( SubscribeCompletedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address2 ); } ); handler.assertNextEvent( SubscribeCompletedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address3 ); } ); } @SuppressWarnings( "unchecked" ) @Test public void progressBulkAreaOfInterestAddRequests_onFailure() { final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), false, ChannelSchema.FilterType.STATIC, null, false, true ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[]{} ); final TestConnector connector = TestConnector.create( schema ); final Connection connection = newConnection( connector ); final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 ); final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 ); final ChannelAddress address3 = new ChannelAddress( 1, 0, 3 ); final String filter = ValueUtil.randomString(); final AreaOfInterestRequest request1 = new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, filter ); final AreaOfInterestRequest request2 = new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.ADD, filter ); final AreaOfInterestRequest request3 = new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.ADD, filter ); pauseScheduler(); final Subscription subscription1 = createSubscription( address1, null, true ); final Subscription subscription2 = createSubscription( address2, null, true ); final Subscription subscription3 = createSubscription( address3, null, true ); connection.injectCurrentAreaOfInterestRequest( request1 ); connection.injectCurrentAreaOfInterestRequest( request2 ); connection.injectCurrentAreaOfInterestRequest( request3 ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>(); final AtomicInteger callCount = new AtomicInteger(); doAnswer( i -> { callCount.incrementAndGet(); final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ]; assertEquals( addresses.contains( address1 ), true ); assertEquals( addresses.contains( address2 ), true ); assertEquals( addresses.contains( address3 ), true ); onFailure.set( (Consumer<Throwable>) i.getArguments()[ 3 ] ); return null; } ) .when( connector.getTransport() ) .requestBulkSubscribe( anyListOf( ChannelAddress.class ), eq( filter ), any( SafeProcedure.class ), any() ); assertEquals( callCount.get(), 0 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); connector.progressBulkAreaOfInterestAddRequests( Arrays.asList( request1, request2, request3 ) ); assertEquals( callCount.get(), 1 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) ); safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) ); safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), true ) ); handler.assertEventCount( 3 ); handler.assertNextEvent( SubscribeStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address1 ); } ); handler.assertNextEvent( SubscribeStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address2 ); } ); handler.assertNextEvent( SubscribeStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address3 ); } ); final Throwable error = new Throwable(); onFailure.get().accept( error ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true ); safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) ); safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) ); safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), true ) ); handler.assertEventCount( 6 ); handler.assertNextEvent( SubscribeFailedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address1 ); assertEquals( e.getError(), error ); } ); handler.assertNextEvent( SubscribeFailedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address2 ); assertEquals( e.getError(), error ); } ); handler.assertNextEvent( SubscribeFailedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address3 ); assertEquals( e.getError(), error ); } ); } @SuppressWarnings( "unchecked" ) @Test public void progressAreaOfInterestAddRequests_onFailure_singleRequests() { final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), false, ChannelSchema.FilterType.STATIC, null, false, true ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[]{} ); final TestConnector connector = TestConnector.create( schema ); final Connection connection = newConnection( connector ); final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 ); final String filter = ValueUtil.randomString(); final AreaOfInterestRequest request1 = new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, filter ); pauseScheduler(); connection.injectCurrentAreaOfInterestRequest( request1 ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>(); final AtomicInteger callCount = new AtomicInteger(); doAnswer( i -> { callCount.incrementAndGet(); onFailure.set( (Consumer<Throwable>) i.getArguments()[ 3 ] ); return null; } ) .when( connector.getTransport() ) .requestSubscribe( eq( address1 ), eq( filter ), any( SafeProcedure.class ), any() ); assertEquals( callCount.get(), 0 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>(); requests.add( request1 ); connector.progressAreaOfInterestAddRequests( requests ); assertEquals( callCount.get(), 1 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); handler.assertEventCount( 1 ); handler.assertNextEvent( SubscribeStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address1 ); } ); final Throwable error = new Throwable(); onFailure.get().accept( error ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true ); handler.assertEventCount( 2 ); handler.assertNextEvent( SubscribeFailedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address1 ); assertEquals( e.getError(), error ); } ); } @SuppressWarnings( "unchecked" ) @Test public void progressAreaOfInterestAddRequests_onFailure_zeroRequests() { final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), false, ChannelSchema.FilterType.STATIC, null, false, true ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[]{} ); final TestConnector connector = TestConnector.create( schema ); final Connection connection = newConnection( connector ); final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 ); final String filter = ValueUtil.randomString(); final AreaOfInterestRequest request1 = new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, filter ); pauseScheduler(); connection.injectCurrentAreaOfInterestRequest( request1 ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>(); // Pass in empty requests list to simulate that they are all filtered out connector.progressAreaOfInterestAddRequests( requests ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true ); handler.assertEventCount( 0 ); } @SuppressWarnings( "unchecked" ) @Test public void progressAreaOfInterestAddRequests_onFailure_multipleRequests() { final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), false, ChannelSchema.FilterType.STATIC, null, false, true ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[]{} ); final TestConnector connector = TestConnector.create( schema ); final Connection connection = newConnection( connector ); final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 ); final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 ); final String filter = ValueUtil.randomString(); final AreaOfInterestRequest request1 = new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, filter ); final AreaOfInterestRequest request2 = new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.ADD, filter ); pauseScheduler(); connector.pauseMessageScheduler(); connection.injectCurrentAreaOfInterestRequest( request1 ); connection.injectCurrentAreaOfInterestRequest( request2 ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>(); final AtomicInteger callCount = new AtomicInteger(); doAnswer( i -> { callCount.incrementAndGet(); final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ]; assertEquals( addresses.contains( address1 ), true ); assertEquals( addresses.contains( address2 ), true ); onFailure.set( (Consumer<Throwable>) i.getArguments()[ 3 ] ); return null; } ) .when( connector.getTransport() ) .requestBulkSubscribe( anyListOf( ChannelAddress.class ), eq( filter ), any( SafeProcedure.class ), any() ); assertEquals( callCount.get(), 0 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>(); requests.add( request1 ); requests.add( request2 ); connector.progressAreaOfInterestAddRequests( requests ); assertEquals( callCount.get(), 1 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); handler.assertEventCount( 2 ); handler.assertNextEvent( SubscribeStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address1 ); } ); handler.assertNextEvent( SubscribeStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address2 ); } ); final Throwable error = new Throwable(); onFailure.get().accept( error ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true ); handler.assertEventCount( 4 ); handler.assertNextEvent( SubscribeFailedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address1 ); assertEquals( e.getError(), error ); } ); handler.assertNextEvent( SubscribeFailedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address2 ); assertEquals( e.getError(), error ); } ); } @SuppressWarnings( "unchecked" ) @Test public void progressAreaOfInterestUpdateRequest_onSuccess() { final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), true, ChannelSchema.FilterType.DYNAMIC, mock( SubscriptionUpdateEntityFilter.class ), false, true ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[]{} ); final TestConnector connector = TestConnector.create( schema ); final Connection connection = newConnection( connector ); final ChannelAddress address = new ChannelAddress( 1, 0 ); final String filter = ValueUtil.randomString(); final AreaOfInterestRequest request = new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.UPDATE, filter ); pauseScheduler(); final Subscription subscription = createSubscription( address, null, true ); connection.injectCurrentAreaOfInterestRequest( request ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); final AtomicReference<SafeProcedure> onSuccess = new AtomicReference<>(); final AtomicInteger callCount = new AtomicInteger(); doAnswer( i -> { callCount.incrementAndGet(); assertEquals( i.getArguments()[ 0 ], address ); onSuccess.set( (SafeProcedure) i.getArguments()[ 2 ] ); return null; } ) .when( connector.getTransport() ) .requestSubscriptionUpdate( eq( address ), eq( filter ), any( SafeProcedure.class ), any() ); assertEquals( callCount.get(), 0 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); connector.progressAreaOfInterestUpdateRequest( request ); assertEquals( callCount.get(), 1 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); safeAction( () -> assertEquals( subscription.isExplicitSubscription(), true ) ); handler.assertEventCount( 1 ); handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address ); } ); onSuccess.get().call(); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true ); safeAction( () -> assertEquals( subscription.isExplicitSubscription(), true ) ); handler.assertEventCount( 2 ); handler.assertNextEvent( SubscriptionUpdateCompletedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address ); } ); } @SuppressWarnings( "unchecked" ) @Test public void progressAreaOfInterestUpdateRequest_onFailure() { final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), true, ChannelSchema.FilterType.DYNAMIC, mock( SubscriptionUpdateEntityFilter.class ), false, true ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[]{} ); final TestConnector connector = TestConnector.create( schema ); final Connection connection = newConnection( connector ); final ChannelAddress address = new ChannelAddress( 1, 0 ); final String filter = ValueUtil.randomString(); final AreaOfInterestRequest request = new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.UPDATE, filter ); pauseScheduler(); final Subscription subscription = createSubscription( address, null, true ); connection.injectCurrentAreaOfInterestRequest( request ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>(); final AtomicInteger callCount = new AtomicInteger(); doAnswer( i -> { callCount.incrementAndGet(); assertEquals( i.getArguments()[ 0 ], address ); onFailure.set( (Consumer<Throwable>) i.getArguments()[ 3 ] ); return null; } ) .when( connector.getTransport() ) .requestSubscriptionUpdate( eq( address ), eq( filter ), any( SafeProcedure.class ), any() ); assertEquals( callCount.get(), 0 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); connector.progressAreaOfInterestUpdateRequest( request ); assertEquals( callCount.get(), 1 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); safeAction( () -> assertEquals( subscription.isExplicitSubscription(), true ) ); handler.assertEventCount( 1 ); handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address ); } ); final Throwable error = new Throwable(); onFailure.get().accept( error ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true ); safeAction( () -> assertEquals( subscription.isExplicitSubscription(), true ) ); handler.assertEventCount( 2 ); handler.assertNextEvent( SubscriptionUpdateFailedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address ); assertEquals( e.getError(), error ); } ); } @SuppressWarnings( "unchecked" ) @Test public void progressBulkAreaOfInterestUpdateRequests_onSuccess() { final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), false, ChannelSchema.FilterType.DYNAMIC, mock( SubscriptionUpdateEntityFilter.class ), false, true ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[]{} ); final TestConnector connector = TestConnector.create( schema ); final Connection connection = newConnection( connector ); final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 ); final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 ); final ChannelAddress address3 = new ChannelAddress( 1, 0, 3 ); final String filter = ValueUtil.randomString(); final AreaOfInterestRequest request1 = new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.UPDATE, filter ); final AreaOfInterestRequest request2 = new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.UPDATE, filter ); final AreaOfInterestRequest request3 = new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.UPDATE, filter ); pauseScheduler(); final Subscription subscription1 = createSubscription( address1, null, true ); final Subscription subscription2 = createSubscription( address2, null, true ); final Subscription subscription3 = createSubscription( address3, null, true ); connection.injectCurrentAreaOfInterestRequest( request1 ); connection.injectCurrentAreaOfInterestRequest( request2 ); connection.injectCurrentAreaOfInterestRequest( request3 ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); final AtomicReference<SafeProcedure> onSuccess = new AtomicReference<>(); final AtomicInteger callCount = new AtomicInteger(); doAnswer( i -> { callCount.incrementAndGet(); final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ]; assertEquals( addresses.contains( address1 ), true ); assertEquals( addresses.contains( address2 ), true ); assertEquals( addresses.contains( address3 ), true ); onSuccess.set( (SafeProcedure) i.getArguments()[ 2 ] ); return null; } ) .when( connector.getTransport() ) .requestBulkSubscriptionUpdate( anyListOf( ChannelAddress.class ), eq( filter ), any( SafeProcedure.class ), any() ); assertEquals( callCount.get(), 0 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); connector.progressBulkAreaOfInterestUpdateRequests( Arrays.asList( request1, request2, request3 ) ); assertEquals( callCount.get(), 1 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) ); safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) ); safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), true ) ); handler.assertEventCount( 3 ); handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address1 ); } ); handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address2 ); } ); handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address3 ); } ); onSuccess.get().call(); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true ); safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) ); safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) ); safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), true ) ); handler.assertEventCount( 6 ); handler.assertNextEvent( SubscriptionUpdateCompletedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address1 ); } ); handler.assertNextEvent( SubscriptionUpdateCompletedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address2 ); } ); handler.assertNextEvent( SubscriptionUpdateCompletedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address3 ); } ); } @SuppressWarnings( "unchecked" ) @Test public void progressBulkAreaOfInterestUpdateRequests_onFailure() { final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), false, ChannelSchema.FilterType.DYNAMIC, mock( SubscriptionUpdateEntityFilter.class ), false, true ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[]{} ); final TestConnector connector = TestConnector.create( schema ); final Connection connection = newConnection( connector ); final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 ); final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 ); final ChannelAddress address3 = new ChannelAddress( 1, 0, 3 ); final String filter = ValueUtil.randomString(); final AreaOfInterestRequest request1 = new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.UPDATE, filter ); final AreaOfInterestRequest request2 = new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.UPDATE, filter ); final AreaOfInterestRequest request3 = new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.UPDATE, filter ); pauseScheduler(); final Subscription subscription1 = createSubscription( address1, null, true ); final Subscription subscription2 = createSubscription( address2, null, true ); final Subscription subscription3 = createSubscription( address3, null, true ); connection.injectCurrentAreaOfInterestRequest( request1 ); connection.injectCurrentAreaOfInterestRequest( request2 ); connection.injectCurrentAreaOfInterestRequest( request3 ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>(); final AtomicInteger callCount = new AtomicInteger(); doAnswer( i -> { callCount.incrementAndGet(); final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ]; assertEquals( addresses.contains( address1 ), true ); assertEquals( addresses.contains( address2 ), true ); assertEquals( addresses.contains( address3 ), true ); onFailure.set( (Consumer<Throwable>) i.getArguments()[ 3 ] ); return null; } ) .when( connector.getTransport() ) .requestBulkSubscriptionUpdate( anyListOf( ChannelAddress.class ), eq( filter ), any( SafeProcedure.class ), any() ); assertEquals( callCount.get(), 0 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); connector.progressBulkAreaOfInterestUpdateRequests( Arrays.asList( request1, request2, request3 ) ); assertEquals( callCount.get(), 1 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) ); safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) ); safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), true ) ); handler.assertEventCount( 3 ); handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address1 ); } ); handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address2 ); } ); handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address3 ); } ); final Throwable error = new Throwable(); onFailure.get().accept( error ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true ); safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) ); safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) ); safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), true ) ); handler.assertEventCount( 6 ); handler.assertNextEvent( SubscriptionUpdateFailedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address1 ); assertEquals( e.getError(), error ); } ); handler.assertNextEvent( SubscriptionUpdateFailedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address2 ); assertEquals( e.getError(), error ); } ); handler.assertNextEvent( SubscriptionUpdateFailedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address3 ); assertEquals( e.getError(), error ); } ); } @SuppressWarnings( "unchecked" ) @Test public void progressAreaOfInterestUpdateRequests_onFailure_singleRequests() { final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), false, ChannelSchema.FilterType.DYNAMIC, mock( SubscriptionUpdateEntityFilter.class ), false, true ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[]{} ); final TestConnector connector = TestConnector.create( schema ); final Connection connection = newConnection( connector ); final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 ); final String filter = ValueUtil.randomString(); final AreaOfInterestRequest request1 = new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.UPDATE, filter ); pauseScheduler(); final Subscription subscription1 = createSubscription( address1, null, true ); connection.injectCurrentAreaOfInterestRequest( request1 ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>(); final AtomicInteger callCount = new AtomicInteger(); doAnswer( i -> { callCount.incrementAndGet(); onFailure.set( (Consumer<Throwable>) i.getArguments()[ 3 ] ); return null; } ) .when( connector.getTransport() ) .requestSubscriptionUpdate( eq( address1 ), eq( filter ), any( SafeProcedure.class ), any() ); assertEquals( callCount.get(), 0 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>(); requests.add( request1 ); connector.progressAreaOfInterestUpdateRequests( requests ); assertEquals( callCount.get(), 1 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) ); handler.assertEventCount( 1 ); handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address1 ); } ); final Throwable error = new Throwable(); onFailure.get().accept( error ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true ); safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) ); handler.assertEventCount( 2 ); handler.assertNextEvent( SubscriptionUpdateFailedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address1 ); assertEquals( e.getError(), error ); } ); } @SuppressWarnings( "unchecked" ) @Test public void progressAreaOfInterestUpdateRequests_onFailure_zeroRequests() { final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), false, ChannelSchema.FilterType.DYNAMIC, mock( SubscriptionUpdateEntityFilter.class ), false, true ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[]{} ); final TestConnector connector = TestConnector.create( schema ); final Connection connection = newConnection( connector ); final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 ); final String filter = ValueUtil.randomString(); final AreaOfInterestRequest request1 = new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.UPDATE, filter ); pauseScheduler(); connection.injectCurrentAreaOfInterestRequest( request1 ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>(); // Pass in empty requests list to simulate that they are all filtered out connector.progressAreaOfInterestUpdateRequests( requests ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true ); handler.assertEventCount( 0 ); } @SuppressWarnings( "unchecked" ) @Test public void progressAreaOfInterestUpdateRequests_onFailure_multipleRequests() { final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), false, ChannelSchema.FilterType.DYNAMIC, mock( SubscriptionUpdateEntityFilter.class ), false, true ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[]{} ); final TestConnector connector = TestConnector.create( schema ); final Connection connection = newConnection( connector ); final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 ); final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 ); final String filter = ValueUtil.randomString(); final AreaOfInterestRequest request1 = new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.UPDATE, filter ); final AreaOfInterestRequest request2 = new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.UPDATE, filter ); pauseScheduler(); final Subscription subscription1 = createSubscription( address1, null, true ); final Subscription subscription2 = createSubscription( address2, null, true ); connection.injectCurrentAreaOfInterestRequest( request1 ); connection.injectCurrentAreaOfInterestRequest( request2 ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>(); final AtomicInteger callCount = new AtomicInteger(); doAnswer( i -> { callCount.incrementAndGet(); final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ]; assertEquals( addresses.contains( address1 ), true ); assertEquals( addresses.contains( address2 ), true ); onFailure.set( (Consumer<Throwable>) i.getArguments()[ 3 ] ); return null; } ) .when( connector.getTransport() ) .requestBulkSubscriptionUpdate( anyListOf( ChannelAddress.class ), eq( filter ), any( SafeProcedure.class ), any() ); assertEquals( callCount.get(), 0 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>(); requests.add( request1 ); requests.add( request2 ); connector.progressAreaOfInterestUpdateRequests( requests ); assertEquals( callCount.get(), 1 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) ); safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) ); handler.assertEventCount( 2 ); handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address1 ); } ); handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address2 ); } ); final Throwable error = new Throwable(); onFailure.get().accept( error ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true ); safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) ); safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) ); handler.assertEventCount( 4 ); handler.assertNextEvent( SubscriptionUpdateFailedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address1 ); assertEquals( e.getError(), error ); } ); handler.assertNextEvent( SubscriptionUpdateFailedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address2 ); assertEquals( e.getError(), error ); } ); } @SuppressWarnings( "unchecked" ) @Test public void progressAreaOfInterestRemoveRequest_onSuccess() { final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), true, ChannelSchema.FilterType.NONE, null, false, true ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[]{} ); final TestConnector connector = TestConnector.create( schema ); final Connection connection = newConnection( connector ); final ChannelAddress address = new ChannelAddress( 1, 0 ); final AreaOfInterestRequest request = new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.REMOVE, null ); pauseScheduler(); final Subscription subscription = createSubscription( address, null, true ); connection.injectCurrentAreaOfInterestRequest( request ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); final AtomicReference<SafeProcedure> onSuccess = new AtomicReference<>(); final AtomicInteger callCount = new AtomicInteger(); doAnswer( i -> { callCount.incrementAndGet(); assertEquals( i.getArguments()[ 0 ], address ); onSuccess.set( (SafeProcedure) i.getArguments()[ 1 ] ); return null; } ) .when( connector.getTransport() ) .requestUnsubscribe( eq( address ), any( SafeProcedure.class ), any() ); assertEquals( callCount.get(), 0 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); connector.progressAreaOfInterestRemoveRequest( request ); assertEquals( callCount.get(), 1 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); safeAction( () -> assertEquals( subscription.isExplicitSubscription(), true ) ); handler.assertEventCount( 1 ); handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address ); } ); onSuccess.get().call(); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true ); safeAction( () -> assertEquals( subscription.isExplicitSubscription(), false ) ); handler.assertEventCount( 2 ); handler.assertNextEvent( UnsubscribeCompletedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address ); } ); } @SuppressWarnings( "unchecked" ) @Test public void progressAreaOfInterestRemoveRequest_onFailure() { final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), true, ChannelSchema.FilterType.NONE, null, false, true ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[]{} ); final TestConnector connector = TestConnector.create( schema ); final Connection connection = newConnection( connector ); final ChannelAddress address = new ChannelAddress( 1, 0 ); final AreaOfInterestRequest request = new AreaOfInterestRequest( address, AreaOfInterestRequest.Type.REMOVE, null ); pauseScheduler(); final Subscription subscription = createSubscription( address, null, true ); connection.injectCurrentAreaOfInterestRequest( request ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>(); final AtomicInteger callCount = new AtomicInteger(); doAnswer( i -> { callCount.incrementAndGet(); assertEquals( i.getArguments()[ 0 ], address ); onFailure.set( (Consumer<Throwable>) i.getArguments()[ 2 ] ); return null; } ) .when( connector.getTransport() ) .requestUnsubscribe( eq( address ), any( SafeProcedure.class ), any() ); assertEquals( callCount.get(), 0 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); connector.progressAreaOfInterestRemoveRequest( request ); assertEquals( callCount.get(), 1 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); safeAction( () -> assertEquals( subscription.isExplicitSubscription(), true ) ); handler.assertEventCount( 1 ); handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address ); } ); final Throwable error = new Throwable(); onFailure.get().accept( error ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true ); safeAction( () -> assertEquals( subscription.isExplicitSubscription(), false ) ); handler.assertEventCount( 2 ); handler.assertNextEvent( UnsubscribeFailedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address ); assertEquals( e.getError(), error ); } ); } @SuppressWarnings( "unchecked" ) @Test public void progressBulkAreaOfInterestRemoveRequests_onSuccess() { final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), false, ChannelSchema.FilterType.NONE, null, false, true ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[]{} ); final TestConnector connector = TestConnector.create( schema ); final Connection connection = newConnection( connector ); final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 ); final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 ); final ChannelAddress address3 = new ChannelAddress( 1, 0, 3 ); final AreaOfInterestRequest request1 = new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null ); final AreaOfInterestRequest request2 = new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.REMOVE, null ); final AreaOfInterestRequest request3 = new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.REMOVE, null ); pauseScheduler(); final Subscription subscription1 = createSubscription( address1, null, true ); final Subscription subscription2 = createSubscription( address2, null, true ); final Subscription subscription3 = createSubscription( address3, null, true ); connection.injectCurrentAreaOfInterestRequest( request1 ); connection.injectCurrentAreaOfInterestRequest( request2 ); connection.injectCurrentAreaOfInterestRequest( request3 ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); final AtomicReference<SafeProcedure> onSuccess = new AtomicReference<>(); final AtomicInteger callCount = new AtomicInteger(); doAnswer( i -> { callCount.incrementAndGet(); final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ]; assertEquals( addresses.contains( address1 ), true ); assertEquals( addresses.contains( address2 ), true ); assertEquals( addresses.contains( address3 ), true ); onSuccess.set( (SafeProcedure) i.getArguments()[ 1 ] ); return null; } ) .when( connector.getTransport() ) .requestBulkUnsubscribe( anyListOf( ChannelAddress.class ), any( SafeProcedure.class ), any() ); assertEquals( callCount.get(), 0 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); connector.progressBulkAreaOfInterestRemoveRequests( Arrays.asList( request1, request2, request3 ) ); assertEquals( callCount.get(), 1 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) ); safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) ); safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), true ) ); handler.assertEventCount( 3 ); handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address1 ); } ); handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address2 ); } ); handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address3 ); } ); onSuccess.get().call(); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true ); safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), false ) ); safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), false ) ); safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), false ) ); handler.assertEventCount( 6 ); handler.assertNextEvent( UnsubscribeCompletedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address1 ); } ); handler.assertNextEvent( UnsubscribeCompletedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address2 ); } ); handler.assertNextEvent( UnsubscribeCompletedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address3 ); } ); } @SuppressWarnings( "unchecked" ) @Test public void progressBulkAreaOfInterestRemoveRequests_onFailure() { final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), false, ChannelSchema.FilterType.NONE, null, false, true ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[]{} ); final TestConnector connector = TestConnector.create( schema ); final Connection connection = newConnection( connector ); final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 ); final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 ); final ChannelAddress address3 = new ChannelAddress( 1, 0, 3 ); final AreaOfInterestRequest request1 = new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null ); final AreaOfInterestRequest request2 = new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.REMOVE, null ); final AreaOfInterestRequest request3 = new AreaOfInterestRequest( address3, AreaOfInterestRequest.Type.REMOVE, null ); pauseScheduler(); final Subscription subscription1 = createSubscription( address1, null, true ); final Subscription subscription2 = createSubscription( address2, null, true ); final Subscription subscription3 = createSubscription( address3, null, true ); connection.injectCurrentAreaOfInterestRequest( request1 ); connection.injectCurrentAreaOfInterestRequest( request2 ); connection.injectCurrentAreaOfInterestRequest( request3 ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>(); final AtomicInteger callCount = new AtomicInteger(); doAnswer( i -> { callCount.incrementAndGet(); final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ]; assertEquals( addresses.contains( address1 ), true ); assertEquals( addresses.contains( address2 ), true ); assertEquals( addresses.contains( address3 ), true ); onFailure.set( (Consumer<Throwable>) i.getArguments()[ 2 ] ); return null; } ) .when( connector.getTransport() ) .requestBulkUnsubscribe( anyListOf( ChannelAddress.class ), any( SafeProcedure.class ), any() ); assertEquals( callCount.get(), 0 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); connector.progressBulkAreaOfInterestRemoveRequests( Arrays.asList( request1, request2, request3 ) ); assertEquals( callCount.get(), 1 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) ); safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) ); safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), true ) ); handler.assertEventCount( 3 ); handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address1 ); } ); handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address2 ); } ); handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address3 ); } ); final Throwable error = new Throwable(); onFailure.get().accept( error ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true ); safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), false ) ); safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), false ) ); safeAction( () -> assertEquals( subscription3.isExplicitSubscription(), false ) ); handler.assertEventCount( 6 ); handler.assertNextEvent( UnsubscribeFailedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address1 ); assertEquals( e.getError(), error ); } ); handler.assertNextEvent( UnsubscribeFailedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address2 ); assertEquals( e.getError(), error ); } ); handler.assertNextEvent( UnsubscribeFailedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address3 ); assertEquals( e.getError(), error ); } ); } @SuppressWarnings( "unchecked" ) @Test public void progressAreaOfInterestRemoveRequests_onFailure_singleRequests() { final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), false, ChannelSchema.FilterType.NONE, null, false, true ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[]{} ); final TestConnector connector = TestConnector.create( schema ); final Connection connection = newConnection( connector ); final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 ); final AreaOfInterestRequest request1 = new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null ); pauseScheduler(); final Subscription subscription1 = createSubscription( address1, null, true ); connection.injectCurrentAreaOfInterestRequest( request1 ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>(); final AtomicInteger callCount = new AtomicInteger(); doAnswer( i -> { callCount.incrementAndGet(); onFailure.set( (Consumer<Throwable>) i.getArguments()[ 2 ] ); return null; } ) .when( connector.getTransport() ) .requestUnsubscribe( eq( address1 ), any( SafeProcedure.class ), any() ); assertEquals( callCount.get(), 0 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>(); requests.add( request1 ); connector.progressAreaOfInterestRemoveRequests( requests ); assertEquals( callCount.get(), 1 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) ); handler.assertEventCount( 1 ); handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address1 ); } ); final Throwable error = new Throwable(); onFailure.get().accept( error ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true ); safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), false ) ); handler.assertEventCount( 2 ); handler.assertNextEvent( UnsubscribeFailedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address1 ); assertEquals( e.getError(), error ); } ); } @SuppressWarnings( "unchecked" ) @Test public void progressAreaOfInterestRemoveRequests_onFailure_zeroRequests() { final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), false, ChannelSchema.FilterType.NONE, null, false, true ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[]{} ); final TestConnector connector = TestConnector.create( schema ); final Connection connection = newConnection( connector ); final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 ); final AreaOfInterestRequest request1 = new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null ); pauseScheduler(); connection.injectCurrentAreaOfInterestRequest( request1 ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>(); // Pass in empty requests list to simulate that they are all filtered out connector.progressAreaOfInterestRemoveRequests( requests ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true ); handler.assertEventCount( 0 ); } @SuppressWarnings( "unchecked" ) @Test public void progressAreaOfInterestRemoveRequests_onFailure_multipleRequests() { final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), false, ChannelSchema.FilterType.NONE, null, false, true ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[]{} ); final TestConnector connector = TestConnector.create( schema ); final Connection connection = newConnection( connector ); final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 ); final ChannelAddress address2 = new ChannelAddress( 1, 0, 2 ); final AreaOfInterestRequest request1 = new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null ); final AreaOfInterestRequest request2 = new AreaOfInterestRequest( address2, AreaOfInterestRequest.Type.REMOVE, null ); pauseScheduler(); final Subscription subscription1 = createSubscription( address1, null, true ); final Subscription subscription2 = createSubscription( address2, null, true ); connection.injectCurrentAreaOfInterestRequest( request1 ); connection.injectCurrentAreaOfInterestRequest( request2 ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); final AtomicReference<Consumer<Throwable>> onFailure = new AtomicReference<>(); final AtomicInteger callCount = new AtomicInteger(); doAnswer( i -> { callCount.incrementAndGet(); final List<ChannelAddress> addresses = (List<ChannelAddress>) i.getArguments()[ 0 ]; assertEquals( addresses.contains( address1 ), true ); assertEquals( addresses.contains( address2 ), true ); onFailure.set( (Consumer<Throwable>) i.getArguments()[ 2 ] ); return null; } ) .when( connector.getTransport() ) .requestBulkUnsubscribe( anyListOf( ChannelAddress.class ), any( SafeProcedure.class ), any() ); assertEquals( callCount.get(), 0 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); final ArrayList<AreaOfInterestRequest> requests = new ArrayList<>(); requests.add( request1 ); requests.add( request2 ); connector.progressAreaOfInterestRemoveRequests( requests ); assertEquals( callCount.get(), 1 ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), true ) ); safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), true ) ); handler.assertEventCount( 2 ); handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address1 ); } ); handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address2 ); } ); final Throwable error = new Throwable(); onFailure.get().accept( error ); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true ); safeAction( () -> assertEquals( subscription1.isExplicitSubscription(), false ) ); safeAction( () -> assertEquals( subscription2.isExplicitSubscription(), false ) ); handler.assertEventCount( 4 ); handler.assertNextEvent( UnsubscribeFailedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address1 ); assertEquals( e.getError(), error ); } ); handler.assertNextEvent( UnsubscribeFailedEvent.class, e -> { assertEquals( e.getSchemaId(), connector.getSchema().getId() ); assertEquals( e.getAddress(), address2 ); assertEquals( e.getError(), error ); } ); } @SuppressWarnings( "unchecked" ) @Test public void progressAreaOfInterestRequestProcessing_Noop() { final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), false, ChannelSchema.FilterType.STATIC, null, false, true ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[]{} ); final TestConnector connector = TestConnector.create( schema ); final Connection connection = newConnection( connector ); pauseScheduler(); final TestSpyEventHandler handler = registerTestSpyEventHandler(); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true ); connector.progressAreaOfInterestRequestProcessing(); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), true ); handler.assertEventCount( 0 ); } @SuppressWarnings( "unchecked" ) @Test public void progressAreaOfInterestRequestProcessing_InProgress() { final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), false, ChannelSchema.FilterType.STATIC, null, false, true ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[]{} ); final TestConnector connector = TestConnector.create( schema ); final Connection connection = newConnection( connector ); final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 ); final String filter = ValueUtil.randomString(); final AreaOfInterestRequest request1 = new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, filter ); pauseScheduler(); request1.markAsInProgress(); connection.injectCurrentAreaOfInterestRequest( request1 ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); connector.progressAreaOfInterestRequestProcessing(); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); handler.assertEventCount( 0 ); } @SuppressWarnings( "unchecked" ) @Test public void progressAreaOfInterestRequestProcessing_Add() { final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), false, ChannelSchema.FilterType.STATIC, null, false, true ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[]{} ); final TestConnector connector = TestConnector.create( schema ); final Connection connection = newConnection( connector ); final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 ); final String filter = ValueUtil.randomString(); final AreaOfInterestRequest request1 = new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.ADD, filter ); pauseScheduler(); connection.injectCurrentAreaOfInterestRequest( request1 ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); connector.progressAreaOfInterestRequestProcessing(); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); handler.assertEventCount( 1 ); handler.assertNextEvent( SubscribeStartedEvent.class, e -> assertEquals( e.getAddress(), address1 ) ); } @SuppressWarnings( "unchecked" ) @Test public void progressAreaOfInterestRequestProcessing_Update() { final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), false, ChannelSchema.FilterType.DYNAMIC, mock( SubscriptionUpdateEntityFilter.class ), false, true ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[]{} ); final TestConnector connector = TestConnector.create( schema ); final Connection connection = newConnection( connector ); final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 ); final String filter = ValueUtil.randomString(); final AreaOfInterestRequest request1 = new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.UPDATE, filter ); pauseScheduler(); createSubscription( address1, null, true ); connection.injectCurrentAreaOfInterestRequest( request1 ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); connector.progressAreaOfInterestRequestProcessing(); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); handler.assertEventCount( 1 ); handler.assertNextEvent( SubscriptionUpdateStartedEvent.class, e -> assertEquals( e.getAddress(), address1 ) ); } @SuppressWarnings( "unchecked" ) @Test public void progressAreaOfInterestRequestProcessing_Remove() { final ChannelSchema channelSchema = new ChannelSchema( 0, ValueUtil.randomString(), false, ChannelSchema.FilterType.NONE, null, false, true ); final SystemSchema schema = new SystemSchema( 1, ValueUtil.randomString(), new ChannelSchema[]{ channelSchema }, new EntitySchema[]{} ); final TestConnector connector = TestConnector.create( schema ); final Connection connection = newConnection( connector ); final ChannelAddress address1 = new ChannelAddress( 1, 0, 1 ); final AreaOfInterestRequest request1 = new AreaOfInterestRequest( address1, AreaOfInterestRequest.Type.REMOVE, null ); pauseScheduler(); createSubscription( address1, null, true ); connection.injectCurrentAreaOfInterestRequest( request1 ); final TestSpyEventHandler handler = registerTestSpyEventHandler(); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); connector.progressAreaOfInterestRequestProcessing(); assertEquals( connection.getCurrentAreaOfInterestRequests().isEmpty(), false ); handler.assertEventCount( 1 ); handler.assertNextEvent( UnsubscribeStartedEvent.class, e -> assertEquals( e.getAddress(), address1 ) ); } @Test public void pauseMessageScheduler() { final TestConnector connector = TestConnector.create(); newConnection( connector ); connector.pauseMessageScheduler(); assertEquals( connector.isSchedulerPaused(), true ); assertEquals( connector.isSchedulerActive(), false ); connector.requestSubscribe( new ChannelAddress( 1, 0, 1 ), null ); assertEquals( connector.isSchedulerActive(), true ); connector.resumeMessageScheduler(); assertEquals( connector.isSchedulerPaused(), false ); assertEquals( connector.isSchedulerActive(), false ); connector.pauseMessageScheduler(); assertEquals( connector.isSchedulerPaused(), true ); assertEquals( connector.isSchedulerActive(), false ); // No progress assertEquals( connector.progressMessages(), false ); Disposable.dispose( connector ); assertEquals( connector.isSchedulerActive(), false ); assertEquals( connector.isSchedulerPaused(), true ); assertNull( connector.getSchedulerLock() ); } }
package replicant; import arez.Arez; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.testng.annotations.Test; import static org.testng.Assert.*; public class ConvergerTest extends AbstractReplicantTest { @Test public void construct_withUnnecessaryContext() { final ReplicantContext context = Replicant.context(); final IllegalStateException exception = expectThrows( IllegalStateException.class, () -> Converger.create( context ) ); assertEquals( exception.getMessage(), "Replicant-0124: SubscriptioConvergernService passed a context but Replicant.areZonesEnabled() is false" ); } @Test public void getReplicantContext() { final ReplicantContext context = Replicant.context(); final Converger converger = context.getConverger(); assertEquals( converger.getReplicantContext(), context ); assertEquals( getFieldValue( converger, "_context" ), null ); } @Test public void getReplicantContext_zonesEnabled() { ReplicantTestUtil.enableZones(); ReplicantTestUtil.resetState(); final ReplicantContext context = Replicant.context(); final Converger converger = context.getConverger(); assertEquals( converger.getReplicantContext(), context ); assertEquals( getFieldValue( converger, "_context" ), context ); } @Test public void preConvergeAction() { final Converger c = Replicant.context().getConverger(); // Pause scheduler so Autoruns don't auto-converge Arez.context().pauseScheduler(); // should do nothing ... Arez.context().safeAction( c::preConverge ); final AtomicInteger callCount = new AtomicInteger(); Arez.context().safeAction( () -> c.setPreConvergeAction( callCount::incrementAndGet ) ); Arez.context().safeAction( c::preConverge ); assertEquals( callCount.get(), 1 ); Arez.context().safeAction( c::preConverge ); assertEquals( callCount.get(), 2 ); Arez.context().safeAction( () -> c.setPreConvergeAction( null ) ); Arez.context().safeAction( c::preConverge ); assertEquals( callCount.get(), 2 ); } @Test public void convergeCompleteAction() { final Converger c = Replicant.context().getConverger(); // Pause scheduler so Autoruns don't auto-converge Arez.context().pauseScheduler(); // should do nothing ... Arez.context().safeAction( c::convergeComplete ); final AtomicInteger callCount = new AtomicInteger(); Arez.context().safeAction( () -> c.setConvergeCompleteAction( callCount::incrementAndGet ) ); Arez.context().safeAction( c::convergeComplete ); assertEquals( callCount.get(), 1 ); Arez.context().safeAction( c::convergeComplete ); assertEquals( callCount.get(), 2 ); Arez.context().safeAction( () -> c.setConvergeCompleteAction( null ) ); Arez.context().safeAction( c::convergeComplete ); assertEquals( callCount.get(), 2 ); } @Nonnull private AreaOfInterest createAreaOfInterest( @Nonnull final ChannelAddress address, @Nullable final Object filter ) { return Replicant.context().createOrUpdateAreaOfInterest( address, filter ); } private enum G { G1, G2 } }
package de.uka.ipd.sdq.beagle.core.evaluableexpressions; /** * Thrown if a {@link EvaluableExpression} is to be evaluated, but insufficient variable * assignments are provided. * * @author Joshua Gleitze * @see EvaluableExpression */ public class UndefinedExpressionException extends RuntimeException { /** * Serialisation version UID, see {@link java.io.Serializable}. */ private static final long serialVersionUID = -80875322029735423L; /** * The variable missing in the assignment. */ private EvaluableVariable undefinedVariable; /** * The assignment raising the exception. */ private EvaluableVariableAssignment assignment; /** * Creates an exception for an encountered undefined variable. Describes the situation * that an {@link EvaluableExpression} containing {@code undefinedVariable} was tried * to be {@link EvaluableExpression#evaluate}d, but the passed {@code assignment} did * not contain a valid assignment for {@code undefinedVariable}. * * @param assignment The assignment raising the exception. * @param undefinedVariable The variable missing in {@code assignment}. */ public UndefinedExpressionException(final EvaluableVariableAssignment assignment, final EvaluableVariable undefinedVariable) { this.assignment = assignment; this.undefinedVariable = undefinedVariable; } /** * The assignment that caused this exception by not assigning a value to * {@link #getMissingVariable()}. * * @return the causing assignment. */ public EvaluableVariableAssignment getCausingAssignment() { return this.assignment; } /** * The variable having no assignment in {@link #getCausingAssignment()} while being * needed. * * @return the missing variable. */ public EvaluableVariable getMissingVariable() { return this.undefinedVariable; } }
package au.gov.ga.geodesy.domain.service; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Objects; import javax.annotation.PostConstruct; import org.apache.commons.collections.ComparatorUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.Collections2; import com.google.common.collect.Lists; import au.gov.ga.geodesy.domain.model.CorsSite; import au.gov.ga.geodesy.domain.model.CorsSiteRepository; import au.gov.ga.geodesy.domain.model.EquipmentInUse; import au.gov.ga.geodesy.domain.model.Node; import au.gov.ga.geodesy.domain.model.NodeRepository; import au.gov.ga.geodesy.domain.model.Setup; import au.gov.ga.geodesy.domain.model.SetupRepository; import au.gov.ga.geodesy.domain.model.equipment.Clock; import au.gov.ga.geodesy.domain.model.equipment.Equipment; import au.gov.ga.geodesy.domain.model.equipment.EquipmentRepository; import au.gov.ga.geodesy.domain.model.equipment.GnssAntenna; import au.gov.ga.geodesy.domain.model.equipment.GnssReceiver; import au.gov.ga.geodesy.domain.model.event.Event; import au.gov.ga.geodesy.domain.model.event.EventPublisher; import au.gov.ga.geodesy.domain.model.event.EventRepository; import au.gov.ga.geodesy.domain.model.event.EventSubscriber; import au.gov.ga.geodesy.domain.model.event.SiteUpdated; import au.gov.ga.geodesy.domain.model.sitelog.EffectiveDates; @Component @Transactional("geodesyTransactionManager") public class NodeService implements EventSubscriber<SiteUpdated> { private static final Logger log = LoggerFactory.getLogger(NodeService.class); private final List<Class<? extends Equipment>> significantEquipment = new ArrayList<>(Arrays.asList( GnssReceiver.class, GnssAntenna.class, Clock.class)); @Autowired private EventPublisher eventPublisher; @Autowired private CorsSiteRepository gnssCorsSites; @Autowired private NodeRepository nodes; @Autowired private EquipmentRepository equipment; @Autowired private SetupRepository setups; @PostConstruct private void subcribe() { eventPublisher.subscribe(this); } public boolean canHandle(Event e) { return e instanceof SiteUpdated; } public void handle(SiteUpdated siteUpdated) { log.info("Notified of " + siteUpdated); String fourCharId = siteUpdated.getFourCharacterId(); CorsSite site = gnssCorsSites.findByFourCharacterId(fourCharId); EffectiveDates nodePeriod = null; setups.findInvalidatedBySiteId(site.getId()) .stream() .map(s -> nodes.findBySetupId(s.getId())) .filter(Objects::nonNull) .forEach(n -> { n.invalidate(); nodes.save(n); log.info("Invalidated node " + n.getId()); }); for (final Setup setup : setups.findBySiteId(site.getId())) { if (nodePeriod != null) { Instant nodeEffectiveTo = nodePeriod.getTo(); if (nodeEffectiveTo == null) { break; } if (nodeEffectiveTo.compareTo(setup.getEffectivePeriod().getFrom()) == 1) { continue; } } if (isCompleteCorsSetup(setup)) { List<EffectiveDates> dates = new ArrayList<>(); for (Class<? extends Equipment> equipmentType : significantEquipment) { EquipmentInUse inUse = getOneEquipmentInUse(setup, equipmentType); if (inUse != null) { dates.add(inUse.getPeriod()); } } nodePeriod = lcd(dates); if (nodes.findBySetupId(setup.getId()) == null) { nodes.save(new Node(site.getId(), nodePeriod, setup.getId())); } } } eventPublisher.handled(siteUpdated); log.info("Saving nodes: " + fourCharId); } private Boolean isCompleteCorsSetup(Setup setup) { return hasReceiver(setup) && hasAntenna(setup); } private Boolean hasReceiver(Setup setup) { return getOneEquipmentInUse(setup, GnssReceiver.class) != null; } private Boolean hasAntenna(Setup setup) { return getOneEquipmentInUse(setup, GnssAntenna.class) != null; } @SuppressWarnings("unchecked") private EffectiveDates lcd(List<EffectiveDates> es) { return new EffectiveDates( Collections.max(Lists.transform(es, new Function<EffectiveDates, Instant>() { public Instant apply(EffectiveDates dates) { return dates == null ? null : dates.getFrom(); } }), ComparatorUtils.nullLowComparator(ComparatorUtils.NATURAL_COMPARATOR)) , Collections.min(Lists.transform(es, new Function<EffectiveDates, Instant>() { public Instant apply(EffectiveDates dates) { return dates == null ? null : dates.getTo(); } }), ComparatorUtils.nullHighComparator(ComparatorUtils.NATURAL_COMPARATOR))); } private <T extends Equipment> EquipmentInUse getOneEquipmentInUse(Setup setup, Class<T> equipmentClass) { Collection<EquipmentInUse> inUse = getEquipmentInUse(setup, equipmentClass); if (inUse.isEmpty()) { return null; } else if (inUse.size() == 1) { return inUse.iterator().next(); } else { System.out.println("Multiple " + equipmentClass.getSimpleName() + " in use!"); return inUse.iterator().next(); } } private <T extends Equipment> Collection<EquipmentInUse> getEquipmentInUse(Setup setup, final Class<T> equipmentClass) { return Collections2.filter(setup.getEquipmentInUse(), new Predicate<EquipmentInUse>() { public boolean apply(EquipmentInUse equipmentInUse) { Equipment e = equipment.findOne(equipmentInUse.getEquipmentId()); return equipmentClass.isAssignableFrom(e.getClass()); } }); } }
package reb2sac; import java.io.*; import java.awt.*; import java.awt.event.*; import java.util.*; import java.util.prefs.Preferences; import javax.swing.*; import parser.*; import lhpn2sbml.gui.LHPNEditor; import lhpn2sbml.parser.Abstraction; import lhpn2sbml.parser.LhpnFile; import lhpn2sbml.parser.Translator; import biomodelsim.*; import gcm2sbml.gui.GCM2SBMLEditor; import gcm2sbml.parser.GCMFile; import graph.*; import buttons.*; import sbmleditor.*; import stategraph.BuildStateGraphThread; import stategraph.PerfromMarkovAnalysisThread; import stategraph.StateGraph; import verification.AbstPane; /** * This class creates the properties file that is given to the reb2sac program. * It also executes the reb2sac program. * * @author Curtis Madsen */ public class Run implements ActionListener { private Process reb2sac; private String separator; private Reb2Sac r2s; StateGraph sg; public Run(Reb2Sac reb2sac) { r2s = reb2sac; if (File.separator.equals("\\")) { separator = "\\\\"; } else { separator = File.separator; } } /** * This method is given which buttons are selected and creates the * properties file from all the other information given. * * @param useInterval * * @param stem */ public void createProperties(double timeLimit, String useInterval, double printInterval, double minTimeStep, double timeStep, double absError, String outDir, long rndSeed, int run, String[] termCond, String[] intSpecies, String printer_id, String printer_track_quantity, String[] getFilename, String selectedButtons, Component component, String filename, double rap1, double rap2, double qss, int con, JCheckBox usingSSA, String ssaFile, JCheckBox usingSad, File sadFile, JList preAbs, JList loopAbs, JList postAbs, AbstPane abstPane) { Properties abs = new Properties(); if (selectedButtons.contains("abs") || selectedButtons.contains("nary")) { for (int i = 0; i < preAbs.getModel().getSize(); i++) { abs.setProperty("reb2sac.abstraction.method.1." + (i + 1), (String) preAbs .getModel().getElementAt(i)); } for (int i = 0; i < loopAbs.getModel().getSize(); i++) { abs.setProperty("reb2sac.abstraction.method.2." + (i + 1), (String) loopAbs .getModel().getElementAt(i)); } // abs.setProperty("reb2sac.abstraction.method.0.1", // "enzyme-kinetic-qssa-1"); // abs.setProperty("reb2sac.abstraction.method.0.2", // "reversible-to-irreversible-transformer"); // abs.setProperty("reb2sac.abstraction.method.0.3", // "multiple-products-reaction-eliminator"); // abs.setProperty("reb2sac.abstraction.method.0.4", // "multiple-reactants-reaction-eliminator"); // abs.setProperty("reb2sac.abstraction.method.0.5", // "single-reactant-product-reaction-eliminator"); // abs.setProperty("reb2sac.abstraction.method.0.6", // "dimer-to-monomer-substitutor"); // abs.setProperty("reb2sac.abstraction.method.0.7", // "inducer-structure-transformer"); // abs.setProperty("reb2sac.abstraction.method.1.1", // "modifier-structure-transformer"); // abs.setProperty("reb2sac.abstraction.method.1.2", // "modifier-constant-propagation"); // abs.setProperty("reb2sac.abstraction.method.2.1", // "operator-site-forward-binding-remover"); // abs.setProperty("reb2sac.abstraction.method.2.3", // "enzyme-kinetic-rapid-equilibrium-1"); // abs.setProperty("reb2sac.abstraction.method.2.4", // "irrelevant-species-remover"); // abs.setProperty("reb2sac.abstraction.method.2.5", // "inducer-structure-transformer"); // abs.setProperty("reb2sac.abstraction.method.2.6", // "modifier-constant-propagation"); // abs.setProperty("reb2sac.abstraction.method.2.7", // "similar-reaction-combiner"); // abs.setProperty("reb2sac.abstraction.method.2.8", // "modifier-constant-propagation"); } // if (selectedButtons.contains("abs")) { // abs.setProperty("reb2sac.abstraction.method.2.2", // "dimerization-reduction"); // else if (selectedButtons.contains("nary")) { // abs.setProperty("reb2sac.abstraction.method.2.2", // "dimerization-reduction-level-assignment"); for (int i = 0; i < postAbs.getModel().getSize(); i++) { abs.setProperty("reb2sac.abstraction.method.3." + (i + 1), (String) postAbs.getModel() .getElementAt(i)); } abs.setProperty("simulation.printer", printer_id); abs.setProperty("simulation.printer.tracking.quantity", printer_track_quantity); // if (selectedButtons.contains("monteCarlo")) { // abs.setProperty("reb2sac.abstraction.method.3.1", // "distribute-transformer"); // abs.setProperty("reb2sac.abstraction.method.3.2", // "reversible-to-irreversible-transformer"); // abs.setProperty("reb2sac.abstraction.method.3.3", // "kinetic-law-constants-simplifier"); // else if (selectedButtons.contains("none")) { // abs.setProperty("reb2sac.abstraction.method.3.1", // "kinetic-law-constants-simplifier"); for (int i = 0; i < intSpecies.length; i++) { if (!intSpecies[i].equals("")) { String[] split = intSpecies[i].split(" "); abs.setProperty("reb2sac.interesting.species." + (i + 1), split[0]); if (split.length > 1) { String[] levels = split[1].split(","); for (int j = 0; j < levels.length; j++) { abs.setProperty("reb2sac.concentration.level." + split[0] + "." + (j + 1), levels[j]); } } } } abs.setProperty("reb2sac.rapid.equilibrium.condition.1", "" + rap1); abs.setProperty("reb2sac.rapid.equilibrium.condition.2", "" + rap2); abs.setProperty("reb2sac.qssa.condition.1", "" + qss); abs.setProperty("reb2sac.operator.max.concentration.threshold", "" + con); if (selectedButtons.contains("none")) { abs.setProperty("reb2sac.abstraction.method", "none"); } if (selectedButtons.contains("abs")) { abs.setProperty("reb2sac.abstraction.method", "abs"); } else if (selectedButtons.contains("nary")) { abs.setProperty("reb2sac.abstraction.method", "nary"); } if (abstPane != null) { String intVars = ""; for (int i = 0; i < abstPane.listModel.getSize(); i++) { if (abstPane.listModel.getElementAt(i) != null) { intVars = intVars + abstPane.listModel.getElementAt(i) + " "; } } if (!intVars.equals("")) { abs.setProperty("abstraction.interesting", intVars.trim()); } else { abs.remove("abstraction.interesting"); } String xforms = ""; for (int i = 0; i < abstPane.absListModel.getSize(); i++) { if (abstPane.absListModel.getElementAt(i) != null) { xforms = xforms + abstPane.absListModel.getElementAt(i) + ", "; } } if (!xforms.equals("")) { abs.setProperty("abstraction.transforms", xforms.trim()); } else { abs.remove("abstraction.transforms"); } if (!abstPane.factorField.getText().equals("")) { abs.setProperty("abstraction.factor", abstPane.factorField.getText()); } if (!abstPane.iterField.getText().equals("")) { abs.setProperty("abstraction.iterations", abstPane.iterField.getText()); } } if (selectedButtons.contains("ODE")) { abs.setProperty("reb2sac.simulation.method", "ODE"); } else if (selectedButtons.contains("monteCarlo")) { abs.setProperty("reb2sac.simulation.method", "monteCarlo"); } else if (selectedButtons.contains("markov")) { abs.setProperty("reb2sac.simulation.method", "markov"); } else if (selectedButtons.contains("sbml")) { abs.setProperty("reb2sac.simulation.method", "SBML"); } else if (selectedButtons.contains("dot")) { abs.setProperty("reb2sac.simulation.method", "Network"); } else if (selectedButtons.contains("xhtml")) { abs.setProperty("reb2sac.simulation.method", "Browser"); } else if (selectedButtons.contains("lhpn")) { abs.setProperty("reb2sac.simulation.method", "LPN"); } if (!selectedButtons.contains("monteCarlo")) { // if (selectedButtons.equals("none_ODE") || // selectedButtons.equals("abs_ODE")) { abs.setProperty("ode.simulation.time.limit", "" + timeLimit); if (useInterval.equals("Print Interval")) { abs.setProperty("ode.simulation.print.interval", "" + printInterval); } else if (useInterval.equals("Minimum Print Interval")) { abs.setProperty("ode.simulation.minimum.print.interval", "" + printInterval); } else { abs.setProperty("ode.simulation.number.steps", "" + ((int) printInterval)); } if (timeStep == Double.MAX_VALUE) { abs.setProperty("ode.simulation.time.step", "inf"); } else { abs.setProperty("ode.simulation.time.step", "" + timeStep); } abs.setProperty("ode.simulation.min.time.step", "" + minTimeStep); abs.setProperty("ode.simulation.absolute.error", "" + absError); abs.setProperty("ode.simulation.out.dir", outDir); abs.setProperty("monte.carlo.simulation.random.seed", "" + rndSeed); abs.setProperty("monte.carlo.simulation.runs", "" + run); } if (!selectedButtons.contains("ODE")) { // if (selectedButtons.equals("none_monteCarlo") || // selectedButtons.equals("abs_monteCarlo")) { abs.setProperty("monte.carlo.simulation.time.limit", "" + timeLimit); if (useInterval.equals("Print Interval")) { abs.setProperty("monte.carlo.simulation.print.interval", "" + printInterval); } else if (useInterval.equals("Minimum Print Interval")) { abs .setProperty("monte.carlo.simulation.minimum.print.interval", "" + printInterval); } else { abs.setProperty("monte.carlo.simulation.number.steps", "" + ((int) printInterval)); } if (timeStep == Double.MAX_VALUE) { abs.setProperty("monte.carlo.simulation.time.step", "inf"); } else { abs.setProperty("monte.carlo.simulation.time.step", "" + timeStep); } abs.setProperty("monte.carlo.simulation.min.time.step", "" + minTimeStep); abs.setProperty("monte.carlo.simulation.random.seed", "" + rndSeed); abs.setProperty("monte.carlo.simulation.runs", "" + run); abs.setProperty("monte.carlo.simulation.out.dir", outDir); if (usingSad.isSelected()) { abs.setProperty("simulation.run.termination.decider", "sad"); abs.setProperty("computation.analysis.sad.path", sadFile.getName()); } } if (!usingSad.isSelected()) { abs.setProperty("simulation.run.termination.decider", "constraint"); } if (usingSSA.isSelected() && selectedButtons.contains("monteCarlo")) { abs.setProperty("simulation.time.series.species.level.file", ssaFile); } for (int i = 0; i < termCond.length; i++) { if (termCond[i] != "") { abs .setProperty("simulation.run.termination.condition." + (i + 1), "" + termCond[i]); } } try { if (!getFilename[getFilename.length - 1].contains(".")) { getFilename[getFilename.length - 1] += "."; filename += "."; } int cut = 0; for (int i = 0; i < getFilename[getFilename.length - 1].length(); i++) { if (getFilename[getFilename.length - 1].charAt(i) == '.') { cut = i; } } FileOutputStream store = new FileOutputStream(new File((filename.substring(0, filename .length() - getFilename[getFilename.length - 1].length())) + getFilename[getFilename.length - 1].substring(0, cut) + ".properties")); abs.store(store, getFilename[getFilename.length - 1].substring(0, cut) + " Properties"); store.close(); } catch (Exception except) { JOptionPane.showMessageDialog(component, "Unable To Save Properties File!" + "\nMake sure you select a model for abstraction.", "Unable To Save File", JOptionPane.ERROR_MESSAGE); } } /** * This method is given what data is entered into the nary frame and creates * the nary properties file from that information. */ public void createNaryProperties(double timeLimit, String useInterval, double printInterval, double minTimeStep, double timeStep, String outDir, long rndSeed, int run, String printer_id, String printer_track_quantity, String[] getFilename, Component component, String filename, JRadioButton monteCarlo, String stopE, double stopR, String[] finalS, ArrayList<JTextField> inhib, ArrayList<JList> consLevel, ArrayList<String> getSpeciesProps, ArrayList<Object[]> conLevel, String[] termCond, String[] intSpecies, double rap1, double rap2, double qss, int con, ArrayList<Integer> counts, JCheckBox usingSSA, String ssaFile) { Properties nary = new Properties(); try { FileInputStream load = new FileInputStream(new File(outDir + separator + "species.properties")); nary.load(load); load.close(); } catch (Exception e) { JOptionPane.showMessageDialog(component, "Species Properties File Not Found!", "File Not Found", JOptionPane.ERROR_MESSAGE); } nary.setProperty("reb2sac.abstraction.method.0.1", "enzyme-kinetic-qssa-1"); nary .setProperty("reb2sac.abstraction.method.0.2", "reversible-to-irreversible-transformer"); nary.setProperty("reb2sac.abstraction.method.0.3", "multiple-products-reaction-eliminator"); nary .setProperty("reb2sac.abstraction.method.0.4", "multiple-reactants-reaction-eliminator"); nary.setProperty("reb2sac.abstraction.method.0.5", "single-reactant-product-reaction-eliminator"); nary.setProperty("reb2sac.abstraction.method.0.6", "dimer-to-monomer-substitutor"); nary.setProperty("reb2sac.abstraction.method.0.7", "inducer-structure-transformer"); nary.setProperty("reb2sac.abstraction.method.1.1", "modifier-structure-transformer"); nary.setProperty("reb2sac.abstraction.method.1.2", "modifier-constant-propagation"); nary.setProperty("reb2sac.abstraction.method.2.1", "operator-site-forward-binding-remover"); nary.setProperty("reb2sac.abstraction.method.2.3", "enzyme-kinetic-rapid-equilibrium-1"); nary.setProperty("reb2sac.abstraction.method.2.4", "irrelevant-species-remover"); nary.setProperty("reb2sac.abstraction.method.2.5", "inducer-structure-transformer"); nary.setProperty("reb2sac.abstraction.method.2.6", "modifier-constant-propagation"); nary.setProperty("reb2sac.abstraction.method.2.7", "similar-reaction-combiner"); nary.setProperty("reb2sac.abstraction.method.2.8", "modifier-constant-propagation"); nary.setProperty("reb2sac.abstraction.method.2.2", "dimerization-reduction"); nary.setProperty("reb2sac.abstraction.method.3.1", "nary-order-unary-transformer"); nary.setProperty("reb2sac.abstraction.method.3.2", "modifier-constant-propagation"); nary.setProperty("reb2sac.abstraction.method.3.3", "absolute-inhibition-generator"); nary.setProperty("reb2sac.abstraction.method.3.4", "final-state-generator"); nary.setProperty("reb2sac.abstraction.method.3.5", "stop-flag-generator"); nary.setProperty("reb2sac.nary.order.decider", "distinct"); nary.setProperty("simulation.printer", printer_id); nary.setProperty("simulation.printer.tracking.quantity", printer_track_quantity); nary.setProperty("reb2sac.analysis.stop.enabled", stopE); nary.setProperty("reb2sac.analysis.stop.rate", "" + stopR); for (int i = 0; i < getSpeciesProps.size(); i++) { if (!(inhib.get(i).getText().trim() != "<<none>>")) { nary.setProperty("reb2sac.absolute.inhibition.threshold." + getSpeciesProps.get(i), inhib.get(i).getText().trim()); } String[] consLevels = Buttons.getList(conLevel.get(i), consLevel.get(i)); for (int j = 0; j < counts.get(i); j++) { nary .remove("reb2sac.concentration.level." + getSpeciesProps.get(i) + "." + (j + 1)); } for (int j = 0; j < consLevels.length; j++) { nary.setProperty("reb2sac.concentration.level." + getSpeciesProps.get(i) + "." + (j + 1), consLevels[j]); } } if (monteCarlo.isSelected()) { nary.setProperty("monte.carlo.simulation.time.limit", "" + timeLimit); if (useInterval.equals("Print Interval")) { nary.setProperty("monte.carlo.simulation.print.interval", "" + printInterval); } else if (useInterval.equals("Minimum Print Interval")) { nary.setProperty("monte.carlo.simulation.minimum.print.interval", "" + printInterval); } else { nary.setProperty("monte.carlo.simulation.number.steps", "" + ((int) printInterval)); } if (timeStep == Double.MAX_VALUE) { nary.setProperty("monte.carlo.simulation.time.step", "inf"); } else { nary.setProperty("monte.carlo.simulation.time.step", "" + timeStep); } nary.setProperty("monte.carlo.simulation.min.time.step", "" + minTimeStep); nary.setProperty("monte.carlo.simulation.random.seed", "" + rndSeed); nary.setProperty("monte.carlo.simulation.runs", "" + run); nary.setProperty("monte.carlo.simulation.out.dir", "."); } for (int i = 0; i < finalS.length; i++) { if (finalS[i].trim() != "<<unknown>>") { nary.setProperty("reb2sac.final.state." + (i + 1), "" + finalS[i]); } } if (usingSSA.isSelected() && monteCarlo.isSelected()) { nary.setProperty("simulation.time.series.species.level.file", ssaFile); } for (int i = 0; i < intSpecies.length; i++) { if (intSpecies[i] != "") { nary.setProperty("reb2sac.interesting.species." + (i + 1), "" + intSpecies[i]); } } nary.setProperty("reb2sac.rapid.equilibrium.condition.1", "" + rap1); nary.setProperty("reb2sac.rapid.equilibrium.condition.2", "" + rap2); nary.setProperty("reb2sac.qssa.condition.1", "" + qss); nary.setProperty("reb2sac.operator.max.concentration.threshold", "" + con); for (int i = 0; i < termCond.length; i++) { if (termCond[i] != "") { nary.setProperty("simulation.run.termination.condition." + (i + 1), "" + termCond[i]); } } try { FileOutputStream store = new FileOutputStream(new File((filename.substring(0, filename .length() - getFilename[getFilename.length - 1].length())) + getFilename[getFilename.length - 1].substring(0, getFilename[getFilename.length - 1].length() - 5) + ".properties")); nary.store(store, getFilename[getFilename.length - 1].substring(0, getFilename[getFilename.length - 1].length() - 5) + " Properties"); store.close(); } catch (Exception except) { JOptionPane.showMessageDialog(component, "Unable To Save Properties File!" + "\nMake sure you select a model for simulation.", "Unable To Save File", JOptionPane.ERROR_MESSAGE); } } /** * Executes the reb2sac program. If ODE, monte carlo, or markov is selected, * this method creates a Graph object. * * @param runTime */ public int execute(String filename, JRadioButton sbml, JRadioButton dot, JRadioButton xhtml, JRadioButton lhpn, Component component, JRadioButton ode, JRadioButton monteCarlo, String sim, String printer_id, String printer_track_quantity, String outDir, JRadioButton nary, int naryRun, String[] intSpecies, Log log, JCheckBox usingSSA, String ssaFile, BioSim biomodelsim, JTabbedPane simTab, String root, JProgressBar progress, String simName, GCM2SBMLEditor gcmEditor, String direct, double timeLimit, double runTime, String modelFile, AbstPane abstPane, JRadioButton abstraction, String lpnProperty) { Runtime exec = Runtime.getRuntime(); int exitValue = 255; while (outDir.split(separator)[outDir.split(separator).length - 1].equals(".")) { outDir = outDir.substring(0, outDir.length() - 1 - outDir.split(separator)[outDir.split(separator).length - 1].length()); } try { long time1; String directory = ""; String theFile = ""; String sbmlName = ""; String lhpnName = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); String out = theFile; if (out.length() > 4 && out.substring(out.length() - 5, out.length()).equals(".sbml")) { out = out.substring(0, out.length() - 5); } else if (out.length() > 3 && out.substring(out.length() - 4, out.length()).equals(".xml")) { out = out.substring(0, out.length() - 4); } if (nary.isSelected() && gcmEditor != null && (monteCarlo.isSelected() || xhtml.isSelected())) { String lpnName = modelFile.replace(".sbml", "").replace(".gcm", "").replace(".xml", "") + ".lpn"; ArrayList<String> specs = new ArrayList<String>(); ArrayList<Object[]> conLevel = new ArrayList<Object[]>(); for (int i = 0; i < intSpecies.length; i++) { if (!intSpecies[i].equals("")) { String[] split = intSpecies[i].split(" "); if (split.length > 1) { String[] levels = split[1].split(","); if (levels.length > 0) { specs.add(split[0]); conLevel.add(levels); } } } } GCMFile gcm = gcmEditor.getGCM(); if (gcm.flattenGCM(false) != null) { LhpnFile lpnFile = gcm.convertToLHPN(specs, conLevel); lpnFile.save(root + separator + simName + separator + lpnName); time1 = System.nanoTime(); Translator t1 = new Translator(); if (abstraction.isSelected()) { LhpnFile lhpnFile = new LhpnFile(); lhpnFile.load(root + separator + simName + separator + lpnName); Abstraction abst = new Abstraction(lhpnFile, abstPane); abst.abstractSTG(false); abst.save(root + separator + simName + separator + lpnName + ".temp"); t1.BuildTemplate( root + separator + simName + separator + lpnName + ".temp", lpnProperty); } else { t1.BuildTemplate(root + separator + simName + separator + lpnName, lpnProperty); } t1.setFilename(root + separator + simName + separator + lpnName.replace(".lpn", ".sbml")); t1.outputSBML(); } else { return 0; } } if (nary.isSelected() && gcmEditor == null && !sim.equals("markov-chain-analysis") && !lhpn.isSelected() && naryRun == 1) { log.addText("Executing:\nreb2sac --target.encoding=nary-level " + filename + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec("reb2sac --target.encoding=nary-level " + theFile, null, work); } else if (sbml.isSelected()) { sbmlName = JOptionPane.showInputDialog(component, "Enter SBML Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (sbmlName != null && !sbmlName.trim().equals("")) { sbmlName = sbmlName.trim(); if (sbmlName.length() > 4) { if (!sbmlName.substring(sbmlName.length() - 3).equals(".xml") || !sbmlName.substring(sbmlName.length() - 4).equals(".sbml")) { sbmlName += ".xml"; } } else { sbmlName += ".xml"; } File f = new File(root + separator + sbmlName); if (f.exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(component, "File already exists." + "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { File dir = new File(root + separator + sbmlName); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { System.gc(); dir.delete(); } } else { return 0; } } if (modelFile.contains(".lpn")) { progress.setIndeterminate(true); time1 = System.nanoTime(); Translator t1 = new Translator(); if (abstraction.isSelected()) { LhpnFile lhpnFile = new LhpnFile(); lhpnFile.load(root + separator + modelFile); Abstraction abst = new Abstraction(lhpnFile, abstPane); abst.abstractSTG(false); abst.save(root + separator + simName + separator + modelFile); t1.BuildTemplate(root + separator + simName + separator + modelFile, lpnProperty); } else { t1.BuildTemplate(root + separator + modelFile, lpnProperty); } t1.setFilename(root + separator + sbmlName); t1.outputSBML(); exitValue = 0; } else if (gcmEditor != null && nary.isSelected()) { String lpnName = modelFile.replace(".sbml", "").replace(".gcm", "") .replace(".xml", "") + ".lpn"; ArrayList<String> specs = new ArrayList<String>(); ArrayList<Object[]> conLevel = new ArrayList<Object[]>(); for (int i = 0; i < intSpecies.length; i++) { if (!intSpecies[i].equals("")) { String[] split = intSpecies[i].split(" "); if (split.length > 1) { String[] levels = split[1].split(","); if (levels.length > 0) { specs.add(split[0]); conLevel.add(levels); } } } } progress.setIndeterminate(true); GCMFile gcm = gcmEditor.getGCM(); if (gcm.flattenGCM(false) != null) { LhpnFile lpnFile = gcm.convertToLHPN(specs, conLevel); lpnFile.save(root + separator + simName + separator + lpnName); time1 = System.nanoTime(); Translator t1 = new Translator(); if (abstraction.isSelected()) { LhpnFile lhpnFile = new LhpnFile(); lhpnFile.load(root + separator + simName + separator + lpnName); Abstraction abst = new Abstraction(lhpnFile, abstPane); abst.abstractSTG(false); abst.save(root + separator + simName + separator + lpnName + ".temp"); t1.BuildTemplate(root + separator + simName + separator + lpnName + ".temp", lpnProperty); } else { t1.BuildTemplate(root + separator + simName + separator + lpnName, lpnProperty); } t1.setFilename(root + separator + sbmlName); t1.outputSBML(); } else { time1 = System.nanoTime(); return 0; } exitValue = 0; } else { log.addText("Executing:\nreb2sac --target.encoding=sbml --out=" + ".." + separator + sbmlName + " " + filename + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec("reb2sac --target.encoding=sbml --out=" + ".." + separator + sbmlName + " " + theFile, null, work); } } else { time1 = System.nanoTime(); } } else if (lhpn.isSelected()) { lhpnName = JOptionPane.showInputDialog(component, "Enter LPN Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (lhpnName != null && !lhpnName.trim().equals("")) { lhpnName = lhpnName.trim(); if (lhpnName.length() > 4) { if (!lhpnName.substring(lhpnName.length() - 3).equals(".lpn")) { lhpnName += ".lpn"; } } else { lhpnName += ".lpn"; } File f = new File(root + separator + lhpnName); if (f.exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(component, "File already exists." + "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { File dir = new File(root + separator + lhpnName); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { System.gc(); dir.delete(); } } else { return 0; } } if (modelFile.contains(".lpn")) { LhpnFile lhpnFile = new LhpnFile(); lhpnFile.load(root + separator + modelFile); lhpnFile.save(root + separator + lhpnName); time1 = System.nanoTime(); exitValue = 0; } else { ArrayList<String> specs = new ArrayList<String>(); ArrayList<Object[]> conLevel = new ArrayList<Object[]>(); for (int i = 0; i < intSpecies.length; i++) { if (!intSpecies[i].equals("")) { String[] split = intSpecies[i].split(" "); if (split.length > 1) { String[] levels = split[1].split(","); if (levels.length > 0) { specs.add(split[0]); conLevel.add(levels); } } } } progress.setIndeterminate(true); GCMFile gcm = gcmEditor.getGCM(); if (gcm.flattenGCM(false) != null) { LhpnFile lhpnFile = gcm.convertToLHPN(specs, conLevel); lhpnFile.save(root + separator + lhpnName); log.addText("Saving GCM file as LHPN:\n" + root + separator + lhpnName + "\n"); } else { return 0; } time1 = System.nanoTime(); exitValue = 0; } } else { time1 = System.nanoTime(); exitValue = 0; } } else if (dot.isSelected()) { if (nary.isSelected() && gcmEditor != null) { //String cmd = "atacs -cPllodpl " // + theFile.replace(".sbml", "").replace(".xml", "") + ".lpn"; LhpnFile lhpnFile = new LhpnFile(log); lhpnFile.load(directory + separator + theFile.replace(".sbml", "").replace(".xml", "") + ".lpn"); lhpnFile.printDot(directory + separator + theFile.replace(".sbml", "").replace(".xml", "") + ".dot"); time1 = System.nanoTime(); //Process ATACS = exec.exec(cmd, null, work); //ATACS.waitFor(); //log.addText("Executing:\n" + cmd); exitValue = 0; } else if (modelFile.contains(".lpn")) { LhpnFile lhpnFile = new LhpnFile(); lhpnFile.load(root + separator + modelFile); lhpnFile.save(root + separator + simName + separator + modelFile); lhpnFile.printDot(root + separator + modelFile.replace(".lpn", ".dot")); //String cmd = "atacs -cPllodpl " + modelFile; //time1 = System.nanoTime(); //Process ATACS = exec.exec(cmd, null, work); //ATACS.waitFor(); //log.addText("Executing:\n" + cmd); time1 = System.nanoTime(); exitValue = 0; } else { log.addText("Executing:\nreb2sac --target.encoding=dot --out=" + out + ".dot " + filename + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec("reb2sac --target.encoding=dot --out=" + out + ".dot " + theFile, null, work); } } else if (xhtml.isSelected()) { log.addText("Executing:\nreb2sac --target.encoding=xhtml --out=" + out + ".xhtml " + filename + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec("reb2sac --target.encoding=xhtml --out=" + out + ".xhtml " + theFile, null, work); } else if (usingSSA.isSelected()) { log.addText("Executing:\nreb2sac --target.encoding=ssa-with-user-update " + filename + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec("reb2sac --target.encoding=ssa-with-user-update " + theFile, null, work); } else { if (sim.equals("atacs")) { log.addText("Executing:\nreb2sac --target.encoding=hse2 " + filename + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec("reb2sac --target.encoding=hse2 " + theFile, null, work); } else if (sim.equals("markov-chain-analysis")) { LhpnFile lhpnFile = null; if (modelFile.contains(".lpn")) { lhpnFile = new LhpnFile(); lhpnFile.load(root + separator + modelFile); } else { new File(filename.replace(".gcm", "").replace(".sbml", "").replace(".xml", "") + ".lpn").delete(); ArrayList<String> specs = new ArrayList<String>(); ArrayList<Object[]> conLevel = new ArrayList<Object[]>(); for (int i = 0; i < intSpecies.length; i++) { if (!intSpecies[i].equals("")) { String[] split = intSpecies[i].split(" "); if (split.length > 1) { String[] levels = split[1].split(","); if (levels.length > 0) { specs.add(split[0]); conLevel.add(levels); } } } } progress.setIndeterminate(true); GCMFile gcm = gcmEditor.getGCM(); if (gcm.flattenGCM(false) != null) { lhpnFile = gcm.convertToLHPN(specs, conLevel); lhpnFile.save(filename.replace(".gcm", "").replace(".sbml", "") .replace(".xml", "") + ".lpn"); log.addText("Saving GCM file as LHPN:\n" + filename.replace(".gcm", "").replace(".sbml", "").replace( ".xml", "") + ".lpn" + "\n"); } else { return 0; } } // gcmEditor.getGCM().createLogicalModel( // filename.replace(".gcm", "").replace(".sbml", // "").replace(".xml", "") // + ".lpn", // log, // biomodelsim, // theFile.replace(".gcm", "").replace(".sbml", // "").replace(".xml", "") // + ".lpn"); // LHPNFile lhpnFile = new LHPNFile(); // while (new File(filename.replace(".gcm", // "").replace(".sbml", "").replace( // ".xml", "") // + ".lpn.temp").exists()) { // if (new File(filename.replace(".gcm", // "").replace(".sbml", "").replace(".xml", // + ".lpn").exists()) { // lhpnFile.load(filename.replace(".gcm", // "").replace(".sbml", "").replace( // ".xml", "") // + ".lpn"); if (lhpnFile != null) { sg = new StateGraph(lhpnFile); BuildStateGraphThread buildStateGraph = new BuildStateGraphThread(sg); buildStateGraph.start(); buildStateGraph.join(); if (!sg.getStop()) { log.addText("Performing Markov Chain analysis.\n"); PerfromMarkovAnalysisThread performMarkovAnalysis = new PerfromMarkovAnalysisThread( sg); if (modelFile.contains(".lpn")) { performMarkovAnalysis.start(null); } else { performMarkovAnalysis.start(gcmEditor.getGCM().getConditions()); } performMarkovAnalysis.join(); if (!sg.getStop()) { String simrep = sg.getMarkovResults(); if (simrep != null) { FileOutputStream simrepstream = new FileOutputStream(new File( directory + separator + "sim-rep.txt")); simrepstream.write((simrep).getBytes()); simrepstream.close(); } sg.outputStateGraph(filename.replace(".gcm", "").replace(".sbml", "").replace(".xml", "") + "_sg.dot", true); biomodelsim.enableTabMenu(biomodelsim.getTab().getSelectedIndex()); } } // if (sg.getNumberOfStates() > 30) { // String[] options = { "Yes", "No" }; // int value = JOptionPane // .showOptionDialog( // BioSim.frame, // "The state graph contains more than 30 states and may not open well in dotty.\nOpen it with dotty anyway?", // "More Than 30 States", JOptionPane.YES_NO_OPTION, // JOptionPane.WARNING_MESSAGE, null, options, // options[0]); // if (value == JOptionPane.YES_OPTION) { // (System.getProperty("os.name").contentEquals("Linux")) // log.addText("Executing:\ndotty " // + filename.replace(".gcm", "").replace(".sbml", "") // .replace(".xml", "") + "_sg.dot" + "\n"); // exec.exec("dotty " // + theFile.replace(".gcm", "").replace(".sbml", // "").replace( // ".xml", "") + "_sg.dot", null, work); // else if // (System.getProperty("os.name").toLowerCase().startsWith( // "mac os")) { // log.addText("Executing:\nopen " // + filename.replace(".gcm", "").replace(".sbml", "") // .replace(".xml", "") + "_sg.dot" + "\n"); // exec.exec("open " // + theFile.replace(".gcm", "").replace(".sbml", // "").replace( // ".xml", "") + "_sg.dot", null, work); // else { // log.addText("Executing:\ndotty " // + filename.replace(".gcm", "").replace(".sbml", "") // .replace(".xml", "") + "_sg.dot" + "\n"); // exec.exec("dotty " // + theFile.replace(".gcm", "").replace(".sbml", // "").replace( // ".xml", "") + "_sg.dot", null, work); for (int i = 0; i < simTab.getComponentCount(); i++) { if (simTab.getComponentAt(i).getName().equals("ProbGraph")) { if (simTab.getComponentAt(i) instanceof Graph) { ((Graph) simTab.getComponentAt(i)).refresh(); } else { simTab .setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir .split(separator)[outDir .split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, false, false)); simTab.getComponentAt(i).setName("ProbGraph"); } } } } time1 = System.nanoTime(); exitValue = 0; } else { Preferences biosimrc = Preferences.userRoot(); if (biosimrc.get("biosim.sim.command", "").equals("")) { log.addText("Executing:\nreb2sac --target.encoding=" + sim + " " + filename + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec("reb2sac --target.encoding=" + sim + " " + theFile, null, work); } else { String command = biosimrc.get("biosim.sim.command", ""); String fileStem = theFile.replaceAll(".xml", ""); fileStem = fileStem.replaceAll(".sbml", ""); command = command.replaceAll("filename", fileStem); command = command.replaceAll("sim", sim); log.addText(command + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec(command, null, work); } } } String error = ""; try { InputStream reb = reb2sac.getInputStream(); InputStreamReader isr = new InputStreamReader(reb); BufferedReader br = new BufferedReader(isr); // int count = 0; String line; double time = 0; double oldTime = 0; int runNum = 0; int prog = 0; while ((line = br.readLine()) != null) { try { if (line.contains("Time")) { time = Double.parseDouble(line.substring(line.indexOf('=') + 1, line .length())); if (oldTime > time) { runNum++; } oldTime = time; time += (runNum * timeLimit); double d = ((time * 100) / runTime); String s = d + ""; double decimal = Double.parseDouble(s.substring(s.indexOf('.'), s .length())); if (decimal >= 0.5) { prog = (int) (Math.ceil(d)); } else { prog = (int) (d); } } } catch (Exception e) { } progress.setValue(prog); // if (steps > 0) { // count++; // progress.setValue(count); // log.addText(output); } InputStream reb2 = reb2sac.getErrorStream(); int read = reb2.read(); while (read != -1) { error += (char) read; read = reb2.read(); } br.close(); isr.close(); reb.close(); reb2.close(); } catch (Exception e) { } if (reb2sac != null) { exitValue = reb2sac.waitFor(); long time2 = System.nanoTime(); long minutes; long hours; long days; double secs = ((time2 - time1) / 1000000000.0); long seconds = ((time2 - time1) / 1000000000); secs = secs - seconds; minutes = seconds / 60; secs = seconds % 60 + secs; hours = minutes / 60; minutes = minutes % 60; days = hours / 24; hours = hours % 60; String time; String dayLabel; String hourLabel; String minuteLabel; String secondLabel; if (days == 1) { dayLabel = " day "; } else { dayLabel = " days "; } if (hours == 1) { hourLabel = " hour "; } else { hourLabel = " hours "; } if (minutes == 1) { minuteLabel = " minute "; } else { minuteLabel = " minutes "; } if (seconds == 1) { secondLabel = " second"; } else { secondLabel = " seconds"; } if (days != 0) { time = days + dayLabel + hours + hourLabel + minutes + minuteLabel + secs + secondLabel; } else if (hours != 0) { time = hours + hourLabel + minutes + minuteLabel + secs + secondLabel; } else if (minutes != 0) { time = minutes + minuteLabel + secs + secondLabel; } else { time = secs + secondLabel; } if (!error.equals("")) { log.addText("Errors:\n" + error + "\n"); } log.addText("Total Simulation Time: " + time + " for " + simName + "\n\n"); } if (exitValue != 0) { if (exitValue == 143) { JOptionPane.showMessageDialog(BioSim.frame, "The simulation was" + " canceled by the user.", "Canceled Simulation", JOptionPane.ERROR_MESSAGE); } else if (exitValue == 139) { JOptionPane.showMessageDialog(BioSim.frame, "The selected model is not a valid sbml file." + "\nYou must select an sbml file.", "Not An SBML File", JOptionPane.ERROR_MESSAGE); } else { JOptionPane.showMessageDialog(BioSim.frame, "Error In Execution!\n" + "Bad Return Value!\n" + "The reb2sac program returned " + exitValue + " as an exit value.", "Error", JOptionPane.ERROR_MESSAGE); } } else { if (nary.isSelected() && gcmEditor == null && !lhpn.isSelected() && naryRun == 1) { } else if (sbml.isSelected()) { if (sbmlName != null && !sbmlName.trim().equals("")) { if (!biomodelsim.updateOpenSBML(sbmlName)) { biomodelsim.addTab(sbmlName, new SBML_Editor(root + separator + sbmlName, null, log, biomodelsim, null, null), "SBML Editor"); biomodelsim.addToTree(sbmlName); } else { biomodelsim.getTab().setSelectedIndex(biomodelsim.getTab(sbmlName)); } } } else if (lhpn.isSelected()) { if (lhpnName != null && !lhpnName.trim().equals("")) { if (!biomodelsim.updateOpenLHPN(lhpnName)) { biomodelsim.addTab(lhpnName, new LHPNEditor(root, lhpnName, null, biomodelsim, log), "LHPN Editor"); biomodelsim.addToTree(lhpnName); } else { biomodelsim.getTab().setSelectedIndex(biomodelsim.getTab(lhpnName)); } } } else if (dot.isSelected()) { if (System.getProperty("os.name").contentEquals("Linux")) { log.addText("Executing:\ndotty " + directory + out + ".dot" + "\n"); exec.exec("dotty " + out + ".dot", null, work); } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { log.addText("Executing:\nopen " + directory + out + ".dot\n"); exec.exec("open " + out + ".dot", null, work); } else { log.addText("Executing:\ndotty " + directory + out + ".dot" + "\n"); exec.exec("dotty " + out + ".dot", null, work); } } else if (xhtml.isSelected()) { if (System.getProperty("os.name").contentEquals("Linux")) { log.addText("Executing:\ngnome-open " + directory + out + ".xhtml" + "\n"); exec.exec("gnome-open " + out + ".xhtml", null, work); } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { log.addText("Executing:\nopen " + directory + out + ".xhtml" + "\n"); exec.exec("open " + out + ".xhtml", null, work); } else { log .addText("Executing:\ncmd /c start " + directory + out + ".xhtml" + "\n"); exec.exec("cmd /c start " + out + ".xhtml", null, work); } } else if (usingSSA.isSelected()) { if (!printer_id.equals("null.printer")) { for (int i = 0; i < simTab.getComponentCount(); i++) { if (simTab.getComponentAt(i).getName().equals("TSD Graph")) { if (simTab.getComponentAt(i) instanceof Graph) { boolean outputM = true; boolean outputV = true; boolean outputS = true; boolean warning = false; int num = -1; String run = "run-1." + printer_id.substring(0, printer_id.length() - 8); for (String f : work.list()) { if (f.contains("mean")) { outputM = false; } else if (f.contains("variance")) { outputV = false; } else if (f.contains("standard_deviation")) { outputS = false; } else if (f.contains("run-")) { String getNumber = f.substring(4, f.length()); String number = ""; for (int j = 0; j < getNumber.length(); j++) { if (Character.isDigit(getNumber.charAt(j))) { number += getNumber.charAt(j); } else { break; } } if (num == -1) { num = Integer.parseInt(number); } else if (Integer.parseInt(number) < num) { num = Integer.parseInt(number); } run = "run-" + num + "." + printer_id.substring(0, printer_id.length() - 8); } } if (outputM) { ArrayList<ArrayList<Double>> mean = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "average", direct, warning); warning = ((Graph) simTab.getComponentAt(i)).getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), mean); p2.outputTSD(directory + separator + "mean.tsd"); } if (outputV) { ArrayList<ArrayList<Double>> var = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "variance", direct, warning); warning = ((Graph) simTab.getComponentAt(i)).getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), var); p2.outputTSD(directory + separator + "variance.tsd"); } if (outputS) { ArrayList<ArrayList<Double>> stddev = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "deviation", direct, warning); warning = ((Graph) simTab.getComponentAt(i)).getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), stddev); p2.outputTSD(directory + separator + "standard_deviation.tsd"); } ((Graph) simTab.getComponentAt(i)).refresh(); } else { simTab .setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir .split(separator)[outDir .split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, true, false)); boolean outputM = true; boolean outputV = true; boolean outputS = true; boolean warning = false; int num = -1; String run = "run-1." + printer_id.substring(0, printer_id.length() - 8); for (String f : work.list()) { if (f.contains("mean")) { outputM = false; } else if (f.contains("variance")) { outputV = false; } else if (f.contains("standard_deviation")) { outputS = false; } else if (f.contains("run-")) { String getNumber = f.substring(4, f.length()); String number = ""; for (int j = 0; j < getNumber.length(); j++) { if (Character.isDigit(getNumber.charAt(j))) { number += getNumber.charAt(j); } else { break; } } if (num == -1) { num = Integer.parseInt(number); } else if (Integer.parseInt(number) < num) { num = Integer.parseInt(number); } run = "run-" + num + "." + printer_id.substring(0, printer_id.length() - 8); } } if (outputM) { ArrayList<ArrayList<Double>> mean = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "average", direct, warning); warning = ((Graph) simTab.getComponentAt(i)).getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), mean); p2.outputTSD(directory + separator + "mean.tsd"); } if (outputV) { ArrayList<ArrayList<Double>> var = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "variance", direct, warning); warning = ((Graph) simTab.getComponentAt(i)).getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), var); p2.outputTSD(directory + separator + "variance.tsd"); } if (outputS) { ArrayList<ArrayList<Double>> stddev = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "deviation", direct, warning); warning = ((Graph) simTab.getComponentAt(i)).getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), stddev); p2.outputTSD(directory + separator + "standard_deviation.tsd"); } simTab.getComponentAt(i).setName("TSD Graph"); } } if (simTab.getComponentAt(i).getName().equals("ProbGraph")) { if (simTab.getComponentAt(i) instanceof Graph) { ((Graph) simTab.getComponentAt(i)).refresh(); } else { if (new File(filename.substring(0, filename.length() - filename.split(separator)[filename .split(separator).length - 1].length()) + "sim-rep.txt").exists()) { simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir.split(separator)[outDir .split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, false, false)); simTab.getComponentAt(i).setName("ProbGraph"); } } } } } } else if (sim.equals("atacs")) { log.addText("Executing:\natacs -T0.000001 -oqoflhsgllvA " + filename .substring(0, filename.length() - filename.split(separator)[filename .split(separator).length - 1].length()) + "out.hse\n"); exec.exec("atacs -T0.000001 -oqoflhsgllvA out.hse", null, work); for (int i = 0; i < simTab.getComponentCount(); i++) { if (simTab.getComponentAt(i).getName().equals("ProbGraph")) { if (simTab.getComponentAt(i) instanceof Graph) { ((Graph) simTab.getComponentAt(i)).refresh(); } else { simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir.split(separator)[outDir.split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, false, false)); simTab.getComponentAt(i).setName("ProbGraph"); } } } // simTab.add("Probability Graph", new // Graph(printer_track_quantity, // outDir.split(separator)[outDir.split(separator).length - // simulation results", // printer_id, outDir, "time", biomodelsim, null, log, null, // false)); // simTab.getComponentAt(simTab.getComponentCount() - // 1).setName("ProbGraph"); } else { if (!printer_id.equals("null.printer")) { if (ode.isSelected()) { for (int i = 0; i < simTab.getComponentCount(); i++) { if (simTab.getComponentAt(i).getName().equals("TSD Graph")) { if (simTab.getComponentAt(i) instanceof Graph) { boolean outputM = true; boolean outputV = true; boolean outputS = true; boolean warning = false; int num = -1; String run = "run-1." + printer_id.substring(0, printer_id.length() - 8); for (String f : work.list()) { if (f.contains("mean")) { outputM = false; } else if (f.contains("variance")) { outputV = false; } else if (f.contains("standard_deviation")) { outputS = false; } else if (f.contains("run-")) { String getNumber = f.substring(4, f.length()); String number = ""; for (int j = 0; j < getNumber.length(); j++) { if (Character.isDigit(getNumber.charAt(j))) { number += getNumber.charAt(j); } else { break; } } if (num == -1) { num = Integer.parseInt(number); } else if (Integer.parseInt(number) < num) { num = Integer.parseInt(number); } run = "run-" + num + "." + printer_id.substring(0, printer_id .length() - 8); } } if (outputM) { ArrayList<ArrayList<Double>> mean = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "average", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), mean); p2.outputTSD(directory + separator + "mean.tsd"); } if (outputV) { ArrayList<ArrayList<Double>> var = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "variance", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), var); p2.outputTSD(directory + separator + "variance.tsd"); } if (outputS) { ArrayList<ArrayList<Double>> stddev = ((Graph) simTab .getComponentAt(i)) .readData(directory + separator + run, "deviation", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), stddev); p2.outputTSD(directory + separator + "standard_deviation.tsd"); } ((Graph) simTab.getComponentAt(i)).refresh(); } else { simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir.split(separator)[outDir .split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, true, false)); boolean outputM = true; boolean outputV = true; boolean outputS = true; boolean warning = false; int num = -1; String run = "run-1." + printer_id.substring(0, printer_id.length() - 8); for (String f : work.list()) { if (f.contains("mean")) { outputM = false; } else if (f.contains("variance")) { outputV = false; } else if (f.contains("standard_deviation")) { outputS = false; } else if (f.contains("run-")) { String getNumber = f.substring(4, f.length()); String number = ""; for (int j = 0; j < getNumber.length(); j++) { if (Character.isDigit(getNumber.charAt(j))) { number += getNumber.charAt(j); } else { break; } } if (num == -1) { num = Integer.parseInt(number); } else if (Integer.parseInt(number) < num) { num = Integer.parseInt(number); } run = "run-" + num + "." + printer_id.substring(0, printer_id .length() - 8); } } if (outputM) { ArrayList<ArrayList<Double>> mean = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "average", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), mean); p2.outputTSD(directory + separator + "mean.tsd"); } if (outputV) { ArrayList<ArrayList<Double>> var = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "variance", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), var); p2.outputTSD(directory + separator + "variance.tsd"); } if (outputS) { ArrayList<ArrayList<Double>> stddev = ((Graph) simTab .getComponentAt(i)) .readData(directory + separator + run, "deviation", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), stddev); p2.outputTSD(directory + separator + "standard_deviation.tsd"); } simTab.getComponentAt(i).setName("TSD Graph"); } } if (simTab.getComponentAt(i).getName().equals("ProbGraph")) { if (simTab.getComponentAt(i) instanceof Graph) { ((Graph) simTab.getComponentAt(i)).refresh(); } else { if (new File(filename.substring(0, filename.length() - filename.split(separator)[filename .split(separator).length - 1].length()) + "sim-rep.txt").exists()) { simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir .split(separator)[outDir .split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, false, false)); simTab.getComponentAt(i).setName("ProbGraph"); } } } } } else if (monteCarlo.isSelected()) { for (int i = 0; i < simTab.getComponentCount(); i++) { if (simTab.getComponentAt(i).getName().equals("TSD Graph")) { if (simTab.getComponentAt(i) instanceof Graph) { boolean outputM = true; boolean outputV = true; boolean outputS = true; boolean warning = false; int num = -1; String run = "run-1." + printer_id.substring(0, printer_id.length() - 8); for (String f : work.list()) { if (f.contains("mean")) { outputM = false; } else if (f.contains("variance")) { outputV = false; } else if (f.contains("standard_deviation")) { outputS = false; } else if (f.contains("run-")) { String getNumber = f.substring(4, f.length()); String number = ""; for (int j = 0; j < getNumber.length(); j++) { if (Character.isDigit(getNumber.charAt(j))) { number += getNumber.charAt(j); } else { break; } } if (num == -1) { num = Integer.parseInt(number); } else if (Integer.parseInt(number) < num) { num = Integer.parseInt(number); } run = "run-" + num + "." + printer_id.substring(0, printer_id .length() - 8); } } if (outputM) { ArrayList<ArrayList<Double>> mean = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "average", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), mean); p2.outputTSD(directory + separator + "mean.tsd"); } if (outputV) { ArrayList<ArrayList<Double>> var = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "variance", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), var); p2.outputTSD(directory + separator + "variance.tsd"); } if (outputS) { ArrayList<ArrayList<Double>> stddev = ((Graph) simTab .getComponentAt(i)) .readData(directory + separator + run, "deviation", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), stddev); p2.outputTSD(directory + separator + "standard_deviation.tsd"); } ((Graph) simTab.getComponentAt(i)).refresh(); } else { simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir.split(separator)[outDir .split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, true, false)); boolean outputM = true; boolean outputV = true; boolean outputS = true; boolean warning = false; int num = -1; String run = "run-1." + printer_id.substring(0, printer_id.length() - 8); for (String f : work.list()) { if (f.contains("mean")) { outputM = false; } else if (f.contains("variance")) { outputV = false; } else if (f.contains("standard_deviation")) { outputS = false; } else if (f.contains("run-")) { String getNumber = f.substring(4, f.length()); String number = ""; for (int j = 0; j < getNumber.length(); j++) { if (Character.isDigit(getNumber.charAt(j))) { number += getNumber.charAt(j); } else { break; } } if (num == -1) { num = Integer.parseInt(number); } else if (Integer.parseInt(number) < num) { num = Integer.parseInt(number); } run = "run-" + num + "." + printer_id.substring(0, printer_id .length() - 8); } } if (outputM) { ArrayList<ArrayList<Double>> mean = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "average", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), mean); p2.outputTSD(directory + separator + "mean.tsd"); } if (outputV) { ArrayList<ArrayList<Double>> var = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "variance", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), var); p2.outputTSD(directory + separator + "variance.tsd"); } if (outputS) { ArrayList<ArrayList<Double>> stddev = ((Graph) simTab .getComponentAt(i)) .readData(directory + separator + run, "deviation", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), stddev); p2.outputTSD(directory + separator + "standard_deviation.tsd"); } simTab.getComponentAt(i).setName("TSD Graph"); } } if (simTab.getComponentAt(i).getName().equals("ProbGraph")) { if (simTab.getComponentAt(i) instanceof Graph) { ((Graph) simTab.getComponentAt(i)).refresh(); } else { if (new File(filename.substring(0, filename.length() - filename.split(separator)[filename .split(separator).length - 1].length()) + "sim-rep.txt").exists()) { simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir .split(separator)[outDir .split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, false, false)); simTab.getComponentAt(i).setName("ProbGraph"); } } } } } } } } } catch (InterruptedException e1) { JOptionPane.showMessageDialog(BioSim.frame, "Error In Execution!", "Error In Execution", JOptionPane.ERROR_MESSAGE); e1.printStackTrace(); } catch (IOException e1) { JOptionPane.showMessageDialog(BioSim.frame, "File I/O Error!", "File I/O Error", JOptionPane.ERROR_MESSAGE); e1.printStackTrace(); } return exitValue; } /** * This method is called if a button that cancels the simulation is pressed. */ public void actionPerformed(ActionEvent e) { if (reb2sac != null) { reb2sac.destroy(); } if (sg != null) { sg.stop(); } } }
package com.gmail.jameshealey1994.simplepvptoggle.listeners; import com.gmail.jameshealey1994.simplepvptoggle.SimplePVPToggle; import org.bukkit.ChatColor; import org.bukkit.entity.Player; import org.bukkit.entity.Projectile; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageByEntityEvent; /** * Listener class for the SimplePVPToggle plugin. * @author JamesHealey94 <jameshealey1994.gmail.com> */ public class SimplePVPToggleListener implements Listener { /** * Plugin with config file used to get PvP value. */ SimplePVPToggle plugin; /** * Constructor used to set plugin. * @param plugin Plugin used for config to retrieve PvP values from */ public SimplePVPToggleListener(SimplePVPToggle plugin) { this.plugin = plugin; } /** * Entity damaged by another entity event. * Cancels the event and sends damager a message if either damager or attacked player have not enabled PvP * @param event The event being handled */ @EventHandler (priority = EventPriority.LOWEST) public void onEntityDamageByEntityEvent(EntityDamageByEntityEvent event) { /* * Currently works with melee, arrows and potions, but not from dispensers. * Should it work with dispensers? Perhaps some config values for dispensers?. */ if (event.getEntity() instanceof Player) { final Player attackedPlayer = (Player) event.getEntity(); final Player attacker; if (event.getDamager() instanceof Player) { attacker = (Player) event.getDamager(); } else if (event.getDamager() instanceof Projectile) { if (((Projectile) event.getDamager()).getShooter() instanceof Player) { attacker = (Player) ((Projectile) event.getDamager()).getShooter(); } else { return; } } else { return; } if (canPVP(attacker)) { if (canPVP(attackedPlayer)) { // Debug messages to show the config values // TODO: Remove attacker.sendMessage(ChatColor.GRAY + "Attacked " + attackedPlayer.getDisplayName() + " for " + event.getDamage() + " damage."); attackedPlayer.sendMessage(ChatColor.GRAY + "Attacked by " + attacker.getDisplayName() + " for " + event.getDamage() + " damage."); // PVP is allowed. No changes needed. } else { event.setCancelled(true); attacker.sendMessage(ChatColor.GRAY + "Attack Cancelled - " + attackedPlayer.getDisplayName() + " does not have PvP enabled."); } } else { event.setCancelled(true); attacker.sendMessage(ChatColor.GRAY + "Attack Cancelled - You do not have PvP enabled."); } // Stop arrows bouncing back, possibly hitting you. if ((event.isCancelled()) && (event.getDamager() instanceof Projectile)) { ((Projectile) event.getDamager()).setBounce(false); } } } /** * Helper method used to check if a player's PvP value is set to true in the config. * It first looks for a specific value for that player in that world. * If that is not found, it is set to the default value for the world the player is currently in. * If that is not found, it is set to the default value for the server. * If there is an error with the default value for the server, it is set to false by default. * @param player The player being checked * @return If the player can PVP in that world */ public boolean canPVP(Player player) { // Debug messages to show the config values // TODO: Add some more statements to help players with "lazy" configs (without .Default, for example). player.sendMessage("Server.Worlds." + player.getWorld().getName() + ".Players." + player.getName() + ": " + plugin.getConfig().getBoolean("Server.Worlds." + player.getWorld().getName() + ".Players." + player.getName())); player.sendMessage("Server.Worlds." + player.getWorld().getName() + ".Default" + ": " + plugin.getConfig().getBoolean("Server.Worlds." + player.getWorld().getName() + ".Default")); player.sendMessage("Server.Worlds." + player.getWorld().getName() + ": " + plugin.getConfig().getBoolean("Server.Worlds." + player.getWorld().getName())); player.sendMessage("Server.Default" + ": " + plugin.getConfig().getBoolean("Server.Default")); return (plugin.getConfig().getBoolean("Server.Worlds." + player.getWorld().getName() + ".Players." + player.getName(), plugin.getConfig().getBoolean("Server.Worlds." + player.getWorld().getName() + ".Default", plugin.getConfig().getBoolean("Server.Worlds." + player.getWorld().getName(), plugin.getConfig().getBoolean("Server.Default", false))))); } }
package reb2sac; import java.io.*; import java.awt.*; import java.awt.event.*; import java.util.*; import java.util.prefs.Preferences; import javax.swing.*; import parser.*; import lpn.gui.LHPNEditor; import lpn.parser.Abstraction; import lpn.parser.LhpnFile; import lpn.parser.Translator; import main.*; import gillespieSSAjava.GillespieSSAJavaSingleStep; import gcm.gui.GCM2SBMLEditor; import gcm.parser.GCMFile; import gcm.util.GlobalConstants; import graph.*; import sbmleditor.*; import stategraph.BuildStateGraphThread; import stategraph.PerfromSteadyStateMarkovAnalysisThread; import stategraph.PerfromTransientMarkovAnalysisThread; import stategraph.StateGraph; import util.*; import verification.AbstPane; /** * This class creates the properties file that is given to the reb2sac program. * It also executes the reb2sac program. * * @author Curtis Madsen */ public class Run implements ActionListener { private Process reb2sac; private String separator; private Reb2Sac r2s; StateGraph sg; public Run(Reb2Sac reb2sac) { r2s = reb2sac; if (File.separator.equals("\\")) { separator = "\\\\"; } else { separator = File.separator; } } /** * This method is given which buttons are selected and creates the * properties file from all the other information given. * * @param useInterval * * @param stem */ public void createProperties(double timeLimit, String useInterval, double printInterval, double minTimeStep, double timeStep, double absError, String outDir, long rndSeed, int run, String[] termCond, String[] intSpecies, String printer_id, String printer_track_quantity, String[] getFilename, String selectedButtons, Component component, String filename, double rap1, double rap2, double qss, int con, JCheckBox usingSSA, String ssaFile, JCheckBox usingSad, File sadFile, JList preAbs, JList loopAbs, JList postAbs, AbstPane abstPane) { Properties abs = new Properties(); if (selectedButtons.contains("abs") || selectedButtons.contains("nary")) { for (int i = 0; i < preAbs.getModel().getSize(); i++) { abs.setProperty("reb2sac.abstraction.method.1." + (i + 1), (String) preAbs .getModel().getElementAt(i)); } for (int i = 0; i < loopAbs.getModel().getSize(); i++) { abs.setProperty("reb2sac.abstraction.method.2." + (i + 1), (String) loopAbs .getModel().getElementAt(i)); } // abs.setProperty("reb2sac.abstraction.method.0.1", // "enzyme-kinetic-qssa-1"); // abs.setProperty("reb2sac.abstraction.method.0.2", // "reversible-to-irreversible-transformer"); // abs.setProperty("reb2sac.abstraction.method.0.3", // "multiple-products-reaction-eliminator"); // abs.setProperty("reb2sac.abstraction.method.0.4", // "multiple-reactants-reaction-eliminator"); // abs.setProperty("reb2sac.abstraction.method.0.5", // "single-reactant-product-reaction-eliminator"); // abs.setProperty("reb2sac.abstraction.method.0.6", // "dimer-to-monomer-substitutor"); // abs.setProperty("reb2sac.abstraction.method.0.7", // "inducer-structure-transformer"); // abs.setProperty("reb2sac.abstraction.method.1.1", // "modifier-structure-transformer"); // abs.setProperty("reb2sac.abstraction.method.1.2", // "modifier-constant-propagation"); // abs.setProperty("reb2sac.abstraction.method.2.1", // "operator-site-forward-binding-remover"); // abs.setProperty("reb2sac.abstraction.method.2.3", // "enzyme-kinetic-rapid-equilibrium-1"); // abs.setProperty("reb2sac.abstraction.method.2.4", // "irrelevant-species-remover"); // abs.setProperty("reb2sac.abstraction.method.2.5", // "inducer-structure-transformer"); // abs.setProperty("reb2sac.abstraction.method.2.6", // "modifier-constant-propagation"); // abs.setProperty("reb2sac.abstraction.method.2.7", // "similar-reaction-combiner"); // abs.setProperty("reb2sac.abstraction.method.2.8", // "modifier-constant-propagation"); } // if (selectedButtons.contains("abs")) { // abs.setProperty("reb2sac.abstraction.method.2.2", // "dimerization-reduction"); // else if (selectedButtons.contains("nary")) { // abs.setProperty("reb2sac.abstraction.method.2.2", // "dimerization-reduction-level-assignment"); for (int i = 0; i < postAbs.getModel().getSize(); i++) { abs.setProperty("reb2sac.abstraction.method.3." + (i + 1), (String) postAbs.getModel() .getElementAt(i)); } abs.setProperty("simulation.printer", printer_id); abs.setProperty("simulation.printer.tracking.quantity", printer_track_quantity); // if (selectedButtons.contains("monteCarlo")) { // abs.setProperty("reb2sac.abstraction.method.3.1", // "distribute-transformer"); // abs.setProperty("reb2sac.abstraction.method.3.2", // "reversible-to-irreversible-transformer"); // abs.setProperty("reb2sac.abstraction.method.3.3", // "kinetic-law-constants-simplifier"); // else if (selectedButtons.contains("none")) { // abs.setProperty("reb2sac.abstraction.method.3.1", // "kinetic-law-constants-simplifier"); for (int i = 0; i < intSpecies.length; i++) { if (!intSpecies[i].equals("")) { String[] split = intSpecies[i].split(" "); abs.setProperty("reb2sac.interesting.species." + (i + 1), split[0]); if (split.length > 1) { String[] levels = split[1].split(","); for (int j = 0; j < levels.length; j++) { abs.setProperty("reb2sac.concentration.level." + split[0] + "." + (j + 1), levels[j]); } } } } abs.setProperty("reb2sac.rapid.equilibrium.condition.1", "" + rap1); abs.setProperty("reb2sac.rapid.equilibrium.condition.2", "" + rap2); abs.setProperty("reb2sac.qssa.condition.1", "" + qss); abs.setProperty("reb2sac.operator.max.concentration.threshold", "" + con); if (selectedButtons.contains("none")) { abs.setProperty("reb2sac.abstraction.method", "none"); } if (selectedButtons.contains("abs")) { abs.setProperty("reb2sac.abstraction.method", "abs"); } else if (selectedButtons.contains("nary")) { abs.setProperty("reb2sac.abstraction.method", "nary"); } if (abstPane != null) { for (Integer i = 0; i < abstPane.preAbsModel.size(); i++) { abs .setProperty("abstraction.transform." + abstPane.preAbsModel.getElementAt(i).toString(), "preloop" + i.toString()); } for (Integer i = 0; i < abstPane.loopAbsModel.size(); i++) { if (abstPane.preAbsModel.contains(abstPane.loopAbsModel.getElementAt(i))) { String value = abs .getProperty(abstPane.loopAbsModel.getElementAt(i).toString()); value = value + "mainloop" + i.toString(); abs.setProperty("abstraction.transform." + abstPane.loopAbsModel.getElementAt(i).toString(), value); } else { abs.setProperty("abstraction.transform." + abstPane.loopAbsModel.getElementAt(i).toString(), "mainloop" + i.toString()); } } for (Integer i = 0; i < abstPane.postAbsModel.size(); i++) { if (abstPane.preAbsModel.contains(abstPane.postAbsModel.getElementAt(i)) || abstPane.preAbsModel.contains(abstPane.postAbsModel.get(i))) { String value = abs .getProperty(abstPane.postAbsModel.getElementAt(i).toString()); value = value + "postloop" + i.toString(); abs.setProperty("abstraction.transform." + abstPane.postAbsModel.getElementAt(i).toString(), value); } else { abs.setProperty("abstraction.transform." + abstPane.postAbsModel.getElementAt(i).toString(), "postloop" + i.toString()); } } for (String s : abstPane.transforms) { if (!abstPane.preAbsModel.contains(s) && !abstPane.loopAbsModel.contains(s) && !abstPane.postAbsModel.contains(s)) { abs.remove(s); } } } if (selectedButtons.contains("ODE")) { abs.setProperty("reb2sac.simulation.method", "ODE"); } else if (selectedButtons.contains("monteCarlo")) { abs.setProperty("reb2sac.simulation.method", "monteCarlo"); } else if (selectedButtons.contains("markov")) { abs.setProperty("reb2sac.simulation.method", "markov"); } else if (selectedButtons.contains("sbml")) { abs.setProperty("reb2sac.simulation.method", "SBML"); } else if (selectedButtons.contains("dot")) { abs.setProperty("reb2sac.simulation.method", "Network"); } else if (selectedButtons.contains("xhtml")) { abs.setProperty("reb2sac.simulation.method", "Browser"); } else if (selectedButtons.contains("lhpn")) { abs.setProperty("reb2sac.simulation.method", "LPN"); } if (!selectedButtons.contains("monteCarlo")) { // if (selectedButtons.equals("none_ODE") || // selectedButtons.equals("abs_ODE")) { abs.setProperty("ode.simulation.time.limit", "" + timeLimit); if (useInterval.equals("Print Interval")) { abs.setProperty("ode.simulation.print.interval", "" + printInterval); } else if (useInterval.equals("Minimum Print Interval")) { abs.setProperty("ode.simulation.minimum.print.interval", "" + printInterval); } else { abs.setProperty("ode.simulation.number.steps", "" + ((int) printInterval)); } if (timeStep == Double.MAX_VALUE) { abs.setProperty("ode.simulation.time.step", "inf"); } else { abs.setProperty("ode.simulation.time.step", "" + timeStep); } abs.setProperty("ode.simulation.min.time.step", "" + minTimeStep); abs.setProperty("ode.simulation.absolute.error", "" + absError); abs.setProperty("ode.simulation.out.dir", outDir); abs.setProperty("monte.carlo.simulation.random.seed", "" + rndSeed); abs.setProperty("monte.carlo.simulation.runs", "" + run); } if (!selectedButtons.contains("ODE")) { // if (selectedButtons.equals("none_monteCarlo") || // selectedButtons.equals("abs_monteCarlo")) { abs.setProperty("monte.carlo.simulation.time.limit", "" + timeLimit); if (useInterval.equals("Print Interval")) { abs.setProperty("monte.carlo.simulation.print.interval", "" + printInterval); } else if (useInterval.equals("Minimum Print Interval")) { abs .setProperty("monte.carlo.simulation.minimum.print.interval", "" + printInterval); } else { abs.setProperty("monte.carlo.simulation.number.steps", "" + ((int) printInterval)); } if (timeStep == Double.MAX_VALUE) { abs.setProperty("monte.carlo.simulation.time.step", "inf"); } else { abs.setProperty("monte.carlo.simulation.time.step", "" + timeStep); } abs.setProperty("monte.carlo.simulation.min.time.step", "" + minTimeStep); abs.setProperty("monte.carlo.simulation.random.seed", "" + rndSeed); abs.setProperty("monte.carlo.simulation.runs", "" + run); abs.setProperty("monte.carlo.simulation.out.dir", outDir); if (usingSad.isSelected()) { abs.setProperty("simulation.run.termination.decider", "sad"); abs.setProperty("computation.analysis.sad.path", sadFile.getName()); } } if (!usingSad.isSelected()) { abs.setProperty("simulation.run.termination.decider", "constraint"); } if (usingSSA.isSelected() && selectedButtons.contains("monteCarlo")) { abs.setProperty("simulation.time.series.species.level.file", ssaFile); } for (int i = 0; i < termCond.length; i++) { if (termCond[i] != "") { abs .setProperty("simulation.run.termination.condition." + (i + 1), "" + termCond[i]); } } try { if (!getFilename[getFilename.length - 1].contains(".")) { getFilename[getFilename.length - 1] += "."; filename += "."; } int cut = 0; for (int i = 0; i < getFilename[getFilename.length - 1].length(); i++) { if (getFilename[getFilename.length - 1].charAt(i) == '.') { cut = i; } } FileOutputStream store = new FileOutputStream(new File((filename.substring(0, filename .length() - getFilename[getFilename.length - 1].length())) + getFilename[getFilename.length - 1].substring(0, cut) + ".properties")); abs.store(store, getFilename[getFilename.length - 1].substring(0, cut) + " Properties"); store.close(); } catch (Exception except) { JOptionPane.showMessageDialog(component, "Unable To Save Properties File!" + "\nMake sure you select a model for abstraction.", "Unable To Save File", JOptionPane.ERROR_MESSAGE); } } /** * This method is given what data is entered into the nary frame and creates * the nary properties file from that information. */ public void createNaryProperties(double timeLimit, String useInterval, double printInterval, double minTimeStep, double timeStep, String outDir, long rndSeed, int run, String printer_id, String printer_track_quantity, String[] getFilename, Component component, String filename, JRadioButton monteCarlo, String stopE, double stopR, String[] finalS, ArrayList<JTextField> inhib, ArrayList<JList> consLevel, ArrayList<String> getSpeciesProps, ArrayList<Object[]> conLevel, String[] termCond, String[] intSpecies, double rap1, double rap2, double qss, int con, ArrayList<Integer> counts, JCheckBox usingSSA, String ssaFile) { Properties nary = new Properties(); try { FileInputStream load = new FileInputStream(new File(outDir + separator + "species.properties")); nary.load(load); load.close(); } catch (Exception e) { JOptionPane.showMessageDialog(component, "Species Properties File Not Found!", "File Not Found", JOptionPane.ERROR_MESSAGE); } nary.setProperty("reb2sac.abstraction.method.0.1", "enzyme-kinetic-qssa-1"); nary .setProperty("reb2sac.abstraction.method.0.2", "reversible-to-irreversible-transformer"); nary.setProperty("reb2sac.abstraction.method.0.3", "multiple-products-reaction-eliminator"); nary .setProperty("reb2sac.abstraction.method.0.4", "multiple-reactants-reaction-eliminator"); nary.setProperty("reb2sac.abstraction.method.0.5", "single-reactant-product-reaction-eliminator"); nary.setProperty("reb2sac.abstraction.method.0.6", "dimer-to-monomer-substitutor"); nary.setProperty("reb2sac.abstraction.method.0.7", "inducer-structure-transformer"); nary.setProperty("reb2sac.abstraction.method.1.1", "modifier-structure-transformer"); nary.setProperty("reb2sac.abstraction.method.1.2", "modifier-constant-propagation"); nary.setProperty("reb2sac.abstraction.method.2.1", "operator-site-forward-binding-remover"); nary.setProperty("reb2sac.abstraction.method.2.3", "enzyme-kinetic-rapid-equilibrium-1"); nary.setProperty("reb2sac.abstraction.method.2.4", "irrelevant-species-remover"); nary.setProperty("reb2sac.abstraction.method.2.5", "inducer-structure-transformer"); nary.setProperty("reb2sac.abstraction.method.2.6", "modifier-constant-propagation"); nary.setProperty("reb2sac.abstraction.method.2.7", "similar-reaction-combiner"); nary.setProperty("reb2sac.abstraction.method.2.8", "modifier-constant-propagation"); nary.setProperty("reb2sac.abstraction.method.2.2", "dimerization-reduction"); nary.setProperty("reb2sac.abstraction.method.3.1", "nary-order-unary-transformer"); nary.setProperty("reb2sac.abstraction.method.3.2", "modifier-constant-propagation"); nary.setProperty("reb2sac.abstraction.method.3.3", "absolute-inhibition-generator"); nary.setProperty("reb2sac.abstraction.method.3.4", "final-state-generator"); nary.setProperty("reb2sac.abstraction.method.3.5", "stop-flag-generator"); nary.setProperty("reb2sac.nary.order.decider", "distinct"); nary.setProperty("simulation.printer", printer_id); nary.setProperty("simulation.printer.tracking.quantity", printer_track_quantity); nary.setProperty("reb2sac.analysis.stop.enabled", stopE); nary.setProperty("reb2sac.analysis.stop.rate", "" + stopR); for (int i = 0; i < getSpeciesProps.size(); i++) { if (!(inhib.get(i).getText().trim() != "<<none>>")) { nary.setProperty("reb2sac.absolute.inhibition.threshold." + getSpeciesProps.get(i), inhib.get(i).getText().trim()); } String[] consLevels = Utility.getList(conLevel.get(i), consLevel.get(i)); for (int j = 0; j < counts.get(i); j++) { nary .remove("reb2sac.concentration.level." + getSpeciesProps.get(i) + "." + (j + 1)); } for (int j = 0; j < consLevels.length; j++) { nary.setProperty("reb2sac.concentration.level." + getSpeciesProps.get(i) + "." + (j + 1), consLevels[j]); } } if (monteCarlo.isSelected()) { nary.setProperty("monte.carlo.simulation.time.limit", "" + timeLimit); if (useInterval.equals("Print Interval")) { nary.setProperty("monte.carlo.simulation.print.interval", "" + printInterval); } else if (useInterval.equals("Minimum Print Interval")) { nary.setProperty("monte.carlo.simulation.minimum.print.interval", "" + printInterval); } else { nary.setProperty("monte.carlo.simulation.number.steps", "" + ((int) printInterval)); } if (timeStep == Double.MAX_VALUE) { nary.setProperty("monte.carlo.simulation.time.step", "inf"); } else { nary.setProperty("monte.carlo.simulation.time.step", "" + timeStep); } nary.setProperty("monte.carlo.simulation.min.time.step", "" + minTimeStep); nary.setProperty("monte.carlo.simulation.random.seed", "" + rndSeed); nary.setProperty("monte.carlo.simulation.runs", "" + run); nary.setProperty("monte.carlo.simulation.out.dir", "."); } for (int i = 0; i < finalS.length; i++) { if (finalS[i].trim() != "<<unknown>>") { nary.setProperty("reb2sac.final.state." + (i + 1), "" + finalS[i]); } } if (usingSSA.isSelected() && monteCarlo.isSelected()) { nary.setProperty("simulation.time.series.species.level.file", ssaFile); } for (int i = 0; i < intSpecies.length; i++) { if (intSpecies[i] != "") { nary.setProperty("reb2sac.interesting.species." + (i + 1), "" + intSpecies[i]); } } nary.setProperty("reb2sac.rapid.equilibrium.condition.1", "" + rap1); nary.setProperty("reb2sac.rapid.equilibrium.condition.2", "" + rap2); nary.setProperty("reb2sac.qssa.condition.1", "" + qss); nary.setProperty("reb2sac.operator.max.concentration.threshold", "" + con); for (int i = 0; i < termCond.length; i++) { if (termCond[i] != "") { nary.setProperty("simulation.run.termination.condition." + (i + 1), "" + termCond[i]); } } try { FileOutputStream store = new FileOutputStream(new File(filename.replace(".sbml", "") .replace(".xml", "") + ".properties")); nary.store(store, getFilename[getFilename.length - 1].replace(".sbml", "").replace( ".xml", "") + " Properties"); store.close(); } catch (Exception except) { JOptionPane.showMessageDialog(component, "Unable To Save Properties File!" + "\nMake sure you select a model for simulation.", "Unable To Save File", JOptionPane.ERROR_MESSAGE); } } /** * Executes the reb2sac program. If ODE, monte carlo, or markov is selected, * this method creates a Graph object. * * @param runTime */ public int execute(String filename, JRadioButton sbml, JRadioButton dot, JRadioButton xhtml, JRadioButton lhpn, Component component, JRadioButton ode, JRadioButton monteCarlo, String sim, String printer_id, String printer_track_quantity, String outDir, JRadioButton nary, int naryRun, String[] intSpecies, Log log, JCheckBox usingSSA, String ssaFile, Gui biomodelsim, JTabbedPane simTab, String root, JProgressBar progress, String simName, GCM2SBMLEditor gcmEditor, String direct, double timeLimit, double runTime, String modelFile, AbstPane abstPane, JRadioButton abstraction, String lpnProperty, double absError, double timeStep, double printInterval, int runs, long rndSeed) { Runtime exec = Runtime.getRuntime(); int exitValue = 255; while (outDir.split(separator)[outDir.split(separator).length - 1].equals(".")) { outDir = outDir.substring(0, outDir.length() - 1 - outDir.split(separator)[outDir.split(separator).length - 1].length()); } try { long time1; String directory = ""; String theFile = ""; String sbmlName = ""; String lhpnName = ""; if (filename.lastIndexOf('/') >= 0) { directory = filename.substring(0, filename.lastIndexOf('/') + 1); theFile = filename.substring(filename.lastIndexOf('/') + 1); } if (filename.lastIndexOf('\\') >= 0) { directory = filename.substring(0, filename.lastIndexOf('\\') + 1); theFile = filename.substring(filename.lastIndexOf('\\') + 1); } File work = new File(directory); String out = theFile; if (out.length() > 4 && out.substring(out.length() - 5, out.length()).equals(".sbml")) { out = out.substring(0, out.length() - 5); } else if (out.length() > 3 && out.substring(out.length() - 4, out.length()).equals(".xml")) { out = out.substring(0, out.length() - 4); } if (nary.isSelected() && gcmEditor != null && (monteCarlo.isSelected() || xhtml.isSelected())) { String lpnName = modelFile.replace(".sbml", "").replace(".gcm", "").replace(".xml", "") + ".lpn"; ArrayList<String> specs = new ArrayList<String>(); ArrayList<Object[]> conLevel = new ArrayList<Object[]>(); for (int i = 0; i < intSpecies.length; i++) { if (!intSpecies[i].equals("")) { String[] split = intSpecies[i].split(" "); if (split.length > 1) { String[] levels = split[1].split(","); if (levels.length > 0) { specs.add(split[0]); conLevel.add(levels); } } } } GCMFile paramGCM = gcmEditor.getGCM(); GCMFile gcm = new GCMFile(root); gcm.load(root + separator + gcmEditor.getRefFile()); HashMap<String, Properties> elements = paramGCM.getSpecies(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.ID) && !prop.equals(GlobalConstants.TYPE)) { gcm.getSpecies().get(key).put(prop, elements.get(key).get(prop)); } } } elements = paramGCM.getInfluences(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.PROMOTER) && !prop.equals(GlobalConstants.BIO) && !prop.equals(GlobalConstants.TYPE)) { gcm.getInfluences().get(key).put(prop, elements.get(key).get(prop)); } } } elements = paramGCM.getPromoters(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.ID)) { gcm.getPromoters().get(key).put(prop, elements.get(key).get(prop)); } } } HashMap<String, String> params = paramGCM.getGlobalParameters(); ArrayList<Object> remove = new ArrayList<Object>(); for (String key : params.keySet()) { gcm.setParameter(key, params.get(key)); remove.add(key); } if (direct != null && !direct.equals("")) { String[] d = direct.split("_"); ArrayList<String> dd = new ArrayList<String>(); for (int i = 0; i < d.length; i++) { if (!d[i].contains("=")) { String di = d[i]; while (!d[i].contains("=")) { i++; di += "_" + d[i]; } dd.add(di); } else { dd.add(d[i]); } } for (String di : dd) { if (di.contains("-")) { if (gcm.getPromoters().containsKey(di.split("=")[0].split("-")[0])) { Properties promoterProps = gcm.getPromoters().get( di.split("=")[0].split("-")[0]); promoterProps.put(di.split("=")[0].split("-")[1], di.split("=")[1]); } if (gcm.getSpecies().containsKey(di.split("=")[0].split("-")[0])) { Properties speciesProps = gcm.getSpecies().get( di.split("=")[0].split("-")[0]); speciesProps.put(di.split("=")[0].split("-")[1], di.split("=")[1]); } String influence = ""; for (String infl : gcm.getInfluences().keySet()) { boolean matchInfl = true; for (String part : di.split("=")[0].split("-")[0] .split("_")) { if (!infl.contains(part)) { matchInfl = false; } } if (matchInfl) { influence = infl; } } if (!influence.equals("")) { Properties influenceProps = gcm.getInfluences().get( influence); influenceProps.put(di.split("=")[0].split("-")[1].replace( "\"", ""), di.split("=")[1]); } } else { if (gcm.getGlobalParameters().containsKey(di.split("=")[0])) { gcm.getGlobalParameters().put(di.split("=")[0], di.split("=")[1]); } if (gcm.getParameters().containsKey(di.split("=")[0])) { gcm.getParameters().put(di.split("=")[0], di.split("=")[1]); } } } } if (gcm.flattenGCM(false) != null) { time1 = System.nanoTime(); LhpnFile lpnFile = gcm.convertToLHPN(specs, conLevel); if (lpnFile == null) { return 0; } lpnFile.save(root + separator + simName + separator + lpnName); Translator t1 = new Translator(); if (abstraction.isSelected()) { LhpnFile lhpnFile = new LhpnFile(); lhpnFile.load(root + separator + simName + separator + lpnName); Abstraction abst = new Abstraction(lhpnFile, abstPane); abst.abstractSTG(false); abst.save(root + separator + simName + separator + lpnName + ".temp"); t1.BuildTemplate( root + separator + simName + separator + lpnName + ".temp", lpnProperty); } else { t1.BuildTemplate(root + separator + simName + separator + lpnName, lpnProperty); } t1.setFilename(root + separator + simName + separator + lpnName.replace(".lpn", ".sbml")); t1.outputSBML(); } else { return 0; } } if (nary.isSelected() && gcmEditor == null && !sim.contains("markov-chain-analysis") && !lhpn.isSelected() && naryRun == 1) { log.addText("Executing:\nreb2sac --target.encoding=nary-level " + filename + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec("reb2sac --target.encoding=nary-level " + theFile, null, work); } else if (sbml.isSelected()) { sbmlName = JOptionPane.showInputDialog(component, "Enter SBML Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (sbmlName != null && !sbmlName.trim().equals("")) { sbmlName = sbmlName.trim(); if (sbmlName.length() > 4) { if (!sbmlName.substring(sbmlName.length() - 3).equals(".xml") || !sbmlName.substring(sbmlName.length() - 4).equals(".sbml")) { sbmlName += ".xml"; } } else { sbmlName += ".xml"; } File f = new File(root + separator + sbmlName); if (f.exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(component, "File already exists." + "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { File dir = new File(root + separator + sbmlName); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { System.gc(); dir.delete(); } } else { return 0; } } if (modelFile.contains(".lpn")) { progress.setIndeterminate(true); time1 = System.nanoTime(); Translator t1 = new Translator(); if (abstraction.isSelected()) { LhpnFile lhpnFile = new LhpnFile(); lhpnFile.load(root + separator + modelFile); Abstraction abst = new Abstraction(lhpnFile, abstPane); abst.abstractSTG(false); abst.save(root + separator + simName + separator + modelFile); t1.BuildTemplate(root + separator + simName + separator + modelFile, lpnProperty); } else { t1.BuildTemplate(root + separator + modelFile, lpnProperty); } t1.setFilename(root + separator + sbmlName); t1.outputSBML(); exitValue = 0; } else if (gcmEditor != null && nary.isSelected()) { String lpnName = modelFile.replace(".sbml", "").replace(".gcm", "") .replace(".xml", "") + ".lpn"; ArrayList<String> specs = new ArrayList<String>(); ArrayList<Object[]> conLevel = new ArrayList<Object[]>(); for (int i = 0; i < intSpecies.length; i++) { if (!intSpecies[i].equals("")) { String[] split = intSpecies[i].split(" "); if (split.length > 1) { String[] levels = split[1].split(","); if (levels.length > 0) { specs.add(split[0]); conLevel.add(levels); } } } } progress.setIndeterminate(true); GCMFile paramGCM = gcmEditor.getGCM(); GCMFile gcm = new GCMFile(root); gcm.load(root + separator + gcmEditor.getRefFile()); HashMap<String, Properties> elements = paramGCM.getSpecies(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.ID) && !prop.equals(GlobalConstants.TYPE)) { gcm.getSpecies().get(key) .put(prop, elements.get(key).get(prop)); } } } elements = paramGCM.getInfluences(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.PROMOTER) && !prop.equals(GlobalConstants.BIO) && !prop.equals(GlobalConstants.TYPE)) { gcm.getInfluences().get(key).put(prop, elements.get(key).get(prop)); } } } elements = paramGCM.getPromoters(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.ID)) { gcm.getPromoters().get(key).put(prop, elements.get(key).get(prop)); } } } HashMap<String, String> params = paramGCM.getGlobalParameters(); ArrayList<Object> remove = new ArrayList<Object>(); for (String key : params.keySet()) { gcm.setParameter(key, params.get(key)); remove.add(key); } if (gcm.flattenGCM(false) != null) { time1 = System.nanoTime(); LhpnFile lpnFile = gcm.convertToLHPN(specs, conLevel); if (lpnFile == null) { return 0; } lpnFile.save(root + separator + simName + separator + lpnName); Translator t1 = new Translator(); if (abstraction.isSelected()) { LhpnFile lhpnFile = new LhpnFile(); lhpnFile.load(root + separator + simName + separator + lpnName); Abstraction abst = new Abstraction(lhpnFile, abstPane); abst.abstractSTG(false); abst.save(root + separator + simName + separator + lpnName + ".temp"); t1.BuildTemplate(root + separator + simName + separator + lpnName + ".temp", lpnProperty); } else { t1.BuildTemplate(root + separator + simName + separator + lpnName, lpnProperty); } t1.setFilename(root + separator + sbmlName); t1.outputSBML(); } else { time1 = System.nanoTime(); return 0; } exitValue = 0; } else { if (abstraction.isSelected() || nary.isSelected()) { log.addText("Executing:\nreb2sac --target.encoding=sbml --out=" + ".." + separator + sbmlName + " " + filename + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec("reb2sac --target.encoding=sbml --out=" + ".." + separator + sbmlName + " " + theFile, null, work); } else { log.addText("Outputting SBML file:\n" + root + separator + sbmlName + "\n"); time1 = System.nanoTime(); FileOutputStream fileOutput = new FileOutputStream(new File(root + separator + sbmlName)); FileInputStream fileInput = new FileInputStream(new File(filename)); int read = fileInput.read(); while (read != -1) { fileOutput.write(read); read = fileInput.read(); } fileInput.close(); fileOutput.close(); exitValue = 0; } } } else { time1 = System.nanoTime(); } } else if (lhpn.isSelected()) { lhpnName = JOptionPane.showInputDialog(component, "Enter LPN Model ID:", "Model ID", JOptionPane.PLAIN_MESSAGE); if (lhpnName != null && !lhpnName.trim().equals("")) { lhpnName = lhpnName.trim(); if (lhpnName.length() > 4) { if (!lhpnName.substring(lhpnName.length() - 3).equals(".lpn")) { lhpnName += ".lpn"; } } else { lhpnName += ".lpn"; } File f = new File(root + separator + lhpnName); if (f.exists()) { Object[] options = { "Overwrite", "Cancel" }; int value = JOptionPane.showOptionDialog(component, "File already exists." + "\nDo you want to overwrite?", "Overwrite", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE, null, options, options[0]); if (value == JOptionPane.YES_OPTION) { File dir = new File(root + separator + lhpnName); if (dir.isDirectory()) { biomodelsim.deleteDir(dir); } else { System.gc(); dir.delete(); } } else { return 0; } } if (modelFile.contains(".lpn")) { LhpnFile lhpnFile = new LhpnFile(); lhpnFile.load(root + separator + modelFile); lhpnFile.save(root + separator + lhpnName); time1 = System.nanoTime(); exitValue = 0; } else { ArrayList<String> specs = new ArrayList<String>(); ArrayList<Object[]> conLevel = new ArrayList<Object[]>(); for (int i = 0; i < intSpecies.length; i++) { if (!intSpecies[i].equals("")) { String[] split = intSpecies[i].split(" "); if (split.length > 1) { String[] levels = split[1].split(","); if (levels.length > 0) { specs.add(split[0]); conLevel.add(levels); } } } } progress.setIndeterminate(true); GCMFile paramGCM = gcmEditor.getGCM(); GCMFile gcm = new GCMFile(root); gcm.load(root + separator + gcmEditor.getRefFile()); HashMap<String, Properties> elements = paramGCM.getSpecies(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.ID) && !prop.equals(GlobalConstants.TYPE)) { gcm.getSpecies().get(key) .put(prop, elements.get(key).get(prop)); } } } elements = paramGCM.getInfluences(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.PROMOTER) && !prop.equals(GlobalConstants.BIO) && !prop.equals(GlobalConstants.TYPE)) { gcm.getInfluences().get(key).put(prop, elements.get(key).get(prop)); } } } elements = paramGCM.getPromoters(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.ID)) { gcm.getPromoters().get(key).put(prop, elements.get(key).get(prop)); } } } HashMap<String, String> params = paramGCM.getGlobalParameters(); ArrayList<Object> remove = new ArrayList<Object>(); for (String key : params.keySet()) { gcm.setParameter(key, params.get(key)); remove.add(key); } if (gcm.flattenGCM(false) != null) { time1 = System.nanoTime(); LhpnFile lhpnFile = gcm.convertToLHPN(specs, conLevel); if (lhpnFile == null) { return 0; } lhpnFile.save(root + separator + lhpnName); log.addText("Saving GCM file as LHPN:\n" + root + separator + lhpnName + "\n"); } else { return 0; } exitValue = 0; } } else { time1 = System.nanoTime(); exitValue = 0; } } else if (dot.isSelected()) { if (nary.isSelected() && gcmEditor != null) { // String cmd = "atacs -cPllodpl " // + theFile.replace(".sbml", "").replace(".xml", "") + // ".lpn"; LhpnFile lhpnFile = new LhpnFile(log); lhpnFile.load(directory + separator + theFile.replace(".sbml", "").replace(".xml", "") + ".lpn"); lhpnFile.printDot(directory + separator + theFile.replace(".sbml", "").replace(".xml", "") + ".dot"); time1 = System.nanoTime(); // Process ATACS = exec.exec(cmd, null, work); // ATACS.waitFor(); // log.addText("Executing:\n" + cmd); exitValue = 0; } else if (modelFile.contains(".lpn")) { LhpnFile lhpnFile = new LhpnFile(); lhpnFile.load(root + separator + modelFile); lhpnFile.save(root + separator + simName + separator + modelFile); lhpnFile.printDot(root + separator + modelFile.replace(".lpn", ".dot")); // String cmd = "atacs -cPllodpl " + modelFile; // time1 = System.nanoTime(); // Process ATACS = exec.exec(cmd, null, work); // ATACS.waitFor(); // log.addText("Executing:\n" + cmd); time1 = System.nanoTime(); exitValue = 0; } else { log.addText("Executing:\nreb2sac --target.encoding=dot --out=" + out + ".dot " + filename + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec("reb2sac --target.encoding=dot --out=" + out + ".dot " + theFile, null, work); } } else if (xhtml.isSelected()) { log.addText("Executing:\nreb2sac --target.encoding=xhtml --out=" + out + ".xhtml " + filename + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec("reb2sac --target.encoding=xhtml --out=" + out + ".xhtml " + theFile, null, work); } else if (usingSSA.isSelected()) { log.addText("Executing:\nreb2sac --target.encoding=ssa-with-user-update " + filename + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec("reb2sac --target.encoding=ssa-with-user-update " + theFile, null, work); } else { if (sim.equals("atacs")) { log.addText("Executing:\nreb2sac --target.encoding=hse2 " + filename + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec("reb2sac --target.encoding=hse2 " + theFile, null, work); } else if (sim.contains("markov-chain-analysis")) { time1 = System.nanoTime(); LhpnFile lhpnFile = null; if (modelFile.contains(".lpn")) { lhpnFile = new LhpnFile(); lhpnFile.load(root + separator + modelFile); } else { new File(filename.replace(".gcm", "").replace(".sbml", "").replace(".xml", "") + ".lpn").delete(); ArrayList<String> specs = new ArrayList<String>(); ArrayList<Object[]> conLevel = new ArrayList<Object[]>(); for (int i = 0; i < intSpecies.length; i++) { if (!intSpecies[i].equals("")) { String[] split = intSpecies[i].split(" "); if (split.length > 1) { String[] levels = split[1].split(","); if (levels.length > 0) { specs.add(split[0]); conLevel.add(levels); } } } } progress.setIndeterminate(true); GCMFile paramGCM = gcmEditor.getGCM(); GCMFile gcm = new GCMFile(root); gcm.load(root + separator + gcmEditor.getRefFile()); HashMap<String, Properties> elements = paramGCM.getSpecies(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.ID) && !prop.equals(GlobalConstants.TYPE)) { gcm.getSpecies().get(key) .put(prop, elements.get(key).get(prop)); } } } elements = paramGCM.getInfluences(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.PROMOTER) && !prop.equals(GlobalConstants.BIO) && !prop.equals(GlobalConstants.TYPE)) { gcm.getInfluences().get(key).put(prop, elements.get(key).get(prop)); } } } elements = paramGCM.getPromoters(); for (String key : elements.keySet()) { for (Object prop : elements.get(key).keySet()) { if (!prop.equals(GlobalConstants.NAME) && !prop.equals(GlobalConstants.ID)) { gcm.getPromoters().get(key).put(prop, elements.get(key).get(prop)); } } } HashMap<String, String> params = paramGCM.getGlobalParameters(); ArrayList<Object> remove = new ArrayList<Object>(); for (String key : params.keySet()) { gcm.setParameter(key, params.get(key)); remove.add(key); } if (direct != null && !direct.equals("")) { String[] d = direct.split("_"); ArrayList<String> dd = new ArrayList<String>(); for (int i = 0; i < d.length; i++) { if (!d[i].contains("=")) { String di = d[i]; while (!d[i].contains("=")) { i++; di += "_" + d[i]; } dd.add(di); } else { dd.add(d[i]); } } for (String di : dd) { if (di.contains("-")) { if (gcm.getPromoters().containsKey( di.split("=")[0].split("-")[0])) { Properties promoterProps = gcm.getPromoters().get( di.split("=")[0].split("-")[0]); promoterProps.put(di.split("=")[0].split("-")[1], di .split("=")[1]); } if (gcm.getSpecies() .containsKey(di.split("=")[0].split("-")[0])) { Properties speciesProps = gcm.getSpecies().get( di.split("=")[0].split("-")[0]); speciesProps.put(di.split("=")[0].split("-")[1], di .split("=")[1]); } String influence = ""; for (String infl : gcm.getInfluences().keySet()) { boolean matchInfl = true; for (String part : di.split("=")[0].split("-")[0] .split("_")) { if (!infl.contains(part)) { matchInfl = false; } } if (matchInfl) { influence = infl; } } if (!influence.equals("")) { Properties influenceProps = gcm.getInfluences().get( influence); influenceProps.put(di.split("=")[0].split("-")[1].replace( "\"", ""), di.split("=")[1]); } } else { if (gcm.getGlobalParameters().containsKey(di.split("=")[0])) { gcm.getGlobalParameters().put(di.split("=")[0], di.split("=")[1]); } if (gcm.getParameters().containsKey(di.split("=")[0])) { gcm.getParameters().put(di.split("=")[0], di.split("=")[1]); } } } } if (gcm.flattenGCM(false) != null) { time1 = System.nanoTime(); lhpnFile = gcm.convertToLHPN(specs, conLevel); if (lhpnFile == null) { return 0; } lhpnFile.save(filename.replace(".gcm", "").replace(".sbml", "") .replace(".xml", "") + ".lpn"); log.addText("Saving GCM file as LHPN:\n" + filename.replace(".gcm", "").replace(".sbml", "").replace( ".xml", "") + ".lpn" + "\n"); } else { return 0; } } // gcmEditor.getGCM().createLogicalModel( // filename.replace(".gcm", "").replace(".sbml", // "").replace(".xml", "") // + ".lpn", // log, // biomodelsim, // theFile.replace(".gcm", "").replace(".sbml", // "").replace(".xml", "") // + ".lpn"); // LHPNFile lhpnFile = new LHPNFile(); // while (new File(filename.replace(".gcm", // "").replace(".sbml", "").replace( // ".xml", "") // + ".lpn.temp").exists()) { // if (new File(filename.replace(".gcm", // "").replace(".sbml", "").replace(".xml", // + ".lpn").exists()) { // lhpnFile.load(filename.replace(".gcm", // "").replace(".sbml", "").replace( // ".xml", "") // + ".lpn"); if (lhpnFile != null) { sg = new StateGraph(lhpnFile); BuildStateGraphThread buildStateGraph = new BuildStateGraphThread(sg); buildStateGraph.start(); buildStateGraph.join(); if (sim.equals("steady-state-markov-chain-analysis")) { if (!sg.getStop()) { log.addText("Performing steady state Markov chain analysis.\n"); PerfromSteadyStateMarkovAnalysisThread performMarkovAnalysis = new PerfromSteadyStateMarkovAnalysisThread( sg); if (modelFile.contains(".lpn")) { performMarkovAnalysis.start(absError, null); } else { ArrayList<String> conditions = new ArrayList<String>(); for (int i = 0; i < gcmEditor.getGCM().getConditions().size(); i++) { if (gcmEditor.getGCM().getConditions().get(i).startsWith( "St")) { conditions.add(Translator .getProbpropExpression(gcmEditor.getGCM() .getConditions().get(i))); } } performMarkovAnalysis.start(absError, conditions); } performMarkovAnalysis.join(); if (!sg.getStop()) { String simrep = sg.getMarkovResults(); if (simrep != null) { FileOutputStream simrepstream = new FileOutputStream( new File(directory + separator + "sim-rep.txt")); simrepstream.write((simrep).getBytes()); simrepstream.close(); } sg.outputStateGraph(filename.replace(".gcm", "").replace( ".sbml", "").replace(".xml", "") + "_sg.dot", true); biomodelsim.enableTabMenu(biomodelsim.getTab() .getSelectedIndex()); } } } else if (sim.equals("transient-markov-chain-analysis")) { if (!sg.getStop()) { log .addText("Performing transient Markov chain analysis with uniformization.\n"); PerfromTransientMarkovAnalysisThread performMarkovAnalysis = new PerfromTransientMarkovAnalysisThread( sg, progress); time1 = System.nanoTime(); if (lpnProperty != null && !lpnProperty.equals("")) { performMarkovAnalysis.start(timeLimit, timeStep, printInterval, absError, Translator.getProbpropParts(Translator .getProbpropExpression(lpnProperty))); } else { performMarkovAnalysis.start(timeLimit, timeStep, printInterval, absError, null); } performMarkovAnalysis.join(); if (!sg.getStop()) { String simrep = sg.getMarkovResults(); if (simrep != null) { FileOutputStream simrepstream = new FileOutputStream( new File(directory + separator + "sim-rep.txt")); simrepstream.write((simrep).getBytes()); simrepstream.close(); } sg.outputStateGraph(filename.replace(".gcm", "").replace( ".sbml", "").replace(".xml", "") + "_sg.dot", true); if (sg.outputTSD(directory + separator + "percent-term-time.tsd")) { for (int i = 0; i < simTab.getComponentCount(); i++) { if (simTab.getComponentAt(i).getName().equals( "TSD Graph")) { if (simTab.getComponentAt(i) instanceof Graph) { ((Graph) simTab.getComponentAt(i)).refresh(); } } } } biomodelsim.enableTabMenu(biomodelsim.getTab() .getSelectedIndex()); } // String simrep = sg.getMarkovResults(); // if (simrep != null) { // FileOutputStream simrepstream = new // FileOutputStream(new File( // directory + separator + "sim-rep.txt")); // simrepstream.write((simrep).getBytes()); // simrepstream.close(); // sg.outputStateGraph(filename.replace(".gcm", // "").replace(".sbml", // "").replace(".xml", "") // + "_sg.dot", true); // biomodelsim.enableTabMenu(biomodelsim.getTab().getSelectedIndex()); } } // if (sg.getNumberOfStates() > 30) { // String[] options = { "Yes", "No" }; // int value = JOptionPane // .showOptionDialog( // BioSim.frame, // "The state graph contains more than 30 states and may not open well in dotty.\nOpen it with dotty anyway?", // "More Than 30 States", JOptionPane.YES_NO_OPTION, // JOptionPane.WARNING_MESSAGE, null, options, // options[0]); // if (value == JOptionPane.YES_OPTION) { // (System.getProperty("os.name").contentEquals("Linux")) // log.addText("Executing:\ndotty " // + filename.replace(".gcm", "").replace(".sbml", "") // .replace(".xml", "") + "_sg.dot" + "\n"); // exec.exec("dotty " // + theFile.replace(".gcm", "").replace(".sbml", // "").replace( // ".xml", "") + "_sg.dot", null, work); // else if // (System.getProperty("os.name").toLowerCase().startsWith( // "mac os")) { // log.addText("Executing:\nopen " // + filename.replace(".gcm", "").replace(".sbml", "") // .replace(".xml", "") + "_sg.dot" + "\n"); // exec.exec("open " // + theFile.replace(".gcm", "").replace(".sbml", // "").replace( // ".xml", "") + "_sg.dot", null, work); // else { // log.addText("Executing:\ndotty " // + filename.replace(".gcm", "").replace(".sbml", "") // .replace(".xml", "") + "_sg.dot" + "\n"); // exec.exec("dotty " // + theFile.replace(".gcm", "").replace(".sbml", // "").replace( // ".xml", "") + "_sg.dot", null, work); for (int i = 0; i < simTab.getComponentCount(); i++) { if (simTab.getComponentAt(i).getName().equals("ProbGraph")) { if (simTab.getComponentAt(i) instanceof Graph) { ((Graph) simTab.getComponentAt(i)).refresh(); } else { simTab .setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir .split(separator)[outDir .split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, false, false)); simTab.getComponentAt(i).setName("ProbGraph"); } } } } exitValue = 0; } else { Preferences biosimrc = Preferences.userRoot(); if (sim.equals("gillespieJava")) { time1 = System.nanoTime(); // Properties props = new Properties(); // props.load(new FileInputStream(new File(directory + // separator + modelFile.substring(0, // modelFile.indexOf('.')) + ".properties"))); int index = -1; for (int i = 0; i < simTab.getComponentCount(); i++) { if (simTab.getComponentAt(i).getName().equals("TSD Graph")) { simTab.setSelectedIndex(i); index = i; } } GillespieSSAJavaSingleStep javaSim = new GillespieSSAJavaSingleStep(); String SBMLFileName = directory + separator + theFile; javaSim.PerformSim(SBMLFileName, outDir, timeLimit, timeStep, rndSeed, ((Graph) simTab.getComponentAt(index))); exitValue = 0; return exitValue; } else if (biosimrc.get("biosim.sim.command", "").equals("")) { time1 = System.nanoTime(); log.addText("Executing:\nreb2sac --target.encoding=" + sim + " " + filename + "\n"); reb2sac = exec.exec("reb2sac --target.encoding=" + sim + " " + theFile, null, work); } else { String command = biosimrc.get("biosim.sim.command", ""); String fileStem = theFile.replaceAll(".xml", ""); fileStem = fileStem.replaceAll(".sbml", ""); command = command.replaceAll("filename", fileStem); command = command.replaceAll("sim", sim); log.addText(command + "\n"); time1 = System.nanoTime(); reb2sac = exec.exec(command, null, work); } } } String error = ""; try { InputStream reb = reb2sac.getInputStream(); InputStreamReader isr = new InputStreamReader(reb); BufferedReader br = new BufferedReader(isr); // int count = 0; String line; double time = 0; double oldTime = 0; int runNum = 0; int prog = 0; while ((line = br.readLine()) != null) { try { if (line.contains("Time")) { time = Double.parseDouble(line.substring(line.indexOf('=') + 1, line .length())); if (oldTime > time) { runNum++; } oldTime = time; time += (runNum * timeLimit); double d = ((time * 100) / runTime); String s = d + ""; double decimal = Double.parseDouble(s.substring(s.indexOf('.'), s .length())); if (decimal >= 0.5) { prog = (int) (Math.ceil(d)); } else { prog = (int) (d); } } } catch (Exception e) { } progress.setValue(prog); // if (steps > 0) { // count++; // progress.setValue(count); // log.addText(output); } InputStream reb2 = reb2sac.getErrorStream(); int read = reb2.read(); while (read != -1) { error += (char) read; read = reb2.read(); } br.close(); isr.close(); reb.close(); reb2.close(); } catch (Exception e) { } if (reb2sac != null) { exitValue = reb2sac.waitFor(); } long time2 = System.nanoTime(); long minutes; long hours; long days; double secs = ((time2 - time1) / 1000000000.0); long seconds = ((time2 - time1) / 1000000000); secs = secs - seconds; minutes = seconds / 60; secs = seconds % 60 + secs; hours = minutes / 60; minutes = minutes % 60; days = hours / 24; hours = hours % 60; String time; String dayLabel; String hourLabel; String minuteLabel; String secondLabel; if (days == 1) { dayLabel = " day "; } else { dayLabel = " days "; } if (hours == 1) { hourLabel = " hour "; } else { hourLabel = " hours "; } if (minutes == 1) { minuteLabel = " minute "; } else { minuteLabel = " minutes "; } if (seconds == 1) { secondLabel = " second"; } else { secondLabel = " seconds"; } if (days != 0) { time = days + dayLabel + hours + hourLabel + minutes + minuteLabel + secs + secondLabel; } else if (hours != 0) { time = hours + hourLabel + minutes + minuteLabel + secs + secondLabel; } else if (minutes != 0) { time = minutes + minuteLabel + secs + secondLabel; } else { time = secs + secondLabel; } if (!error.equals("")) { log.addText("Errors:\n" + error + "\n"); } log.addText("Total Simulation Time: " + time + " for " + simName + "\n\n"); if (exitValue != 0) { if (exitValue == 143) { JOptionPane.showMessageDialog(Gui.frame, "The simulation was" + " canceled by the user.", "Canceled Simulation", JOptionPane.ERROR_MESSAGE); } else if (exitValue == 139) { JOptionPane.showMessageDialog(Gui.frame, "The selected model is not a valid sbml file." + "\nYou must select an sbml file.", "Not An SBML File", JOptionPane.ERROR_MESSAGE); } else { JOptionPane.showMessageDialog(Gui.frame, "Error In Execution!\n" + "Bad Return Value!\n" + "The reb2sac program returned " + exitValue + " as an exit value.", "Error", JOptionPane.ERROR_MESSAGE); } } else { if (nary.isSelected() && gcmEditor == null && !lhpn.isSelected() && naryRun == 1) { } else if (sbml.isSelected()) { if (sbmlName != null && !sbmlName.trim().equals("")) { if (!biomodelsim.updateOpenSBML(sbmlName)) { biomodelsim.addTab(sbmlName, new SBML_Editor(root + separator + sbmlName, null, log, biomodelsim, null, null), "SBML Editor"); biomodelsim.addToTree(sbmlName); } else { biomodelsim.getTab().setSelectedIndex(biomodelsim.getTab(sbmlName)); } biomodelsim.enableTabMenu(biomodelsim.getTab().getSelectedIndex()); } } else if (lhpn.isSelected()) { if (lhpnName != null && !lhpnName.trim().equals("")) { if (!biomodelsim.updateOpenLHPN(lhpnName)) { biomodelsim.addTab(lhpnName, new LHPNEditor(root, lhpnName, null, biomodelsim, log), "LHPN Editor"); biomodelsim.addToTree(lhpnName); } else { biomodelsim.getTab().setSelectedIndex(biomodelsim.getTab(lhpnName)); } biomodelsim.enableTabMenu(biomodelsim.getTab().getSelectedIndex()); } } else if (dot.isSelected()) { if (System.getProperty("os.name").contentEquals("Linux")) { log.addText("Executing:\ndotty " + directory + out + ".dot" + "\n"); exec.exec("dotty " + out + ".dot", null, work); } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { log.addText("Executing:\nopen " + directory + out + ".dot\n"); exec.exec("open " + out + ".dot", null, work); } else { log.addText("Executing:\ndotty " + directory + out + ".dot" + "\n"); exec.exec("dotty " + out + ".dot", null, work); } } else if (xhtml.isSelected()) { if (System.getProperty("os.name").contentEquals("Linux")) { log.addText("Executing:\ngnome-open " + directory + out + ".xhtml" + "\n"); exec.exec("gnome-open " + out + ".xhtml", null, work); } else if (System.getProperty("os.name").toLowerCase().startsWith("mac os")) { log.addText("Executing:\nopen " + directory + out + ".xhtml" + "\n"); exec.exec("open " + out + ".xhtml", null, work); } else { log .addText("Executing:\ncmd /c start " + directory + out + ".xhtml" + "\n"); exec.exec("cmd /c start " + out + ".xhtml", null, work); } } else if (usingSSA.isSelected()) { if (!printer_id.equals("null.printer")) { for (int i = 0; i < simTab.getComponentCount(); i++) { if (simTab.getComponentAt(i).getName().equals("TSD Graph")) { if (simTab.getComponentAt(i) instanceof Graph) { boolean outputM = true; boolean outputV = true; boolean outputS = true; boolean outputTerm = false; boolean warning = false; int num = -1; String run = "run-1." + printer_id.substring(0, printer_id.length() - 8); for (String f : work.list()) { if (f.contains("mean")) { outputM = false; } else if (f.contains("variance")) { outputV = false; } else if (f.contains("standard_deviation")) { outputS = false; } else if (f.contains("run-")) { String getNumber = f.substring(4, f.length()); String number = ""; for (int j = 0; j < getNumber.length(); j++) { if (Character.isDigit(getNumber.charAt(j))) { number += getNumber.charAt(j); } else { break; } } if (num == -1) { num = Integer.parseInt(number); } else if (Integer.parseInt(number) < num) { num = Integer.parseInt(number); } run = "run-" + num + "." + printer_id.substring(0, printer_id.length() - 8); } else if (f.equals("term-time.txt")) { outputTerm = true; } } if (outputM) { ArrayList<ArrayList<Double>> mean = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "average", direct, warning); warning = ((Graph) simTab.getComponentAt(i)).getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), mean); p2.outputTSD(directory + separator + "mean.tsd"); } if (outputV) { ArrayList<ArrayList<Double>> var = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "variance", direct, warning); warning = ((Graph) simTab.getComponentAt(i)).getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), var); p2.outputTSD(directory + separator + "variance.tsd"); } if (outputS) { ArrayList<ArrayList<Double>> stddev = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "deviation", direct, warning); warning = ((Graph) simTab.getComponentAt(i)).getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), stddev); p2.outputTSD(directory + separator + "standard_deviation.tsd"); } if (outputTerm) { ArrayList<String> dataLabels = new ArrayList<String>(); dataLabels.add("time"); ArrayList<ArrayList<Double>> terms = new ArrayList<ArrayList<Double>>(); Scanner scan = new Scanner(new File(directory + separator + "term-time.txt")); while (scan.hasNextLine()) { String line = scan.nextLine(); String[] term = line.split(" "); if (!dataLabels.contains(term[0])) { dataLabels.add(term[0]); ArrayList<Double> times = new ArrayList<Double>(); times.add(Double.parseDouble(term[1])); terms.add(times); } else { terms.get(dataLabels.indexOf(term[0]) - 1).add( Double.parseDouble(term[1])); } } scan.close(); ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> percentData = new ArrayList<ArrayList<Double>>(); for (int j = 0; j < dataLabels.size(); j++) { ArrayList<Double> temp = new ArrayList<Double>(); temp.add(0.0); data.add(temp); temp = new ArrayList<Double>(); temp.add(0.0); percentData.add(temp); } for (double j = printInterval; j <= timeLimit; j += printInterval) { data.get(0).add(j); percentData.get(0).add(j); for (int k = 1; k < dataLabels.size(); k++) { data.get(k).add( data.get(k).get(data.get(k).size() - 1)); percentData.get(k).add( percentData.get(k).get( percentData.get(k).size() - 1)); for (int l = terms.get(k - 1).size() - 1; l >= 0; l if (terms.get(k - 1).get(l) < j) { data .get(k) .set( data.get(k).size() - 1, data .get(k) .get( data .get( k) .size() - 1) + 1); percentData.get(k).set( percentData.get(k).size() - 1, ((data.get(k).get(data.get(k) .size() - 1)) * 100) / runs); terms.get(k - 1).remove(l); } } } } Parser probData = new Parser(dataLabels, data); probData.outputTSD(directory + separator + "term-time.tsd"); probData = new Parser(dataLabels, percentData); probData.outputTSD(directory + separator + "percent-term-time.tsd"); } ((Graph) simTab.getComponentAt(i)).refresh(); } else { simTab .setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir .split(separator)[outDir .split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, true, false)); boolean outputM = true; boolean outputV = true; boolean outputS = true; boolean outputTerm = false; boolean warning = false; int num = -1; String run = "run-1." + printer_id.substring(0, printer_id.length() - 8); for (String f : work.list()) { if (f.contains("mean")) { outputM = false; } else if (f.contains("variance")) { outputV = false; } else if (f.contains("standard_deviation")) { outputS = false; } else if (f.contains("run-")) { String getNumber = f.substring(4, f.length()); String number = ""; for (int j = 0; j < getNumber.length(); j++) { if (Character.isDigit(getNumber.charAt(j))) { number += getNumber.charAt(j); } else { break; } } if (num == -1) { num = Integer.parseInt(number); } else if (Integer.parseInt(number) < num) { num = Integer.parseInt(number); } run = "run-" + num + "." + printer_id.substring(0, printer_id.length() - 8); } else if (f.equals("term-time.txt")) { outputTerm = true; } } if (outputM) { ArrayList<ArrayList<Double>> mean = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "average", direct, warning); warning = ((Graph) simTab.getComponentAt(i)).getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), mean); p2.outputTSD(directory + separator + "mean.tsd"); } if (outputV) { ArrayList<ArrayList<Double>> var = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "variance", direct, warning); warning = ((Graph) simTab.getComponentAt(i)).getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), var); p2.outputTSD(directory + separator + "variance.tsd"); } if (outputS) { ArrayList<ArrayList<Double>> stddev = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "deviation", direct, warning); warning = ((Graph) simTab.getComponentAt(i)).getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), stddev); p2.outputTSD(directory + separator + "standard_deviation.tsd"); } if (outputTerm) { ArrayList<String> dataLabels = new ArrayList<String>(); dataLabels.add("time"); ArrayList<ArrayList<Double>> terms = new ArrayList<ArrayList<Double>>(); Scanner scan = new Scanner(new File(directory + separator + "term-time.txt")); while (scan.hasNextLine()) { String line = scan.nextLine(); String[] term = line.split(" "); if (!dataLabels.contains(term[0])) { dataLabels.add(term[0]); ArrayList<Double> times = new ArrayList<Double>(); times.add(Double.parseDouble(term[1])); terms.add(times); } else { terms.get(dataLabels.indexOf(term[0]) - 1).add( Double.parseDouble(term[1])); } } scan.close(); ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> percentData = new ArrayList<ArrayList<Double>>(); for (int j = 0; j < dataLabels.size(); j++) { ArrayList<Double> temp = new ArrayList<Double>(); temp.add(0.0); data.add(temp); temp = new ArrayList<Double>(); temp.add(0.0); percentData.add(temp); } for (double j = printInterval; j <= timeLimit; j += printInterval) { data.get(0).add(j); percentData.get(0).add(j); for (int k = 1; k < dataLabels.size(); k++) { data.get(k).add( data.get(k).get(data.get(k).size() - 1)); percentData.get(k).add( percentData.get(k).get( percentData.get(k).size() - 1)); for (int l = terms.get(k - 1).size() - 1; l >= 0; l if (terms.get(k - 1).get(l) < j) { data .get(k) .set( data.get(k).size() - 1, data .get(k) .get( data .get( k) .size() - 1) + 1); percentData.get(k).set( percentData.get(k).size() - 1, ((data.get(k).get(data.get(k) .size() - 1)) * 100) / runs); terms.get(k - 1).remove(l); } } } } Parser probData = new Parser(dataLabels, data); probData.outputTSD(directory + separator + "term-time.tsd"); probData = new Parser(dataLabels, percentData); probData.outputTSD(directory + separator + "percent-term-time.tsd"); } simTab.getComponentAt(i).setName("TSD Graph"); } } if (simTab.getComponentAt(i).getName().equals("ProbGraph")) { if (simTab.getComponentAt(i) instanceof Graph) { ((Graph) simTab.getComponentAt(i)).refresh(); } else { if (new File(filename.substring(0, filename.length() - filename.split(separator)[filename .split(separator).length - 1].length()) + "sim-rep.txt").exists()) { simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir.split(separator)[outDir .split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, false, false)); simTab.getComponentAt(i).setName("ProbGraph"); } } } } } } else if (sim.equals("atacs")) { log.addText("Executing:\natacs -T0.000001 -oqoflhsgllvA " + filename .substring(0, filename.length() - filename.split(separator)[filename .split(separator).length - 1].length()) + "out.hse\n"); exec.exec("atacs -T0.000001 -oqoflhsgllvA out.hse", null, work); for (int i = 0; i < simTab.getComponentCount(); i++) { if (simTab.getComponentAt(i).getName().equals("ProbGraph")) { if (simTab.getComponentAt(i) instanceof Graph) { ((Graph) simTab.getComponentAt(i)).refresh(); } else { simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir.split(separator)[outDir.split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, false, false)); simTab.getComponentAt(i).setName("ProbGraph"); } } } // simTab.add("Probability Graph", new // Graph(printer_track_quantity, // outDir.split(separator)[outDir.split(separator).length - // simulation results", // printer_id, outDir, "time", biomodelsim, null, log, null, // false)); // simTab.getComponentAt(simTab.getComponentCount() - // 1).setName("ProbGraph"); } else { if (!printer_id.equals("null.printer")) { if (ode.isSelected()) { for (int i = 0; i < simTab.getComponentCount(); i++) { if (simTab.getComponentAt(i).getName().equals("TSD Graph")) { if (simTab.getComponentAt(i) instanceof Graph) { boolean outputM = true; boolean outputV = true; boolean outputS = true; boolean outputTerm = false; boolean warning = false; int num = -1; String run = "run-1." + printer_id.substring(0, printer_id.length() - 8); for (String f : work.list()) { if (f.contains("mean")) { outputM = false; } else if (f.contains("variance")) { outputV = false; } else if (f.contains("standard_deviation")) { outputS = false; } else if (f.contains("run-")) { String getNumber = f.substring(4, f.length()); String number = ""; for (int j = 0; j < getNumber.length(); j++) { if (Character.isDigit(getNumber.charAt(j))) { number += getNumber.charAt(j); } else { break; } } if (num == -1) { num = Integer.parseInt(number); } else if (Integer.parseInt(number) < num) { num = Integer.parseInt(number); } run = "run-" + num + "." + printer_id.substring(0, printer_id .length() - 8); } else if (f.equals("term-time.txt")) { outputTerm = true; } } if (outputM) { ArrayList<ArrayList<Double>> mean = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "average", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), mean); p2.outputTSD(directory + separator + "mean.tsd"); } if (outputV) { ArrayList<ArrayList<Double>> var = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "variance", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), var); p2.outputTSD(directory + separator + "variance.tsd"); } if (outputS) { ArrayList<ArrayList<Double>> stddev = ((Graph) simTab .getComponentAt(i)) .readData(directory + separator + run, "deviation", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), stddev); p2.outputTSD(directory + separator + "standard_deviation.tsd"); } if (outputTerm) { ArrayList<String> dataLabels = new ArrayList<String>(); dataLabels.add("time"); ArrayList<ArrayList<Double>> terms = new ArrayList<ArrayList<Double>>(); Scanner scan = new Scanner(new File(directory + separator + "term-time.txt")); while (scan.hasNextLine()) { String line = scan.nextLine(); String[] term = line.split(" "); if (!dataLabels.contains(term[0])) { dataLabels.add(term[0]); ArrayList<Double> times = new ArrayList<Double>(); times.add(Double.parseDouble(term[1])); terms.add(times); } else { terms.get(dataLabels.indexOf(term[0]) - 1).add( Double.parseDouble(term[1])); } } scan.close(); ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> percentData = new ArrayList<ArrayList<Double>>(); for (int j = 0; j < dataLabels.size(); j++) { ArrayList<Double> temp = new ArrayList<Double>(); temp.add(0.0); data.add(temp); temp = new ArrayList<Double>(); temp.add(0.0); percentData.add(temp); } for (double j = printInterval; j <= timeLimit; j += printInterval) { data.get(0).add(j); percentData.get(0).add(j); for (int k = 1; k < dataLabels.size(); k++) { data .get(k) .add( data.get(k).get( data.get(k).size() - 1)); percentData.get(k).add( percentData.get(k).get( percentData.get(k).size() - 1)); for (int l = terms.get(k - 1).size() - 1; l >= 0; l if (terms.get(k - 1).get(l) < j) { data .get(k) .set( data.get(k).size() - 1, data .get(k) .get( data .get( k) .size() - 1) + 1); percentData.get(k).set( percentData.get(k).size() - 1, ((data.get(k).get(data.get(k) .size() - 1)) * 100) / runs); terms.get(k - 1).remove(l); } } } } Parser probData = new Parser(dataLabels, data); probData.outputTSD(directory + separator + "term-time.tsd"); probData = new Parser(dataLabels, percentData); probData.outputTSD(directory + separator + "percent-term-time.tsd"); } ((Graph) simTab.getComponentAt(i)).refresh(); } else { simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir.split(separator)[outDir .split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, true, false)); boolean outputM = true; boolean outputV = true; boolean outputS = true; boolean outputTerm = false; boolean warning = false; int num = -1; String run = "run-1." + printer_id.substring(0, printer_id.length() - 8); for (String f : work.list()) { if (f.contains("mean")) { outputM = false; } else if (f.contains("variance")) { outputV = false; } else if (f.contains("standard_deviation")) { outputS = false; } else if (f.contains("run-")) { String getNumber = f.substring(4, f.length()); String number = ""; for (int j = 0; j < getNumber.length(); j++) { if (Character.isDigit(getNumber.charAt(j))) { number += getNumber.charAt(j); } else { break; } } if (num == -1) { num = Integer.parseInt(number); } else if (Integer.parseInt(number) < num) { num = Integer.parseInt(number); } run = "run-" + num + "." + printer_id.substring(0, printer_id .length() - 8); } else if (f.equals("term-time.txt")) { outputTerm = true; } } if (outputM) { ArrayList<ArrayList<Double>> mean = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "average", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), mean); p2.outputTSD(directory + separator + "mean.tsd"); } if (outputV) { ArrayList<ArrayList<Double>> var = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "variance", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), var); p2.outputTSD(directory + separator + "variance.tsd"); } if (outputS) { ArrayList<ArrayList<Double>> stddev = ((Graph) simTab .getComponentAt(i)) .readData(directory + separator + run, "deviation", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), stddev); p2.outputTSD(directory + separator + "standard_deviation.tsd"); } if (outputTerm) { ArrayList<String> dataLabels = new ArrayList<String>(); dataLabels.add("time"); ArrayList<ArrayList<Double>> terms = new ArrayList<ArrayList<Double>>(); Scanner scan = new Scanner(new File(directory + separator + "term-time.txt")); while (scan.hasNextLine()) { String line = scan.nextLine(); String[] term = line.split(" "); if (!dataLabels.contains(term[0])) { dataLabels.add(term[0]); ArrayList<Double> times = new ArrayList<Double>(); times.add(Double.parseDouble(term[1])); terms.add(times); } else { terms.get(dataLabels.indexOf(term[0]) - 1).add( Double.parseDouble(term[1])); } } scan.close(); ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> percentData = new ArrayList<ArrayList<Double>>(); for (int j = 0; j < dataLabels.size(); j++) { ArrayList<Double> temp = new ArrayList<Double>(); temp.add(0.0); data.add(temp); temp = new ArrayList<Double>(); temp.add(0.0); percentData.add(temp); } for (double j = printInterval; j <= timeLimit; j += printInterval) { data.get(0).add(j); percentData.get(0).add(j); for (int k = 1; k < dataLabels.size(); k++) { data .get(k) .add( data.get(k).get( data.get(k).size() - 1)); percentData.get(k).add( percentData.get(k).get( percentData.get(k).size() - 1)); for (int l = terms.get(k - 1).size() - 1; l >= 0; l if (terms.get(k - 1).get(l) < j) { data .get(k) .set( data.get(k).size() - 1, data .get(k) .get( data .get( k) .size() - 1) + 1); percentData.get(k).set( percentData.get(k).size() - 1, ((data.get(k).get(data.get(k) .size() - 1)) * 100) / runs); terms.get(k - 1).remove(l); } } } } Parser probData = new Parser(dataLabels, data); probData.outputTSD(directory + separator + "term-time.tsd"); probData = new Parser(dataLabels, percentData); probData.outputTSD(directory + separator + "percent-term-time.tsd"); } simTab.getComponentAt(i).setName("TSD Graph"); } } if (simTab.getComponentAt(i).getName().equals("ProbGraph")) { if (simTab.getComponentAt(i) instanceof Graph) { ((Graph) simTab.getComponentAt(i)).refresh(); } else { if (new File(filename.substring(0, filename.length() - filename.split(separator)[filename .split(separator).length - 1].length()) + "sim-rep.txt").exists()) { simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir .split(separator)[outDir .split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, false, false)); simTab.getComponentAt(i).setName("ProbGraph"); } } } } } else if (monteCarlo.isSelected()) { for (int i = 0; i < simTab.getComponentCount(); i++) { if (simTab.getComponentAt(i).getName().equals("TSD Graph")) { if (simTab.getComponentAt(i) instanceof Graph) { boolean outputM = true; boolean outputV = true; boolean outputS = true; boolean outputTerm = false; boolean warning = false; int num = -1; String run = "run-1." + printer_id.substring(0, printer_id.length() - 8); for (String f : work.list()) { if (f.contains("mean")) { outputM = false; } else if (f.contains("variance")) { outputV = false; } else if (f.contains("standard_deviation")) { outputS = false; } else if (f.contains("run-")) { String getNumber = f.substring(4, f.length()); String number = ""; for (int j = 0; j < getNumber.length(); j++) { if (Character.isDigit(getNumber.charAt(j))) { number += getNumber.charAt(j); } else { break; } } if (num == -1) { num = Integer.parseInt(number); } else if (Integer.parseInt(number) < num) { num = Integer.parseInt(number); } run = "run-" + num + "." + printer_id.substring(0, printer_id .length() - 8); } else if (f.equals("term-time.txt")) { outputTerm = true; } } if (outputM) { ArrayList<ArrayList<Double>> mean = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "average", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), mean); p2.outputTSD(directory + separator + "mean.tsd"); } if (outputV) { ArrayList<ArrayList<Double>> var = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "variance", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), var); p2.outputTSD(directory + separator + "variance.tsd"); } if (outputS) { ArrayList<ArrayList<Double>> stddev = ((Graph) simTab .getComponentAt(i)) .readData(directory + separator + run, "deviation", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), stddev); p2.outputTSD(directory + separator + "standard_deviation.tsd"); } if (outputTerm) { ArrayList<String> dataLabels = new ArrayList<String>(); dataLabels.add("time"); ArrayList<ArrayList<Double>> terms = new ArrayList<ArrayList<Double>>(); Scanner scan = new Scanner(new File(directory + separator + "term-time.txt")); while (scan.hasNextLine()) { String line = scan.nextLine(); String[] term = line.split(" "); if (!dataLabels.contains(term[0])) { dataLabels.add(term[0]); ArrayList<Double> times = new ArrayList<Double>(); times.add(Double.parseDouble(term[1])); terms.add(times); } else { terms.get(dataLabels.indexOf(term[0]) - 1).add( Double.parseDouble(term[1])); } } scan.close(); ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> percentData = new ArrayList<ArrayList<Double>>(); for (int j = 0; j < dataLabels.size(); j++) { ArrayList<Double> temp = new ArrayList<Double>(); temp.add(0.0); data.add(temp); temp = new ArrayList<Double>(); temp.add(0.0); percentData.add(temp); } for (double j = printInterval; j <= timeLimit; j += printInterval) { data.get(0).add(j); percentData.get(0).add(j); for (int k = 1; k < dataLabels.size(); k++) { data .get(k) .add( data.get(k).get( data.get(k).size() - 1)); percentData.get(k).add( percentData.get(k).get( percentData.get(k).size() - 1)); for (int l = terms.get(k - 1).size() - 1; l >= 0; l if (terms.get(k - 1).get(l) < j) { data .get(k) .set( data.get(k).size() - 1, data .get(k) .get( data .get( k) .size() - 1) + 1); percentData.get(k).set( percentData.get(k).size() - 1, ((data.get(k).get(data.get(k) .size() - 1)) * 100) / runs); terms.get(k - 1).remove(l); } } } } Parser probData = new Parser(dataLabels, data); probData.outputTSD(directory + separator + "term-time.tsd"); probData = new Parser(dataLabels, percentData); probData.outputTSD(directory + separator + "percent-term-time.tsd"); } ((Graph) simTab.getComponentAt(i)).refresh(); } else { simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir.split(separator)[outDir .split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, true, false)); boolean outputM = true; boolean outputV = true; boolean outputS = true; boolean outputTerm = false; boolean warning = false; int num = -1; String run = "run-1." + printer_id.substring(0, printer_id.length() - 8); for (String f : work.list()) { if (f.contains("mean")) { outputM = false; } else if (f.contains("variance")) { outputV = false; } else if (f.contains("standard_deviation")) { outputS = false; } else if (f.contains("run-")) { String getNumber = f.substring(4, f.length()); String number = ""; for (int j = 0; j < getNumber.length(); j++) { if (Character.isDigit(getNumber.charAt(j))) { number += getNumber.charAt(j); } else { break; } } if (num == -1) { num = Integer.parseInt(number); } else if (Integer.parseInt(number) < num) { num = Integer.parseInt(number); } run = "run-" + num + "." + printer_id.substring(0, printer_id .length() - 8); } else if (f.equals("term-time.txt")) { outputTerm = true; } } if (outputM) { ArrayList<ArrayList<Double>> mean = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "average", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), mean); p2.outputTSD(directory + separator + "mean.tsd"); } if (outputV) { ArrayList<ArrayList<Double>> var = ((Graph) simTab .getComponentAt(i)).readData(directory + separator + run, "variance", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), var); p2.outputTSD(directory + separator + "variance.tsd"); } if (outputS) { ArrayList<ArrayList<Double>> stddev = ((Graph) simTab .getComponentAt(i)) .readData(directory + separator + run, "deviation", direct, warning); warning = ((Graph) simTab.getComponentAt(i)) .getWarning(); Parser p = new TSDParser(directory + separator + run, warning); warning = p.getWarning(); Parser p2 = new Parser(p.getSpecies(), stddev); p2.outputTSD(directory + separator + "standard_deviation.tsd"); } if (outputTerm) { ArrayList<String> dataLabels = new ArrayList<String>(); dataLabels.add("time"); ArrayList<ArrayList<Double>> terms = new ArrayList<ArrayList<Double>>(); Scanner scan = new Scanner(new File(directory + separator + "term-time.txt")); while (scan.hasNextLine()) { String line = scan.nextLine(); String[] term = line.split(" "); if (!dataLabels.contains(term[0])) { dataLabels.add(term[0]); ArrayList<Double> times = new ArrayList<Double>(); times.add(Double.parseDouble(term[1])); terms.add(times); } else { terms.get(dataLabels.indexOf(term[0]) - 1).add( Double.parseDouble(term[1])); } } scan.close(); ArrayList<ArrayList<Double>> data = new ArrayList<ArrayList<Double>>(); ArrayList<ArrayList<Double>> percentData = new ArrayList<ArrayList<Double>>(); for (int j = 0; j < dataLabels.size(); j++) { ArrayList<Double> temp = new ArrayList<Double>(); temp.add(0.0); data.add(temp); temp = new ArrayList<Double>(); temp.add(0.0); percentData.add(temp); } for (double j = printInterval; j <= timeLimit; j += printInterval) { data.get(0).add(j); percentData.get(0).add(j); for (int k = 1; k < dataLabels.size(); k++) { data .get(k) .add( data.get(k).get( data.get(k).size() - 1)); percentData.get(k).add( percentData.get(k).get( percentData.get(k).size() - 1)); for (int l = terms.get(k - 1).size() - 1; l >= 0; l if (terms.get(k - 1).get(l) < j) { data .get(k) .set( data.get(k).size() - 1, data .get(k) .get( data .get( k) .size() - 1) + 1); percentData.get(k).set( percentData.get(k).size() - 1, ((data.get(k).get(data.get(k) .size() - 1)) * 100) / runs); terms.get(k - 1).remove(l); } } } } Parser probData = new Parser(dataLabels, data); probData.outputTSD(directory + separator + "term-time.tsd"); probData = new Parser(dataLabels, percentData); probData.outputTSD(directory + separator + "percent-term-time.tsd"); } simTab.getComponentAt(i).setName("TSD Graph"); } } if (simTab.getComponentAt(i).getName().equals("ProbGraph")) { if (simTab.getComponentAt(i) instanceof Graph) { ((Graph) simTab.getComponentAt(i)).refresh(); } else { if (new File(filename.substring(0, filename.length() - filename.split(separator)[filename .split(separator).length - 1].length()) + "sim-rep.txt").exists()) { simTab.setComponentAt(i, new Graph(r2s, printer_track_quantity, outDir .split(separator)[outDir .split(separator).length - 1] + " simulation results", printer_id, outDir, "time", biomodelsim, null, log, null, false, false)); simTab.getComponentAt(i).setName("ProbGraph"); } } } } } } } } } catch (InterruptedException e1) { JOptionPane.showMessageDialog(Gui.frame, "Error In Execution!", "Error In Execution", JOptionPane.ERROR_MESSAGE); e1.printStackTrace(); } catch (IOException e1) { JOptionPane.showMessageDialog(Gui.frame, "File I/O Error!", "File I/O Error", JOptionPane.ERROR_MESSAGE); e1.printStackTrace(); } return exitValue; } /** * This method is called if a button that cancels the simulation is pressed. */ public void actionPerformed(ActionEvent e) { if (reb2sac != null) { reb2sac.destroy(); } if (sg != null) { sg.stop(); } } }
package com.hubspot.singularity.scheduler; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.ws.rs.WebApplicationException; import org.apache.mesos.Protos.SlaveID; import org.apache.mesos.Protos.TaskState; import org.junit.Assert; import org.junit.Test; import com.google.common.base.Optional; import com.google.common.collect.ImmutableMap; import com.google.inject.Inject; import com.hubspot.mesos.json.MesosFrameworkObject; import com.hubspot.mesos.json.MesosMasterSlaveObject; import com.hubspot.mesos.json.MesosMasterStateObject; import com.hubspot.mesos.json.MesosResourcesObject; import com.hubspot.singularity.MachineState; import com.hubspot.singularity.SingularityMachineStateHistoryUpdate; import com.hubspot.singularity.SingularitySlave; import com.hubspot.singularity.SingularityTask; import com.hubspot.singularity.SlavePlacement; import com.hubspot.singularity.TaskCleanupType; import com.hubspot.singularity.api.SingularityMachineChangeRequest; import com.hubspot.singularity.data.AbstractMachineManager.StateChangeResult; import com.hubspot.singularity.mesos.SingularitySlaveAndRackManager; import com.hubspot.singularity.resources.SlaveResource; public class SingularityMachineStatesTest extends SingularitySchedulerTestBase { @Inject protected SingularitySlaveReconciliationPoller slaveReconciliationPoller; @Inject private SingularitySlaveAndRackManager singularitySlaveAndRackManager; @Inject private SlaveResource slaveResource; public SingularityMachineStatesTest() { super(false); } @Test public void testDeadSlavesArePurged() { SingularitySlave liveSlave = new SingularitySlave("1", "h1", "r1", ImmutableMap.of("uniqueAttribute", "1"), Optional.absent()); SingularitySlave deadSlave = new SingularitySlave("2", "h1", "r1", ImmutableMap.of("uniqueAttribute", "2"), Optional.absent()); final long now = System.currentTimeMillis(); liveSlave = liveSlave.changeState(new SingularityMachineStateHistoryUpdate("1", MachineState.ACTIVE, 100, Optional.absent(), Optional.absent())); deadSlave = deadSlave.changeState(new SingularityMachineStateHistoryUpdate("2", MachineState.DEAD, now - TimeUnit.HOURS.toMillis(10), Optional.absent(), Optional.absent())); slaveManager.saveObject(liveSlave); slaveManager.saveObject(deadSlave); slaveReconciliationPoller.runActionOnPoll(); Assert.assertEquals(1, slaveManager.getObjectsFiltered(MachineState.ACTIVE).size()); Assert.assertEquals(1, slaveManager.getObjectsFiltered(MachineState.DEAD).size()); configuration.setDeleteDeadSlavesAfterHours(1); slaveReconciliationPoller.runActionOnPoll(); Assert.assertEquals(1, slaveManager.getObjectsFiltered(MachineState.ACTIVE).size()); Assert.assertEquals(0, slaveManager.getObjectsFiltered(MachineState.DEAD).size()); } @Test public void testBasicSlaveAndRackState() { sms.resourceOffers(driver, Arrays.asList(createOffer(1, 1, "slave1", "host1", Optional.of("rack1")))); sms.resourceOffers(driver, Arrays.asList(createOffer(1, 1, "slave2", "host2", Optional.of("rack2")))); sms.resourceOffers(driver, Arrays.asList(createOffer(1, 1, "slave1", "host1", Optional.of("rack1")))); Assert.assertEquals(1, slaveManager.getHistory("slave1").size()); Assert.assertTrue(slaveManager.getNumObjectsAtState(MachineState.ACTIVE) == 2); Assert.assertTrue(rackManager.getNumObjectsAtState(MachineState.ACTIVE) == 2); Assert.assertTrue(slaveManager.getObject("slave1").get().getCurrentState().equals(slaveManager.getHistory("slave1").get(0))); sms.slaveLost(driver, SlaveID.newBuilder().setValue("slave1").build()); Assert.assertTrue(slaveManager.getNumObjectsAtState(MachineState.ACTIVE) == 1); Assert.assertTrue(rackManager.getNumObjectsAtState(MachineState.ACTIVE) == 1); Assert.assertTrue(slaveManager.getNumObjectsAtState(MachineState.DEAD) == 1); Assert.assertTrue(rackManager.getNumObjectsAtState(MachineState.DEAD) == 1); Assert.assertTrue(slaveManager.getObject("slave1").get().getCurrentState().getState() == MachineState.DEAD); Assert.assertTrue(rackManager.getObject("rack1").get().getCurrentState().getState() == MachineState.DEAD); sms.resourceOffers(driver, Arrays.asList(createOffer(1, 1, "slave3", "host3", Optional.of("rack1")))); Assert.assertTrue(slaveManager.getNumObjectsAtState(MachineState.ACTIVE) == 2); Assert.assertEquals(2, rackManager.getNumObjectsAtState(MachineState.ACTIVE)); Assert.assertTrue(slaveManager.getNumObjectsAtState(MachineState.DEAD) == 1); Assert.assertTrue(rackManager.getHistory("rack1").size() == 3); sms.resourceOffers(driver, Arrays.asList(createOffer(1, 1, "slave1", "host1", Optional.of("rack1")))); Assert.assertTrue(slaveManager.getNumObjectsAtState(MachineState.ACTIVE) == 3); Assert.assertTrue(rackManager.getNumObjectsAtState(MachineState.ACTIVE) == 2); sms.slaveLost(driver, SlaveID.newBuilder().setValue("slave1").build()); Assert.assertTrue(slaveManager.getNumObjectsAtState(MachineState.ACTIVE) == 2); Assert.assertTrue(rackManager.getNumObjectsAtState(MachineState.ACTIVE) == 2); Assert.assertTrue(slaveManager.getNumObjectsAtState(MachineState.DEAD) == 1); Assert.assertTrue(slaveManager.getHistory("slave1").size() == 4); sms.slaveLost(driver, SlaveID.newBuilder().setValue("slave1").build()); Assert.assertTrue(slaveManager.getNumObjectsAtState(MachineState.ACTIVE) == 2); Assert.assertTrue(rackManager.getNumObjectsAtState(MachineState.ACTIVE) == 2); Assert.assertTrue(slaveManager.getNumObjectsAtState(MachineState.DEAD) == 1); Assert.assertTrue(slaveManager.getHistory("slave1").size() == 4); slaveManager.deleteObject("slave1"); Assert.assertTrue(slaveManager.getNumObjectsAtState(MachineState.DEAD) == 0); Assert.assertTrue(slaveManager.getNumObjectsAtState(MachineState.ACTIVE) == 2); Assert.assertTrue(slaveManager.getHistory("slave1").isEmpty()); } @Test public void testDecommissioning() { initRequest(); initFirstDeploy(); saveAndSchedule(request.toBuilder().setInstances(Optional.of(2))); scheduler.drainPendingQueue(stateCacheProvider.get()); sms.resourceOffers(driver, Arrays.asList(createOffer(1, 129, "slave1", "host1", Optional.of("rack1")))); sms.resourceOffers(driver, Arrays.asList(createOffer(1, 129, "slave2", "host2", Optional.of("rack1")))); sms.resourceOffers(driver, Arrays.asList(createOffer(1, 129, "slave3", "host3", Optional.of("rack2")))); sms.resourceOffers(driver, Arrays.asList(createOffer(1, 129, "slave4", "host4", Optional.of("rack2")))); for (SingularityTask task : taskManager.getTasksOnSlave(taskManager.getActiveTaskIds(), slaveManager.getObject("slave1").get())) { statusUpdate(task, TaskState.TASK_RUNNING); } for (SingularityTask task : taskManager.getTasksOnSlave(taskManager.getActiveTaskIds(), slaveManager.getObject("slave2").get())) { statusUpdate(task, TaskState.TASK_RUNNING); } Assert.assertTrue(rackManager.getNumObjectsAtState(MachineState.ACTIVE) == 2); Assert.assertTrue(slaveManager.getNumObjectsAtState(MachineState.ACTIVE) == 4); Assert.assertTrue(taskManager.getTasksOnSlave(taskManager.getActiveTaskIds(), slaveManager.getObject("slave1").get()).size() == 1); Assert.assertTrue(taskManager.getTasksOnSlave(taskManager.getActiveTaskIds(), slaveManager.getObject("slave2").get()).size() == 1); Assert.assertTrue(taskManager.getTasksOnSlave(taskManager.getActiveTaskIds(), slaveManager.getObject("slave3").get()).isEmpty()); Assert.assertTrue(taskManager.getTasksOnSlave(taskManager.getActiveTaskIds(), slaveManager.getObject("slave4").get()).isEmpty()); Assert.assertEquals(StateChangeResult.SUCCESS, slaveManager.changeState("slave1", MachineState.STARTING_DECOMMISSION, Optional.absent(), Optional.of("user1"))); Assert.assertEquals(StateChangeResult.FAILURE_ALREADY_AT_STATE, slaveManager.changeState("slave1", MachineState.STARTING_DECOMMISSION, Optional.absent(), Optional.of("user1"))); Assert.assertEquals(StateChangeResult.FAILURE_NOT_FOUND, slaveManager.changeState("slave9231", MachineState.STARTING_DECOMMISSION, Optional.absent(), Optional.of("user1"))); Assert.assertEquals(MachineState.STARTING_DECOMMISSION, slaveManager.getObject("slave1").get().getCurrentState().getState()); Assert.assertTrue(slaveManager.getObject("slave1").get().getCurrentState().getUser().get().equals("user1")); saveAndSchedule(request.toBuilder().setInstances(Optional.of(3))); sms.resourceOffers(driver, Arrays.asList(createOffer(1, 129, "slave1", "host1", Optional.of("rack1")))); Assert.assertTrue(taskManager.getTasksOnSlave(taskManager.getActiveTaskIds(), slaveManager.getObject("slave1").get()).size() == 1); Assert.assertTrue(slaveManager.getObject("slave1").get().getCurrentState().getState() == MachineState.DECOMMISSIONING); Assert.assertTrue(slaveManager.getObject("slave1").get().getCurrentState().getUser().get().equals("user1")); cleaner.drainCleanupQueue(); Assert.assertTrue(slaveManager.getObject("slave1").get().getCurrentState().getState() == MachineState.DECOMMISSIONING); Assert.assertTrue(slaveManager.getObject("slave1").get().getCurrentState().getUser().get().equals("user1")); sms.resourceOffers(driver, Arrays.asList(createOffer(1, 129, "slave4", "host4", Optional.of("rack2")))); sms.resourceOffers(driver, Arrays.asList(createOffer(1, 129, "slave3", "host3", Optional.of("rack2")))); for (SingularityTask task : taskManager.getTasksOnSlave(taskManager.getActiveTaskIds(), slaveManager.getObject("slave4").get())) { statusUpdate(task, TaskState.TASK_RUNNING); } for (SingularityTask task : taskManager.getTasksOnSlave(taskManager.getActiveTaskIds(), slaveManager.getObject("slave3").get())) { statusUpdate(task, TaskState.TASK_RUNNING); } // all task should have moved. cleaner.drainCleanupQueue(); Assert.assertTrue(taskManager.getTasksOnSlave(taskManager.getActiveTaskIds(), slaveManager.getObject("slave4").get()).size() == 1); Assert.assertTrue(taskManager.getTasksOnSlave(taskManager.getActiveTaskIds(), slaveManager.getObject("slave3").get()).size() == 1); Assert.assertEquals(1, taskManager.getKilledTaskIdRecords().size()); // kill the task statusUpdate(taskManager.getTasksOnSlave(taskManager.getActiveTaskIds(), slaveManager.getObject("slave1").get()).get(0), TaskState.TASK_KILLED); Assert.assertTrue(slaveManager.getObject("slave1").get().getCurrentState().getState() == MachineState.DECOMMISSIONED); Assert.assertTrue(slaveManager.getObject("slave1").get().getCurrentState().getUser().get().equals("user1")); // let's DECOMMission rack2 Assert.assertEquals(StateChangeResult.SUCCESS, rackManager.changeState("rack2", MachineState.STARTING_DECOMMISSION, Optional.absent(), Optional.of("user2"))); // it shouldn't place any on here, since it's DECOMMissioned sms.resourceOffers(driver, Arrays.asList(createOffer(1, 129, "slave1", "host1", Optional.of("rack1")))); Assert.assertEquals(0, taskManager.getTasksOnSlave(taskManager.getActiveTaskIds(), slaveManager.getObject("slave1").get()).size()); sms.resourceOffers(driver, Arrays.asList(createOffer(1, 129, "slave1", "host1", Optional.of("rack1")))); Assert.assertEquals(0, taskManager.getTasksOnSlave(taskManager.getActiveTaskIds(), slaveManager.getObject("slave1").get()).size()); slaveResource.activateSlave("slave1", null); sms.resourceOffers(driver, Arrays.asList(createOffer(1, 129, "slave1", "host1", Optional.of("rack1")))); Assert.assertEquals(1, taskManager.getTasksOnSlave(taskManager.getActiveTaskIds(), slaveManager.getObject("slave1").get()).size()); Assert.assertTrue(rackManager.getObject("rack2").get().getCurrentState().getState() == MachineState.DECOMMISSIONING); sms.resourceOffers(driver, Arrays.asList(createOffer(1, 129, "slave2", "host2", Optional.of("rack1")))); for (SingularityTask task : taskManager.getTasksOnSlave(taskManager.getActiveTaskIds(), slaveManager.getObject("slave1").get())) { statusUpdate(task, TaskState.TASK_RUNNING); } for (SingularityTask task : taskManager.getTasksOnSlave(taskManager.getActiveTaskIds(), slaveManager.getObject("slave2").get())) { statusUpdate(task, TaskState.TASK_RUNNING); } cleaner.drainCleanupQueue(); // kill the tasks statusUpdate(taskManager.getTasksOnSlave(taskManager.getActiveTaskIds(), slaveManager.getObject("slave3").get()).get(0), TaskState.TASK_KILLED); Assert.assertTrue(rackManager.getObject("rack2").get().getCurrentState().getState() == MachineState.DECOMMISSIONING); statusUpdate(taskManager.getTasksOnSlave(taskManager.getActiveTaskIds(), slaveManager.getObject("slave4").get()).get(0), TaskState.TASK_KILLED); Assert.assertTrue(rackManager.getObject("rack2").get().getCurrentState().getState() == MachineState.DECOMMISSIONED); } @Test public void testEmptyDecommissioning() { sms.resourceOffers(driver, Arrays.asList(createOffer(1, 129, "slave1", "host1", Optional.of("rack1")))); Assert.assertEquals(StateChangeResult.SUCCESS, slaveManager.changeState("slave1", MachineState.STARTING_DECOMMISSION, Optional.absent(), Optional.of("user1"))); scheduler.drainPendingQueue(stateCacheProvider.get()); sms.resourceOffers(driver, Arrays.asList(createOffer(1, 129, "slave1", "host1", Optional.of("rack1")))); Assert.assertEquals(MachineState.DECOMMISSIONED, slaveManager.getObject("slave1").get().getCurrentState().getState()); } @Test public void testFrozenSlaveTransitions() { initRequest(); initFirstDeploy(); resourceOffers(); // test transitions out of frozen Assert.assertEquals(StateChangeResult.SUCCESS, slaveManager.changeState("slave1", MachineState.FROZEN, Optional.absent(), Optional.of("user1"))); Assert.assertEquals(StateChangeResult.FAILURE_ALREADY_AT_STATE, slaveManager.changeState("slave1", MachineState.FROZEN, Optional.absent(), Optional.of("user1"))); Assert.assertEquals(StateChangeResult.FAILURE_ILLEGAL_TRANSITION, slaveManager.changeState("slave1", MachineState.DECOMMISSIONING, Optional.absent(), Optional.of("user1"))); Assert.assertEquals(StateChangeResult.FAILURE_ILLEGAL_TRANSITION, slaveManager.changeState("slave1", MachineState.DECOMMISSIONED, Optional.absent(), Optional.of("user1"))); Assert.assertEquals(StateChangeResult.SUCCESS, slaveManager.changeState("slave1", MachineState.ACTIVE, Optional.absent(), Optional.of("user1"))); // test transitions into frozen Assert.assertEquals(StateChangeResult.SUCCESS, slaveManager.changeState("slave2", MachineState.STARTING_DECOMMISSION, Optional.absent(), Optional.of("user2"))); Assert.assertEquals(StateChangeResult.FAILURE_ILLEGAL_TRANSITION, slaveManager.changeState("slave2", MachineState.FROZEN, Optional.absent(), Optional.of("user2"))); Assert.assertEquals(StateChangeResult.SUCCESS, slaveManager.changeState("slave2", MachineState.DECOMMISSIONING, Optional.absent(), Optional.of("user2"))); Assert.assertEquals(StateChangeResult.FAILURE_ILLEGAL_TRANSITION, slaveManager.changeState("slave2", MachineState.FROZEN, Optional.absent(), Optional.of("user2"))); Assert.assertEquals(StateChangeResult.SUCCESS, slaveManager.changeState("slave2", MachineState.DECOMMISSIONED, Optional.absent(), Optional.of("user2"))); Assert.assertEquals(StateChangeResult.FAILURE_ILLEGAL_TRANSITION, slaveManager.changeState("slave2", MachineState.FROZEN, Optional.absent(), Optional.of("user2"))); Assert.assertEquals(StateChangeResult.SUCCESS, slaveManager.changeState("slave2", MachineState.ACTIVE, Optional.absent(), Optional.of("user2"))); Assert.assertEquals(StateChangeResult.SUCCESS, slaveManager.changeState("slave2", MachineState.FROZEN, Optional.absent(), Optional.of("user2"))); } @Test public void testFrozenSlaveDoesntLaunchTasks() { initRequest(); initFirstDeploy(); resourceOffers(); Assert.assertEquals(StateChangeResult.SUCCESS, slaveManager.changeState("slave1", MachineState.FROZEN, Optional.absent(), Optional.of("user1"))); saveAndSchedule(request.toBuilder().setInstances(Optional.of(2))); resourceOffers(); Assert.assertEquals(0, taskManager.getTasksOnSlave(taskManager.getActiveTaskIds(), slaveManager.getObject("slave1").get()).size()); Assert.assertEquals(2, taskManager.getTasksOnSlave(taskManager.getActiveTaskIds(), slaveManager.getObject("slave2").get()).size()); } @Test public void testUnfrozenSlaveLaunchesTasks() { initRequest(); initFirstDeploy(); resourceOffers(); Assert.assertEquals(StateChangeResult.SUCCESS, slaveManager.changeState("slave1", MachineState.FROZEN, Optional.absent(), Optional.of("user1"))); saveAndSchedule(request.toBuilder().setInstances(Optional.of(2)).setSlavePlacement(Optional.of(SlavePlacement.SEPARATE))); resourceOffers(); Assert.assertEquals(0, taskManager.getTasksOnSlave(taskManager.getActiveTaskIds(), slaveManager.getObject("slave1").get()).size()); Assert.assertEquals(1, taskManager.getTasksOnSlave(taskManager.getActiveTaskIds(), slaveManager.getObject("slave2").get()).size()); Assert.assertEquals(StateChangeResult.SUCCESS, slaveManager.changeState("slave1", MachineState.ACTIVE, Optional.absent(), Optional.of("user1"))); resourceOffers(); Assert.assertEquals(1, taskManager.getTasksOnSlave(taskManager.getActiveTaskIds(), slaveManager.getObject("slave1").get()).size()); Assert.assertEquals(1, taskManager.getTasksOnSlave(taskManager.getActiveTaskIds(), slaveManager.getObject("slave2").get()).size()); } @Test public void testFrozenSlaveCanBeDecommissioned() { initRequest(); initFirstDeploy(); saveAndSchedule(request.toBuilder().setSlavePlacement(Optional.of(SlavePlacement.GREEDY)).setInstances(Optional.of(2))); sms.resourceOffers(driver, Arrays.asList(createOffer(1, 128, "slave1", "host1"))); sms.resourceOffers(driver, Arrays.asList(createOffer(1, 128, "slave2", "host2"))); // freeze slave1 Assert.assertEquals(StateChangeResult.SUCCESS, slaveManager.changeState("slave1", MachineState.FROZEN, Optional.absent(), Optional.of("user1"))); // mark tasks as running for (SingularityTask task : taskManager.getTasksOnSlave(taskManager.getActiveTaskIds(), slaveManager.getObject("slave1").get())) { statusUpdate(task, TaskState.TASK_RUNNING); } for (SingularityTask task : taskManager.getTasksOnSlave(taskManager.getActiveTaskIds(), slaveManager.getObject("slave2").get())) { statusUpdate(task, TaskState.TASK_RUNNING); } // assert Request is spread over the two slaves Assert.assertEquals(1, taskManager.getTasksOnSlave(taskManager.getActiveTaskIds(), slaveManager.getObject("slave1").get()).size()); Assert.assertEquals(1, taskManager.getTasksOnSlave(taskManager.getActiveTaskIds(), slaveManager.getObject("slave2").get()).size()); // decommission frozen slave1 Assert.assertEquals(StateChangeResult.SUCCESS, slaveManager.changeState("slave1", MachineState.STARTING_DECOMMISSION, Optional.absent(), Optional.of("user1"))); resourceOffers(); cleaner.drainCleanupQueue(); // assert slave1 is decommissioning Assert.assertTrue(slaveManager.getObject("slave1").get().getCurrentState().getState() == MachineState.DECOMMISSIONING); // mark tasks as running for (SingularityTask task : taskManager.getTasksOnSlave(taskManager.getActiveTaskIds(), slaveManager.getObject("slave2").get())) { statusUpdate(task, TaskState.TASK_RUNNING); } // all tasks should have moved cleaner.drainCleanupQueue(); // kill decommissioned task statusUpdate(taskManager.getTasksOnSlave(taskManager.getActiveTaskIds(), slaveManager.getObject("slave1").get()).get(0), TaskState.TASK_KILLED); // assert all tasks on slave2 + slave1 is decommissioned Assert.assertEquals(0, taskManager.getTasksOnSlave(taskManager.getActiveTaskIds(), slaveManager.getObject("slave1").get()).size()); Assert.assertEquals(2, taskManager.getTasksOnSlave(taskManager.getActiveTaskIds(), slaveManager.getObject("slave2").get()).size()); Assert.assertTrue(slaveManager.getObject("slave1").get().getCurrentState().getState() == MachineState.DECOMMISSIONED); } @Test public void testLoadSlavesFromMasterDataOnStartup() { MesosMasterStateObject state = getMasterState(3); singularitySlaveAndRackManager.loadSlavesAndRacksFromMaster(state, true); List<SingularitySlave> slaves = slaveManager.getObjects(); Assert.assertEquals(3, slaves.size()); for (SingularitySlave slave : slaves) { Assert.assertEquals(MachineState.ACTIVE, slave.getCurrentState().getState()); } } @Test public void testReconcileSlaves() { // Load 3 slaves on startup MesosMasterStateObject state = getMasterState(3); singularitySlaveAndRackManager.loadSlavesAndRacksFromMaster(state, true); MesosMasterStateObject newState = getMasterState(2); // 2 slaves, third has died singularitySlaveAndRackManager.loadSlavesAndRacksFromMaster(newState, false); List<SingularitySlave> slaves = slaveManager.getObjects(); Assert.assertEquals(3, slaves.size()); for (SingularitySlave slave : slaves) { if (slave.getId().equals("2")) { Assert.assertEquals(MachineState.DEAD, slave.getCurrentState().getState()); } else { Assert.assertEquals(MachineState.ACTIVE, slave.getCurrentState().getState()); } } } private MesosMasterStateObject getMasterState(int numSlaves) { long now = System.currentTimeMillis(); Map<String, Object> resources = new HashMap<>(); resources.put("cpus", 10); resources.put("mem", 2000); Map<String, String> attributes = new HashMap<>(); attributes.put("testKey", "testValue"); List<MesosMasterSlaveObject> slaves = new ArrayList<>(); for (Integer i = 0; i < numSlaves; i++) { slaves.add(new MesosMasterSlaveObject(i.toString(), i.toString(), String.format("localhost:505%s", i), now, new MesosResourcesObject(resources), attributes, new MesosResourcesObject(resources), new MesosResourcesObject(resources), new MesosResourcesObject(resources), new MesosResourcesObject(resources), "", true)); } MesosFrameworkObject framework = new MesosFrameworkObject("", "", "", "", "", "", "", now, now, now, true, true, new MesosResourcesObject(resources), new MesosResourcesObject(resources), new MesosResourcesObject(resources), Collections.emptyList()); return new MesosMasterStateObject("", "", "", "", now, "", now, now, "", "", "", 0, 0, "", "", "", Collections.emptyMap(), slaves, Collections.singletonList(framework)); } @Test public void testExpiringMachineState() { MesosMasterStateObject state = getMasterState(1); singularitySlaveAndRackManager.loadSlavesAndRacksFromMaster(state, true); SingularitySlave slave = slaveManager.getObjects().get(0); slaveResource.freezeSlave(slave.getId(), new SingularityMachineChangeRequest(Optional.of(1L), Optional.absent(), Optional.absent(), Optional.of(MachineState.ACTIVE), Optional.absent())); Assert.assertEquals(MachineState.FROZEN, slaveManager.getObjects().get(0).getCurrentState().getState()); expiringUserActionPoller.runActionOnPoll(); Assert.assertEquals(MachineState.ACTIVE, slaveManager.getObjects().get(0).getCurrentState().getState()); } private SingularitySlave getSingleSlave() { MesosMasterStateObject state = getMasterState(1); singularitySlaveAndRackManager.loadSlavesAndRacksFromMaster(state, true); return slaveManager.getObjects().get(0); } @Test(expected = WebApplicationException.class) public void testCannotUseStateReservedForSystem() { SingularitySlave slave = getSingleSlave(); slaveResource.freezeSlave(slave.getId(), new SingularityMachineChangeRequest(Optional.of(1L), Optional.absent(), Optional.absent(), Optional.of(MachineState.DEAD), Optional.absent())); } @Test(expected = WebApplicationException.class) public void testBadExpiringStateTransition() { SingularitySlave slave = getSingleSlave(); slaveResource.decommissionSlave(slave.getId(), new SingularityMachineChangeRequest(Optional.of(1L), Optional.absent(), Optional.absent(), Optional.of(MachineState.FROZEN), Optional.absent())); } @Test(expected = WebApplicationException.class) public void testInvalidTransitionToDecommissioned() { SingularitySlave slave = getSingleSlave(); slaveResource.decommissionSlave(slave.getId(), new SingularityMachineChangeRequest(Optional.of(1L), Optional.absent(), Optional.absent(), Optional.of(MachineState.DECOMMISSIONED), Optional.absent())); } @Test public void testValidTransitionToDecommissioned() { initRequest(); initFirstDeploy(); requestResource.postRequest(request.toBuilder().setInstances(Optional.of(2)).build()); scheduler.drainPendingQueue(stateCacheProvider.get()); resourceOffers(1); SingularitySlave slave = slaveManager.getObjects().get(0); slaveResource.decommissionSlave(slave.getId(), new SingularityMachineChangeRequest(Optional.of(1L), Optional.absent(), Optional.absent(), Optional.of(MachineState.DECOMMISSIONED), Optional.of(true))); Assert.assertEquals(MachineState.STARTING_DECOMMISSION, slaveManager.getObjects().get(0).getCurrentState().getState()); scheduler.checkForDecomissions(stateCacheProvider.get()); scheduler.drainPendingQueue(stateCacheProvider.get()); Assert.assertEquals(TaskCleanupType.DECOMISSIONING, taskManager.getCleanupTasks().get(0).getCleanupType()); expiringUserActionPoller.runActionOnPoll(); Assert.assertEquals(MachineState.DECOMMISSIONED, slaveManager.getObjects().get(0).getCurrentState().getState()); Assert.assertEquals(TaskCleanupType.DECOMMISSION_TIMEOUT, taskManager.getCleanupTasks().get(0).getCleanupType()); } @Test public void testSystemChangeClearsExpiringChangeIfInvalid() { SingularitySlave slave = getSingleSlave(); slaveResource.freezeSlave(slave.getId(), null); slaveResource.activateSlave(slave.getId(), new SingularityMachineChangeRequest(Optional.of(1L), Optional.absent(), Optional.absent(), Optional.of(MachineState.FROZEN), Optional.absent())); Assert.assertTrue(slaveManager.getExpiringObject(slave.getId()).isPresent()); slaveResource.decommissionSlave(slave.getId(), null); Assert.assertFalse(slaveManager.getExpiringObject(slave.getId()).isPresent()); } }
package lecho.lib.hellocharts.renderer; import lecho.lib.hellocharts.ChartComputator; import lecho.lib.hellocharts.model.Axis; import lecho.lib.hellocharts.model.AxisValue; import lecho.lib.hellocharts.model.Viewport; import lecho.lib.hellocharts.util.AxisAutoStops; import lecho.lib.hellocharts.util.Utils; import lecho.lib.hellocharts.view.Chart; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Paint.Align; import android.graphics.Paint.FontMetricsInt; import android.graphics.Rect; import android.graphics.Typeface; import android.text.TextUtils; /** * Default axes renderer. Can draw maximum four axes - two horizontal(top/bottom) and two vertical(left/right). * * @author Leszek Wach */ public class AxesRenderer { private static final int DEFAULT_AXIS_MARGIN_DP = 2; // Axis positions and also *Tabs indexes. private static final int TOP = 0; private static final int LEFT = 1; private static final int RIGHT = 2; private static final int BOTTOM = 3; private static final char[] labelWidthChars = new char[] { '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0' }; private Chart chart; private int axisMargin; // 4 text paints for every axis, not all have to be used, indexed with TOP, LEFT, RIGHT, BOTTOM. private Paint[] textPaintTab = new Paint[] { new Paint(), new Paint(), new Paint(), new Paint() }; private Paint linePaint; private int[] axisStopsToDrawNumTab = new int[4]; private float[][] axisRawStopsTab = new float[4][0]; private float[][] axisAutoStopsToDrawTab = new float[4][0]; private AxisValue[][] axisValuesToDrawTab = new AxisValue[4][0]; private float[][] axisLinesDrawBufferTab = new float[4][0]; private AxisAutoStops[] axisAutoStopsBufferTab = new AxisAutoStops[] { new AxisAutoStops(), new AxisAutoStops(), new AxisAutoStops(), new AxisAutoStops() }; private float[] axisFixedCoordinateTab = new float[4]; private float[] axisBaselineTab = new float[4]; private float[] axisSeparationLineTab = new float[4]; private int[] axisLabelWidthTab = new int[4]; private int[] axisLabelTextAscentTab = new int[4]; private int[] axisLabelTextDescentTab = new int[4]; private FontMetricsInt[] fontMetricsTab = new FontMetricsInt[] { new FontMetricsInt(), new FontMetricsInt(), new FontMetricsInt(), new FontMetricsInt() }; private float[] valuesBuff = new float[1]; private char[] labelBuffer = new char[32]; private float density; private float scaledDensity; public AxesRenderer(Context context, Chart chart) { this.chart = chart; density = context.getResources().getDisplayMetrics().density; scaledDensity = context.getResources().getDisplayMetrics().scaledDensity; axisMargin = Utils.dp2px(density, DEFAULT_AXIS_MARGIN_DP); linePaint = new Paint(); linePaint.setAntiAlias(true); linePaint.setStyle(Paint.Style.STROKE); linePaint.setStrokeWidth(1); for (Paint paint : textPaintTab) { paint.setAntiAlias(true); } } public void initAxesAttributes() { int axisXTopHeight = initAxisAttributes(chart.getChartData().getAxisXTop(), TOP); int axisXBottomHeight = initAxisAttributes(chart.getChartData().getAxisXBottom(), BOTTOM); int axisYLeftWidth = initAxisAttributes(chart.getChartData().getAxisYLeft(), LEFT); int axisYRightWidth = initAxisAttributes(chart.getChartData().getAxisYRight(), RIGHT); chart.getChartComputator().setAxesMargin(axisYLeftWidth, axisXTopHeight, axisYRightWidth, axisXBottomHeight); } public void draw(Canvas canvas) { if (null != chart.getChartData().getAxisYLeft()) { drawAxisVertical(canvas, LEFT); } if (null != chart.getChartData().getAxisYRight()) { drawAxisVertical(canvas, RIGHT); } if (null != chart.getChartData().getAxisXBottom()) { drawAxisHorizontal(canvas, BOTTOM); } if (null != chart.getChartData().getAxisXTop()) { drawAxisHorizontal(canvas, TOP); } } public void drawInBackground(Canvas canvas) { } public void drawInForeground(Canvas canvas) { } /** * Initialize attributes and measurement for axes(left, right, top, bottom); Returns axis measured width( for left * and right) or height(for top and bottom). */ private int initAxisAttributes(Axis axis, int position) { if (null == axis) { return 0; } Typeface typeface = axis.getTypeface(); if (null != typeface) { textPaintTab[position].setTypeface(typeface); } textPaintTab[position].setColor(axis.getTextColor()); textPaintTab[position].setTextSize(Utils.sp2px(scaledDensity, axis.getTextSize())); textPaintTab[position].getFontMetricsInt(fontMetricsTab[position]); axisLabelTextAscentTab[position] = Math.abs(fontMetricsTab[position].ascent); axisLabelTextDescentTab[position] = Math.abs(fontMetricsTab[position].descent); axisLabelWidthTab[position] = (int) textPaintTab[position].measureText(labelWidthChars, 0, axis.getMaxLabelChars()); int result = 0; if (LEFT == position || RIGHT == position) { int width = 0; // If auto-generated or has manual values add height for value labels. if ((axis.isAutoGenerated() || !axis.getValues().isEmpty()) && !axis.isInside()) { width += axisLabelWidthTab[position]; width += axisMargin; } // If has name add height for axis name text. if (!TextUtils.isEmpty(axis.getName())) { width += axisLabelTextAscentTab[position]; width += axisLabelTextDescentTab[position]; width += axisMargin; } result = width; } else if (TOP == position || BOTTOM == position) { int height = 0; // If auto-generated or has manual values add height for value labels. if ((axis.isAutoGenerated() || !axis.getValues().isEmpty()) && !axis.isInside()) { height += axisLabelTextAscentTab[position]; height += axisLabelTextDescentTab[position]; height += axisMargin; } // If has name add height for axis name text. if (!TextUtils.isEmpty(axis.getName())) { height += axisLabelTextAscentTab[position]; height += axisLabelTextDescentTab[position]; height += axisMargin; } result = height; } else { throw new IllegalArgumentException("Invalid axis position: " + position); } return result; } private void drawAxisHorizontal(Canvas canvas, int position) { final ChartComputator computator = chart.getChartComputator(); textPaintTab[position].setTextAlign(Align.CENTER); final Axis axis; if (BOTTOM == position) { axis = chart.getChartData().getAxisXBottom(); if (axis.isInside()) { axisFixedCoordinateTab[position] = computator.getContentRectWithMargins().bottom - axisMargin - axisLabelTextDescentTab[position]; axisBaselineTab[position] = computator.getContentRectWithMargins().bottom + axisLabelTextAscentTab[position] + axisMargin; } else { axisFixedCoordinateTab[position] = computator.getContentRectWithMargins().bottom + axisLabelTextAscentTab[position] + axisMargin; axisBaselineTab[position] = axisFixedCoordinateTab[position] + axisMargin + axisLabelTextAscentTab[position] + axisLabelTextDescentTab[position]; } axisSeparationLineTab[position] = computator.getContentRect().bottom; } else if (TOP == position) { axis = chart.getChartData().getAxisXTop(); if (axis.isInside()) { axisFixedCoordinateTab[position] = computator.getContentRectWithMargins().top + axisMargin + axisLabelTextAscentTab[position]; axisBaselineTab[position] = computator.getContentRectWithMargins().top - axisMargin - axisLabelTextDescentTab[position]; } else { axisFixedCoordinateTab[position] = computator.getContentRectWithMargins().top - axisMargin - axisLabelTextDescentTab[position]; axisBaselineTab[position] = axisFixedCoordinateTab[position] - axisMargin - axisLabelTextAscentTab[position] - axisLabelTextDescentTab[position]; } axisSeparationLineTab[position] = computator.getContentRect().top; } else { throw new IllegalArgumentException("Invalid position for horizontal axis: " + position); } if (axis.isAutoGenerated()) { drawAxisHorizontalAuto(canvas, axis, axisFixedCoordinateTab[position], position); } else { drawAxisHorizontal(canvas, axis, axisFixedCoordinateTab[position], position); } // Drawing axis name if (!TextUtils.isEmpty(axis.getName())) { canvas.drawText(axis.getName(), computator.getContentRect().centerX(), axisBaselineTab[position], textPaintTab[position]); } // Draw separation line with the same color as axis text. Only horizontal axes have separation lines. canvas.drawLine(computator.getContentRectWithMargins().left, axisSeparationLineTab[position], computator.getContentRectWithMargins().right, axisSeparationLineTab[position], textPaintTab[position]); } private void drawAxisHorizontal(Canvas canvas, Axis axis, float rawY, int position) { final ChartComputator computator = chart.getChartComputator(); final Viewport maxViewport = computator.getMaximumViewport(); final Viewport visibleViewport = computator.getVisibleViewport(); final Rect contentRect = computator.getContentRect(); final Rect contentRectMargins = computator.getContentRectWithMargins(); float scale = maxViewport.width() / visibleViewport.width(); final int module = (int) Math.ceil(axis.getValues().size() * axisLabelWidthTab[position] / (contentRect.width() * scale)); if (axis.hasLines() && axisLinesDrawBufferTab[position].length < axis.getValues().size() * 4) { axisLinesDrawBufferTab[position] = new float[axis.getValues().size() * 4]; } if (axisRawStopsTab[position].length < axis.getValues().size()) { axisRawStopsTab[position] = new float[axis.getValues().size()]; axisValuesToDrawTab[position] = new AxisValue[axis.getValues().size()]; } int lineIndex = 0; int valueIndex = 0; int stopsToDrawIndex = 0; for (AxisValue axisValue : axis.getValues()) { final float value = axisValue.getValue(); // Draw axis values that area within visible viewport. if (value >= visibleViewport.left && value <= visibleViewport.right) { // Draw axis values that have 0 module value, this will hide some labels if there is no place for them. if (0 == valueIndex % module) { final float rawX = computator.computeRawX(axisValue.getValue()); if (checkRawX(contentRect, rawX, axis.isInside(), position)) { axisRawStopsTab[position][stopsToDrawIndex] = rawX; axisValuesToDrawTab[position][stopsToDrawIndex] = axisValue; valuesBuff[0] = axisValuesToDrawTab[position][stopsToDrawIndex].getValue(); final int nummChars = axis.getFormatter().formatValue(labelBuffer, valuesBuff, axisValuesToDrawTab[position][stopsToDrawIndex].getLabel()); canvas.drawText(labelBuffer, labelBuffer.length - nummChars, nummChars, axisRawStopsTab[position][stopsToDrawIndex], rawY, textPaintTab[position]); if (axis.hasLines()) { axisLinesDrawBufferTab[position][lineIndex * 4 + 0] = axisRawStopsTab[position][stopsToDrawIndex]; axisLinesDrawBufferTab[position][lineIndex * 4 + 1] = contentRectMargins.top; axisLinesDrawBufferTab[position][lineIndex * 4 + 2] = axisRawStopsTab[position][stopsToDrawIndex]; axisLinesDrawBufferTab[position][lineIndex * 4 + 3] = contentRectMargins.bottom; ++lineIndex; } ++stopsToDrawIndex; } } // If within viewport - increment valueIndex; ++valueIndex; } } axisStopsToDrawNumTab[position] = stopsToDrawIndex; if (axis.hasLines()) { linePaint.setColor(axis.getLineColor()); canvas.drawLines(axisLinesDrawBufferTab[position], 0, lineIndex * 4, linePaint); } } private void drawAxisHorizontalAuto(Canvas canvas, Axis axis, float rawY, int position) { final ChartComputator computator = chart.getChartComputator(); final Viewport visibleViewport = computator.getVisibleViewport(); final Rect contentRect = computator.getContentRect(); final Rect contentRectMargins = computator.getContentRectWithMargins(); Utils.computeAxisStops(visibleViewport.left, visibleViewport.right, contentRect.width() / axisLabelWidthTab[position] / 2, axisAutoStopsBufferTab[position]); if (axis.hasLines() && axisLinesDrawBufferTab[position].length < axisAutoStopsBufferTab[position].numStops * 4) { axisLinesDrawBufferTab[position] = new float[axisAutoStopsBufferTab[position].numStops * 4]; } if (axisRawStopsTab[position].length < axisAutoStopsBufferTab[position].numStops) { axisRawStopsTab[position] = new float[axisAutoStopsBufferTab[position].numStops]; axisAutoStopsToDrawTab[position] = new float[axisAutoStopsBufferTab[position].numStops]; } int lineIndex = 0; int stopsToDrawIndex = 0; for (int i = 0; i < axisAutoStopsBufferTab[position].numStops; ++i) { final float rawX = computator.computeRawX(axisAutoStopsBufferTab[position].stops[i]); if (checkRawX(contentRect, rawX, axis.isInside(), position)) { axisRawStopsTab[position][stopsToDrawIndex] = rawX; axisAutoStopsToDrawTab[position][stopsToDrawIndex] = axisAutoStopsBufferTab[position].stops[i]; valuesBuff[0] = axisAutoStopsToDrawTab[position][stopsToDrawIndex]; final int nummChars = axis.getFormatter().formatValue(labelBuffer, valuesBuff, null, axisAutoStopsBufferTab[position].decimals); canvas.drawText(labelBuffer, labelBuffer.length - nummChars, nummChars, axisRawStopsTab[position][stopsToDrawIndex], rawY, textPaintTab[position]); if (axis.hasLines()) { axisLinesDrawBufferTab[position][lineIndex * 4 + 0] = axisRawStopsTab[position][stopsToDrawIndex]; axisLinesDrawBufferTab[position][lineIndex * 4 + 1] = contentRectMargins.top; axisLinesDrawBufferTab[position][lineIndex * 4 + 2] = axisRawStopsTab[position][stopsToDrawIndex]; axisLinesDrawBufferTab[position][lineIndex * 4 + 3] = contentRectMargins.bottom; ++lineIndex; } ++stopsToDrawIndex; } } axisStopsToDrawNumTab[position] = stopsToDrawIndex; if (axis.hasLines()) { linePaint.setColor(axis.getLineColor()); canvas.drawLines(axisLinesDrawBufferTab[position], 0, lineIndex * 4, linePaint); } } /** * For axis inside chart area this method checks if there is place to draw axis label. If yes returns true, * otherwise false. */ private boolean checkRawX(Rect rect, float rawX, boolean axisInside, int position) { if (axisInside) { float margin = axisLabelWidthTab[position] / 2; if (rawX >= rect.left + margin && rawX <= rect.right - margin) { return true; } else { return false; } } return true; } private void drawAxisVertical(Canvas canvas, int position) { final ChartComputator computator = chart.getChartComputator(); final Axis axis; if (LEFT == position) { axis = chart.getChartData().getAxisYLeft(); textPaintTab[position].setTextAlign(Align.RIGHT); if (axis.isInside()) { axisFixedCoordinateTab[position] = computator.getContentRectWithMargins().left + axisMargin + axisLabelWidthTab[position]; axisBaselineTab[position] = computator.getContentRectWithMargins().left - axisMargin - axisLabelTextDescentTab[position]; } else { axisFixedCoordinateTab[position] = computator.getContentRectWithMargins().left - axisMargin; axisBaselineTab[position] = axisFixedCoordinateTab[position] - axisLabelWidthTab[position] - axisMargin - axisLabelTextDescentTab[position]; } } else if (RIGHT == position) { textPaintTab[position].setTextAlign(Align.LEFT); axis = chart.getChartData().getAxisYRight(); if (axis.isInside()) { axisFixedCoordinateTab[position] = computator.getContentRectWithMargins().right - axisMargin - axisLabelWidthTab[position]; axisBaselineTab[position] = computator.getContentRectWithMargins().right + axisMargin + axisLabelTextAscentTab[position]; } else { axisFixedCoordinateTab[position] = computator.getContentRectWithMargins().right + axisMargin; axisBaselineTab[position] = axisFixedCoordinateTab[position] + axisLabelWidthTab[position] + axisMargin + axisLabelTextAscentTab[position]; } } else { throw new IllegalArgumentException("Invalid position for horizontal axis: " + position); } // drawing axis values if (axis.isAutoGenerated()) { drawAxisVerticalAuto(canvas, axis, axisFixedCoordinateTab[position], position); } else { drawAxisVertical(canvas, axis, axisFixedCoordinateTab[position], position); } // drawing axis name if (!TextUtils.isEmpty(axis.getName())) { textPaintTab[position].setTextAlign(Align.CENTER); canvas.save(); canvas.rotate(-90, computator.getContentRect().centerY(), computator.getContentRect().centerY()); canvas.drawText(axis.getName(), computator.getContentRect().centerY(), axisBaselineTab[position], textPaintTab[position]); canvas.restore(); } } private void drawAxisVertical(Canvas canvas, Axis axis, float rawX, int position) { final ChartComputator computator = chart.getChartComputator(); final Viewport maxViewport = computator.getMaximumViewport(); final Viewport visibleViewport = computator.getVisibleViewport(); final Rect contentRect = computator.getContentRect(); final Rect contentRectMargins = computator.getContentRectWithMargins(); float scale = maxViewport.height() / visibleViewport.height(); final int module = (int) Math.ceil(axis.getValues().size() * axisLabelTextAscentTab[position] * 2 / (contentRect.height() * scale)); if (axis.hasLines() && axisLinesDrawBufferTab[position].length < axis.getValues().size() * 4) { axisLinesDrawBufferTab[position] = new float[axis.getValues().size() * 4]; } int lineIndex = 0; int valueIndex = 0; for (AxisValue axisValue : axis.getValues()) { final float value = axisValue.getValue(); // Draw axis values that area within visible viewport. if (value >= visibleViewport.bottom && value <= visibleViewport.top) { // Draw axis values that have 0 module value, this will hide some labels if there is no place for them. if (0 == valueIndex % module) { final float rawY = computator.computeRawY(value); if (checkRawY(contentRect, rawY, axis.isInside(), position)) { valuesBuff[0] = axisValue.getValue(); final int nummChars = axis.getFormatter().formatValue(labelBuffer, valuesBuff, axisValue.getLabel()); canvas.drawText(labelBuffer, labelBuffer.length - nummChars, nummChars, rawX, rawY, textPaintTab[position]); if (axis.hasLines()) { axisLinesDrawBufferTab[position][lineIndex * 4 + 0] = contentRectMargins.left; axisLinesDrawBufferTab[position][lineIndex * 4 + 1] = rawY; axisLinesDrawBufferTab[position][lineIndex * 4 + 2] = contentRectMargins.right; axisLinesDrawBufferTab[position][lineIndex * 4 + 3] = rawY; ++lineIndex; } } } // If within viewport - increment valueIndex; ++valueIndex; } } if (axis.hasLines()) { linePaint.setColor(axis.getLineColor()); canvas.drawLines(axisLinesDrawBufferTab[position], 0, lineIndex * 4, linePaint); } } private void drawAxisVerticalAuto(Canvas canvas, Axis axis, float rawX, int position) { final ChartComputator computator = chart.getChartComputator(); final Viewport visibleViewport = computator.getVisibleViewport(); final Rect contentRect = computator.getContentRect(); final Rect contentRectMargins = computator.getContentRectWithMargins(); Utils.computeAxisStops(visibleViewport.bottom, visibleViewport.top, contentRect.height() / axisLabelTextAscentTab[position] / 2, axisAutoStopsBufferTab[position]); if (axis.hasLines() && axisLinesDrawBufferTab[position].length < axisAutoStopsBufferTab[position].numStops * 4) { axisLinesDrawBufferTab[position] = new float[axisAutoStopsBufferTab[position].numStops * 4]; } int lineIndex = 0; for (int i = 0; i < axisAutoStopsBufferTab[position].numStops; i++) { final float rawY = computator.computeRawY(axisAutoStopsBufferTab[position].stops[i]); if (checkRawY(contentRect, rawY, axis.isInside(), position)) { valuesBuff[0] = axisAutoStopsBufferTab[position].stops[i]; final int nummChars = axis.getFormatter().formatValue(labelBuffer, valuesBuff, null, axisAutoStopsBufferTab[position].decimals); canvas.drawText(labelBuffer, labelBuffer.length - nummChars, nummChars, rawX, rawY, textPaintTab[position]); if (axis.hasLines()) { axisLinesDrawBufferTab[position][lineIndex * 4 + 0] = contentRectMargins.left; axisLinesDrawBufferTab[position][lineIndex * 4 + 1] = rawY; axisLinesDrawBufferTab[position][lineIndex * 4 + 2] = contentRectMargins.right; axisLinesDrawBufferTab[position][lineIndex * 4 + 3] = rawY; ++lineIndex; } } } if (axis.hasLines()) { linePaint.setColor(axis.getLineColor()); canvas.drawLines(axisLinesDrawBufferTab[position], 0, lineIndex * 4, linePaint); } } /** * For axis inside chart area this method checks if there is place to draw axis label. If yes returns true, * otherwise false. */ private boolean checkRawY(Rect rect, float rawY, boolean axisInside, int position) { if (axisInside) { float marginBottom = axisLabelTextAscentTab[BOTTOM] + axisMargin; float marginTop = axisLabelTextAscentTab[TOP] + axisMargin; if (rawY <= rect.bottom - marginBottom && rawY >= rect.top + marginTop) { return true; } else { return false; } } return true; } }
package ai.vespa.hosted.client; import ai.vespa.http.HttpURL; import ai.vespa.http.HttpURL.Path; import ai.vespa.http.HttpURL.Query; import com.yahoo.time.TimeBudget; import org.apache.hc.client5.http.config.RequestConfig; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.core5.http.ClassicHttpRequest; import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.HttpEntity; import org.apache.hc.core5.http.Method; import org.apache.hc.core5.http.ParseException; import org.apache.hc.core5.http.io.entity.EntityUtils; import org.apache.hc.core5.http.io.entity.HttpEntities; import org.apache.hc.core5.http.io.support.ClassicRequestBuilder; import org.apache.hc.core5.util.Timeout; import java.io.IOException; import java.io.UncheckedIOException; import java.net.URI; import java.time.Duration; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.function.BiFunction; import java.util.function.Function; import java.util.function.Supplier; import java.util.logging.Logger; import static java.util.Objects.requireNonNull; import static java.util.logging.Level.FINE; import static java.util.logging.Level.WARNING; /** * @author jonmv */ public abstract class AbstractHttpClient implements HttpClient { private static final Logger log = Logger.getLogger(AbstractHttpClient.class.getName()); public static HttpClient wrapping(CloseableHttpClient client) { return new AbstractHttpClient() { @Override protected ClassicHttpResponse execute(ClassicHttpRequest request, HttpClientContext context) throws IOException { return client.execute(request, context); } @Override public void close() throws IOException { client.close(); } }; } /** Executes the request with the given context. The caller must close the response. */ protected abstract ClassicHttpResponse execute(ClassicHttpRequest request, HttpClientContext context) throws IOException; /** Executes the given request with response/error handling and retries. */ private <T> T execute(RequestBuilder builder, BiFunction<ClassicHttpResponse, ClassicHttpRequest, T> handler, ExceptionHandler catcher) { Throwable thrown = null; for (URI host : builder.hosts) { Query query = builder.query; for (Supplier<Query> dynamic : builder.dynamicQuery) query = query.set(dynamic.get().lastEntries()); ClassicHttpRequest request = ClassicRequestBuilder.create(builder.method.name()) .setUri(HttpURL.from(host) .appendPath(builder.path) .appendQuery(query) .asURI()) .build(); builder.headers.forEach((name, values) -> values.forEach(value -> request.setHeader(name, value))); try (HttpEntity entity = builder.entity.get()) { request.setEntity(entity); try { return handler.apply(execute(request, contextWithTimeout(builder)), request); } catch (IOException e) { catcher.handle(e, request); throw RetryException.wrap(e, request); } } catch (IOException e) { throw new UncheckedIOException("failed closing request entity", e); } catch (RetryException e) { if (thrown == null) thrown = e.getCause(); else thrown.addSuppressed(e.getCause()); log.log(FINE, e.getCause(), () -> request + " failed; will retry"); } } if (thrown != null) { if (thrown instanceof IOException) throw new UncheckedIOException((IOException) thrown); else if (thrown instanceof RuntimeException) throw (RuntimeException) thrown; else throw new IllegalStateException("Illegal retry cause: " + thrown.getClass(), thrown); } throw new IllegalStateException("No hosts to perform the request against"); } private HttpClientContext contextWithTimeout(RequestBuilder builder) { HttpClientContext context = HttpClientContext.create(); RequestConfig config = builder.config; if (builder.deadline != null) { Optional<Duration> remaining = builder.deadline.timeLeftOrThrow(); if (remaining.isPresent()) { config = RequestConfig.copy(config) .setConnectTimeout(min(config.getConnectTimeout(), remaining.get())) .setConnectionRequestTimeout(min(config.getConnectionRequestTimeout(), remaining.get())) .setResponseTimeout(min(config.getResponseTimeout(), remaining.get())) .build(); } } context.setRequestConfig(config); return context; } // TimeBudget guarantees remaining duration is positive. static Timeout min(Timeout first, Duration second) { long firstMillis = first == null || first.isDisabled() ? second.toMillis() : first.toMilliseconds(); return Timeout.ofMilliseconds(Math.min(firstMillis, second.toMillis())); } @Override public HttpClient.RequestBuilder send(HostStrategy hosts, Method method) { return new RequestBuilder(hosts, method); } /** Builder for a request against a given set of hosts. */ class RequestBuilder implements HttpClient.RequestBuilder { private final Method method; private final HostStrategy hosts; private HttpURL.Path path = Path.empty(); private HttpURL.Query query = Query.empty(); private List<Supplier<Query>> dynamicQuery = new ArrayList<>(); private Map<String, List<String>> headers = new LinkedHashMap<>(); private Supplier<HttpEntity> entity = () -> null; private RequestConfig config = HttpClient.defaultRequestConfig; private ResponseVerifier verifier = HttpClient.throwOnError; private ExceptionHandler catcher = HttpClient.retryAll; private TimeBudget deadline; private RequestBuilder(HostStrategy hosts, Method method) { if ( ! hosts.iterator().hasNext()) throw new IllegalArgumentException("Host strategy cannot be empty"); this.hosts = hosts; this.method = requireNonNull(method); } @Override public RequestBuilder at(Path subPath) { path = path.append(subPath); return this; } @Override public HttpClient.RequestBuilder body(byte[] json) { return body(HttpEntities.create(json, ContentType.APPLICATION_JSON)); } @Override public RequestBuilder body(Supplier<HttpEntity> entity) { this.entity = requireNonNull(entity); return this; } @Override public HttpClient.RequestBuilder emptyParameters(List<String> keys) { for (String key : keys) query = query.add(key); return this; } @Override public RequestBuilder parameters(List<String> pairs) { if (pairs.size() % 2 != 0) throw new IllegalArgumentException("Must supply parameter key/values in pairs"); for (int i = 0; i < pairs.size(); ) { String key = pairs.get(i++), value = pairs.get(i++); if (value != null) query = query.add(key, value); } return this; } @Override public HttpClient.RequestBuilder parameters(Query query) { this.query = this.query.add(query.entries()); return this; } @Override public HttpClient.RequestBuilder parameters(Supplier<Query> query) { dynamicQuery.add(query); return this; } @Override public RequestBuilder timeout(Duration timeout) { return config(RequestConfig.copy(config) .setResponseTimeout(timeout.toMillis(), TimeUnit.MILLISECONDS) .build()); } @Override public HttpClient.RequestBuilder deadline(TimeBudget deadline) { this.deadline = requireNonNull(deadline); return this; } @Override public HttpClient.RequestBuilder addHeader(String name, String value) { this.headers.computeIfAbsent(name, __ -> new ArrayList<>()).add(value); return this; } @Override public HttpClient.RequestBuilder setHeader(String name, String value) { this.headers.put(name, new ArrayList<>(List.of(value))); return this; } @Override public RequestBuilder config(RequestConfig config) { this.config = requireNonNull(config); return this; } @Override public RequestBuilder catching(ExceptionHandler catcher) { this.catcher = requireNonNull(catcher); return this; } @Override public RequestBuilder throwing(ResponseVerifier verifier) { this.verifier = requireNonNull(verifier); return this; } @Override public String read() { return handle((response, __) -> { try (response) { return response.getEntity() == null ? "" : EntityUtils.toString(response.getEntity()); } catch (ParseException e) { throw new IllegalStateException(e); // This isn't actually thrown by apache >_< } }); } @Override public <T> T read(Function<byte[], T> mapper) { return handle((response, __) -> { try (response) { return mapper.apply(response.getEntity() == null ? new byte[0] : EntityUtils.toByteArray(response.getEntity())); } }); } @Override public void discard() throws UncheckedIOException, ResponseException { handle((response, __) -> { try (response) { return null; } }); } @Override public HttpInputStream stream() throws UncheckedIOException, ResponseException { return handle((response, __) -> new HttpInputStream(response)); } @Override public <T> T handle(ResponseHandler<T> handler) { return execute(this, (response, request) -> { try { verifier.verify(response, request); // This throws on unacceptable responses. return handler.handle(response, request); } catch (IOException | RuntimeException | Error e) { try { response.close(); } catch (IOException f) { e.addSuppressed(f); } if (e instanceof IOException) { catcher.handle((IOException) e, request); throw RetryException.wrap((IOException) e, request); } else sneakyThrow(e); // e is a runtime exception or an error, so this is fine. throw new AssertionError("Should not happen"); } }, catcher); } } @SuppressWarnings("unchecked") private static <T extends Throwable> void sneakyThrow(Throwable t) throws T { throw (T) t; } }
package org.sakaiproject.evaluation.dao; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.sakaiproject.evaluation.constant.EvalConstants; import org.sakaiproject.evaluation.model.EvalAdhocGroup; import org.sakaiproject.evaluation.model.EvalAnswer; import org.sakaiproject.evaluation.model.EvalAssignGroup; import org.sakaiproject.evaluation.model.EvalAssignUser; import org.sakaiproject.evaluation.model.EvalEmailProcessingData; import org.sakaiproject.evaluation.model.EvalEmailTemplate; import org.sakaiproject.evaluation.model.EvalEvaluation; import org.sakaiproject.evaluation.model.EvalItem; import org.sakaiproject.evaluation.model.EvalResponse; import org.sakaiproject.evaluation.model.EvalScale; import org.sakaiproject.evaluation.model.EvalTemplate; import org.sakaiproject.evaluation.model.EvalTemplateItem; import org.sakaiproject.evaluation.test.EvalTestDataLoad; import org.sakaiproject.evaluation.test.PreloadTestDataImpl; import org.sakaiproject.evaluation.utils.ArrayUtils; import org.sakaiproject.genericdao.api.search.Restriction; import org.sakaiproject.genericdao.api.search.Search; import org.springframework.test.AbstractTransactionalSpringContextTests; /** * Testing for the Evaluation Data Access Layer * * @author Aaron Zeckoski (aaronz@vt.edu) */ public class EvaluationDaoImplTest extends AbstractTransactionalSpringContextTests { protected EvaluationDao evaluationDao; private EvalTestDataLoad etdl; private EvalScale scaleLocked; private EvalItem itemLocked; private EvalItem itemUnlocked; private EvalEvaluation evalUnLocked; protected static final long MILLISECONDS_PER_DAY = 24L * 60L * 60L * 1000L; protected String[] getConfigLocations() { // point to the needed spring config files, must be on the classpath // (add component/src/webapp/WEB-INF to the build path in Eclipse), // they also need to be referenced in the maven file return new String[] {"hibernate-test.xml", "spring-hibernate.xml"}; } // run this before each test starts protected void onSetUpBeforeTransaction() throws Exception { // load the spring created dao class bean from the Spring Application Context evaluationDao = (EvaluationDao) applicationContext.getBean("org.sakaiproject.evaluation.dao.EvaluationDao"); if (evaluationDao == null) { throw new NullPointerException("DAO could not be retrieved from spring context"); } // check the preloaded data assertTrue("Error preloading data", evaluationDao.countAll(EvalScale.class) > 0); // check the preloaded test data assertTrue("Error preloading test data", evaluationDao.countAll(EvalEvaluation.class) > 0); PreloadTestDataImpl ptd = (PreloadTestDataImpl) applicationContext.getBean("org.sakaiproject.evaluation.test.PreloadTestData"); if (ptd == null) { throw new NullPointerException("PreloadTestDataImpl could not be retrieved from spring context"); } // get test objects etdl = ptd.getEtdl(); // init the test class if needed } // run this before each test starts and as part of the transaction protected void onSetUpInTransaction() { // preload additional data if desired String[] optionsA = {"Male", "Female", "Unknown"}; scaleLocked = new EvalScale(EvalTestDataLoad.ADMIN_USER_ID, "Scale Alpha", EvalConstants.SCALE_MODE_SCALE, EvalConstants.SHARING_PRIVATE, EvalTestDataLoad.NOT_EXPERT, "description", EvalConstants.SCALE_IDEAL_NONE, optionsA, EvalTestDataLoad.LOCKED); evaluationDao.save( scaleLocked ); itemLocked = new EvalItem(EvalTestDataLoad.MAINT_USER_ID, "Header type locked", EvalConstants.SHARING_PRIVATE, EvalConstants.ITEM_TYPE_HEADER, EvalTestDataLoad.NOT_EXPERT); itemLocked.setLocked(EvalTestDataLoad.LOCKED); evaluationDao.save( itemLocked ); itemUnlocked = new EvalItem(EvalTestDataLoad.MAINT_USER_ID, "Header type locked", EvalConstants.SHARING_PRIVATE, EvalConstants.ITEM_TYPE_HEADER, EvalTestDataLoad.NOT_EXPERT); itemUnlocked.setScale(etdl.scale2); itemUnlocked.setScaleDisplaySetting( EvalConstants.ITEM_SCALE_DISPLAY_VERTICAL ); itemUnlocked.setCategory(EvalConstants.ITEM_CATEGORY_COURSE); itemUnlocked.setLocked(EvalTestDataLoad.UNLOCKED); evaluationDao.save( itemUnlocked ); evalUnLocked = new EvalEvaluation(EvalConstants.EVALUATION_TYPE_EVALUATION, EvalTestDataLoad.MAINT_USER_ID, "Eval active not taken", null, etdl.yesterday, etdl.tomorrow, etdl.tomorrow, etdl.threeDaysFuture, false, null, false, null, EvalConstants.EVALUATION_STATE_ACTIVE, EvalConstants.SHARING_VISIBLE, EvalConstants.INSTRUCTOR_OPT_IN, new Integer(1), null, null, null, null, etdl.templatePublicUnused, null, Boolean.TRUE, Boolean.FALSE, Boolean.FALSE, EvalTestDataLoad.UNLOCKED, EvalConstants.EVALUATION_AUTHCONTROL_AUTH_REQ, null, null); evaluationDao.save( evalUnLocked ); } /** * ADD unit tests below here, use testMethod as the name of the unit test, * Note that if a method is overloaded you should include the arguments in the * test name like so: testMethodClassInt (for method(Class, int); */ public void testValidateDao() { assertNotNull(evaluationDao); List<EvalTemplate> templates = evaluationDao.findAll(EvalTemplate.class); assertNotNull( templates ); assertTrue(templates.size() > 4); List<EvalAssignUser> assignUsers = evaluationDao.findAll(EvalAssignUser.class); assertNotNull( assignUsers ); assertTrue(assignUsers.size() > 20); evaluationDao.findAll(EvalEmailTemplate.class); } public void testGetParticipants() { List<EvalAssignUser> l = null; long start = 0l; // more testing at the higher level // get all participants for an evaluation start = System.currentTimeMillis(); l = evaluationDao.getParticipantsForEval(etdl.evaluationActive.getId(), null, null, null, null, null, null); System.out.println("Query executed in " + (System.currentTimeMillis()-start) + " ms"); assertNotNull(l); assertEquals(2, l.size()); // limit groups start = System.currentTimeMillis(); l = evaluationDao.getParticipantsForEval(etdl.evaluationActive.getId(), null, new String[] {EvalTestDataLoad.SITE1_REF}, null, null, null, null); System.out.println("Query executed in " + (System.currentTimeMillis()-start) + " ms"); assertNotNull(l); assertEquals(2, l.size()); l = evaluationDao.getParticipantsForEval(etdl.evaluationActive.getId(), null, new String[] {EvalTestDataLoad.SITE2_REF}, null, null, null, null); assertNotNull(l); assertEquals(0, l.size()); // get everyone who can take an evaluation start = System.currentTimeMillis(); l = evaluationDao.getParticipantsForEval(etdl.evaluationActive.getId(), null, null, EvalAssignUser.TYPE_EVALUATOR, null, null, null); System.out.println("Query executed in " + (System.currentTimeMillis()-start) + " ms"); assertNotNull(l); assertEquals(1, l.size()); // get all the evals a user is assigned to start = System.currentTimeMillis(); l = evaluationDao.getParticipantsForEval(null, EvalTestDataLoad.USER_ID, null, EvalAssignUser.TYPE_EVALUATOR, null, null, null); System.out.println("Query executed in " + (System.currentTimeMillis()-start) + " ms"); assertNotNull(l); assertEquals(11, l.size()); // get all active evals a user is assigned to l = evaluationDao.getParticipantsForEval(null, EvalTestDataLoad.USER_ID, null, EvalAssignUser.TYPE_EVALUATOR, null, null, EvalConstants.EVALUATION_STATE_ACTIVE); assertNotNull(l); assertEquals(2, l.size()); // test the way that the reminders email gets participants //evaluationService.getParticipantsForEval(evaluationId, null, limitGroupIds, null, null, includeConstant, null); l = evaluationDao.getParticipantsForEval(etdl.evaluationActiveUntaken.getId(), null, null, null, null, EvalConstants.EVAL_INCLUDE_NONTAKERS, null); assertNotNull(l); assertEquals(1, l.size()); l = evaluationDao.getParticipantsForEval(etdl.evaluationActiveUntaken.getId(), null, null, null, null, EvalConstants.EVAL_INCLUDE_IN_PROGRESS, null); assertNotNull(l); assertEquals(0, l.size()); l = evaluationDao.getParticipantsForEval(etdl.evaluationActive.getId(), null, null, null, null, EvalConstants.EVAL_INCLUDE_NONTAKERS, null); assertNotNull(l); assertEquals(0, l.size()); l = evaluationDao.getParticipantsForEval(etdl.evaluationActive.getId(), null, null, null, null, EvalConstants.EVAL_INCLUDE_IN_PROGRESS, null); assertNotNull(l); assertEquals(0, l.size()); // add in a saved response EvalResponse r1 = new EvalResponse(EvalTestDataLoad.USER_ID, EvalTestDataLoad.SITE2_REF, etdl.evaluationActiveUntaken, new Date(), null, null); r1.setAnswers( new HashSet<EvalAnswer>() ); evaluationDao.save(r1); l = evaluationDao.getParticipantsForEval(etdl.evaluationActiveUntaken.getId(), null, null, null, null, EvalConstants.EVAL_INCLUDE_IN_PROGRESS, null); assertNotNull(l); assertEquals(1, l.size()); l = evaluationDao.getParticipantsForEval(etdl.evaluationActiveUntaken.getId(), null, null, null, null, EvalConstants.EVAL_INCLUDE_NONTAKERS, null); assertNotNull(l); assertEquals(0, l.size()); } public void testGetEvalsUserCanTake() { // get ones we can take List<EvalEvaluation> evals = evaluationDao.getEvalsUserCanTake(EvalTestDataLoad.USER_ID, true, true, false, 0, 0); assertNotNull(evals); assertEquals(1, evals.size()); assertEquals(etdl.evaluationActive.getId(), evals.get(0).getId()); evals = evaluationDao.getEvalsUserCanTake(EvalTestDataLoad.STUDENT_USER_ID, true, true, false, 0, 0); assertNotNull(evals); assertEquals(0, evals.size()); evals = evaluationDao.getEvalsUserCanTake(EvalTestDataLoad.MAINT_USER_ID, true, true, false, 0, 0); assertNotNull(evals); assertEquals(0, evals.size()); // admin normally takes none evals = evaluationDao.getEvalsUserCanTake(EvalTestDataLoad.ADMIN_USER_ID, true, true, false, 0, 0); assertNotNull(evals); assertEquals(0, evals.size()); // include anonymous evals = evaluationDao.getEvalsUserCanTake(EvalTestDataLoad.USER_ID, true, true, null, 0, 0); assertNotNull(evals); assertEquals(2, evals.size()); assertEquals(etdl.evaluationActive.getId(), evals.get(0).getId()); assertEquals(etdl.evaluationActiveUntaken.getId(), evals.get(1).getId()); evals = evaluationDao.getEvalsUserCanTake(EvalTestDataLoad.STUDENT_USER_ID, true, true, null, 0, 0); assertNotNull(evals); assertEquals(1, evals.size()); assertEquals(etdl.evaluationActiveUntaken.getId(), evals.get(0).getId()); evals = evaluationDao.getEvalsUserCanTake(EvalTestDataLoad.MAINT_USER_ID, true, true, null, 0, 0); assertNotNull(evals); assertEquals(1, evals.size()); assertEquals(etdl.evaluationActiveUntaken.getId(), evals.get(0).getId()); // TODO add assign groups support /** // testing instructor approval EvalAssignGroup eag = (EvalAssignGroup) evaluationDao.findById(EvalAssignGroup.class, etdl.assign1.getId()); eag.setInstructorApproval(false); // make evaluationActive unapproved evaluationDao.save(eag); // get ones we can take evals = evaluationDao.getEvalsUserCanTake(EvalTestDataLoad.USER_ID, true, true, false, 0, 0); assertNotNull(evals); assertEquals(0, evals.size()); // include anonymous evals = evaluationDao.getEvalsUserCanTake(EvalTestDataLoad.USER_ID, true, true, null, 0, 0); assertNotNull(evals); assertEquals(1, evals.size()); assertEquals(etdl.evaluationActiveUntaken.getId(), evals.get(0).getId()); **/ } public void testGetEvalsWithoutUserAssignments() { List<EvalEvaluation> evals = evaluationDao.getEvalsWithoutUserAssignments(); assertNotNull(evals); assertTrue(evals.size() > 0); } public void testGetSharedEntitiesForUser() { List<EvalTemplate> l = null; List<Long> ids = null; // test using templates String[] props = new String[] { "type" }; Object[] values = new Object[] { EvalConstants.TEMPLATE_TYPE_STANDARD }; int[] comparisons = new int[] { Restriction.EQUALS }; String[] order = new String[] {"sharing","title"}; String[] options = new String[] {"notHidden"}; String[] notEmptyOptions = new String[] {"notHidden", "notEmpty"}; // all templates visible to user l = evaluationDao.getSharedEntitiesForUser(EvalTemplate.class, EvalTestDataLoad.USER_ID, new String[] {EvalConstants.SHARING_PRIVATE, EvalConstants.SHARING_PUBLIC}, props, values, comparisons, order, options, 0, 0); assertNotNull(l); assertEquals(5, l.size()); ids = EvalTestDataLoad.makeIdList(l); assertTrue(ids.contains( etdl.templatePublic.getId() )); assertTrue(ids.contains( etdl.templatePublicUnused.getId() )); assertTrue(ids.contains( etdl.templateUser.getId() )); assertTrue(ids.contains( etdl.templateUserUnused.getId() )); assertTrue(ids.contains( etdl.templateEid.getId() )); // all templates visible to maint user l = evaluationDao.getSharedEntitiesForUser(EvalTemplate.class, EvalTestDataLoad.MAINT_USER_ID, new String[] {EvalConstants.SHARING_PRIVATE, EvalConstants.SHARING_PUBLIC}, props, values, comparisons, order, options, 0, 0); assertNotNull(l); assertEquals(4, l.size()); ids = EvalTestDataLoad.makeIdList(l); assertTrue(ids.contains( etdl.templatePublic.getId() )); assertTrue(ids.contains( etdl.templatePublicUnused.getId() )); assertTrue(ids.contains( etdl.templateUnused.getId() )); assertTrue(ids.contains( etdl.templateEid.getId() )); // all templates owned by USER l = evaluationDao.getSharedEntitiesForUser(EvalTemplate.class, EvalTestDataLoad.USER_ID, new String[] {EvalConstants.SHARING_PRIVATE}, props, values, comparisons, order, options, 0, 0); assertNotNull(l); assertEquals(2, l.size()); ids = EvalTestDataLoad.makeIdList(l); assertTrue(ids.contains( etdl.templateUser.getId() )); assertTrue(ids.contains( etdl.templateUserUnused.getId() )); // all private templates l = evaluationDao.getSharedEntitiesForUser(EvalTemplate.class, null, new String[] {EvalConstants.SHARING_PRIVATE}, props, values, comparisons, order, options, 0, 0); assertNotNull(l); assertEquals(8, l.size()); ids = EvalTestDataLoad.makeIdList(l); assertTrue(ids.contains( etdl.templateAdmin.getId() )); assertTrue(ids.contains( etdl.templateAdminNoItems.getId() )); assertTrue(ids.contains( etdl.templateUnused.getId() )); assertTrue(ids.contains( etdl.templateUser.getId() )); assertTrue(ids.contains( etdl.templateUserUnused.getId() )); assertTrue(ids.contains( etdl.templateAdminBlock.getId() )); assertTrue(ids.contains( etdl.templateUser_4.getId() )); assertTrue(ids.contains( etdl.evalsys_1007_templateUser01.getId() )); // all private non-empty templates l = evaluationDao.getSharedEntitiesForUser(EvalTemplate.class, null, new String[] {EvalConstants.SHARING_PRIVATE}, props, values, comparisons, order, notEmptyOptions, 0, 0); assertNotNull(l); assertEquals(5, l.size()); ids = EvalTestDataLoad.makeIdList(l); assertTrue(ids.contains( etdl.templateAdmin.getId() )); assertTrue(ids.contains( etdl.templateUnused.getId() )); assertTrue(ids.contains( etdl.templateUser.getId() )); assertTrue(ids.contains( etdl.templateUserUnused.getId() )); assertTrue(ids.contains( etdl.templateAdminBlock.getId() )); // all public templates l = evaluationDao.getSharedEntitiesForUser(EvalTemplate.class, null, new String[] {EvalConstants.SHARING_PUBLIC}, props, values, comparisons, order, options, 0, 0); assertNotNull(l); assertEquals(3, l.size()); ids = EvalTestDataLoad.makeIdList(l); assertTrue(ids.contains( etdl.templatePublic.getId() )); assertTrue(ids.contains( etdl.templatePublicUnused.getId() )); assertTrue(ids.contains( etdl.templateEid.getId() )); // all templates (admin would use this) l = evaluationDao.getSharedEntitiesForUser(EvalTemplate.class, null, new String[] {EvalConstants.SHARING_PRIVATE, EvalConstants.SHARING_PUBLIC, EvalConstants.SHARING_SHARED, EvalConstants.SHARING_VISIBLE}, props, values, comparisons, order, options, 0, 0); assertNotNull(l); assertEquals(11, l.size()); // all non-empty templates (admin would use this) l = evaluationDao.getSharedEntitiesForUser(EvalTemplate.class, null, new String[] {EvalConstants.SHARING_PRIVATE, EvalConstants.SHARING_PUBLIC, EvalConstants.SHARING_SHARED, EvalConstants.SHARING_VISIBLE}, props, values, comparisons, order, notEmptyOptions, 0, 0); assertNotNull(l); assertEquals(8, l.size()); // no templates (no one should do this, it throws an exception) try { l = evaluationDao.getSharedEntitiesForUser(EvalTemplate.class, null, new String[] {}, props, values, comparisons, order, notEmptyOptions, 0, 0); fail("Should have thrown an exception"); } catch (IllegalArgumentException e) { assertNotNull(e); } } public void testCountSharedEntitiesForUser() { int count = 0; // test using templates String[] props = new String[] { "type" }; Object[] values = new Object[] { EvalConstants.TEMPLATE_TYPE_STANDARD }; int[] comparisons = new int[] { Restriction.EQUALS }; String[] options = new String[] {"notHidden"}; String[] notEmptyOptions = new String[] {"notHidden", "notEmpty"}; // all templates visible to user count = evaluationDao.countSharedEntitiesForUser(EvalTemplate.class, EvalTestDataLoad.USER_ID, new String[] {EvalConstants.SHARING_PRIVATE, EvalConstants.SHARING_PUBLIC}, props, values, comparisons, options); assertEquals(5, count); // all templates visible to maint user count = evaluationDao.countSharedEntitiesForUser(EvalTemplate.class, EvalTestDataLoad.MAINT_USER_ID, new String[] {EvalConstants.SHARING_PRIVATE, EvalConstants.SHARING_PUBLIC}, props, values, comparisons, options); assertEquals(4, count); // all templates owned by USER count = evaluationDao.countSharedEntitiesForUser(EvalTemplate.class, EvalTestDataLoad.USER_ID, new String[] {EvalConstants.SHARING_PRIVATE}, props, values, comparisons, options); assertEquals(2, count); // all private templates (admin only) count = evaluationDao.countSharedEntitiesForUser(EvalTemplate.class, null, new String[] {EvalConstants.SHARING_PRIVATE}, props, values, comparisons, options); assertEquals(8, count); // all private non-empty templates (admin only) count = evaluationDao.countSharedEntitiesForUser(EvalTemplate.class, null, new String[] {EvalConstants.SHARING_PRIVATE}, props, values, comparisons, notEmptyOptions); assertEquals(5, count); // all public templates count = evaluationDao.countSharedEntitiesForUser(EvalTemplate.class, null, new String[] {EvalConstants.SHARING_PUBLIC}, props, values, comparisons, options); assertEquals(3, count); // all templates (admin would use this) count = evaluationDao.countSharedEntitiesForUser(EvalTemplate.class, null, new String[] {EvalConstants.SHARING_PRIVATE, EvalConstants.SHARING_PUBLIC, EvalConstants.SHARING_SHARED, EvalConstants.SHARING_VISIBLE}, props, values, comparisons, options); assertEquals(11, count); // all non-empty templates (admin would use this) count = evaluationDao.countSharedEntitiesForUser(EvalTemplate.class, null, new String[] {EvalConstants.SHARING_PRIVATE, EvalConstants.SHARING_PUBLIC, EvalConstants.SHARING_SHARED, EvalConstants.SHARING_VISIBLE}, props, values, comparisons, notEmptyOptions); assertEquals(8, count); } public void testGetEvaluationsByEvalGroups() { List<EvalEvaluation> l = null; List<Long> ids = null; // testing instructor approval false EvalAssignGroup eag = (EvalAssignGroup) evaluationDao.findById(EvalAssignGroup.class, etdl.assign5.getId()); eag.setInstructorApproval(false); evaluationDao.save(eag); // test getting all assigned evaluations for 2 sites l = evaluationDao.getEvaluationsByEvalGroups( new String[] {EvalTestDataLoad.SITE1_REF, EvalTestDataLoad.SITE2_REF}, null, null, null, 0, 0); assertNotNull(l); assertEquals(7, l.size()); ids = EvalTestDataLoad.makeIdList(l); assertTrue(ids.contains( etdl.evaluationNewAdmin.getId() )); assertTrue(ids.contains( etdl.evaluationActive.getId() )); assertTrue(ids.contains( etdl.evaluationActiveUntaken.getId() )); assertTrue(ids.contains( etdl.evaluationClosed.getId() )); assertTrue(ids.contains( etdl.evaluationClosedUntaken.getId() )); assertTrue(ids.contains( etdl.evaluationViewable.getId() )); // test getting all assigned (minus anonymous) evaluations for 2 sites l = evaluationDao.getEvaluationsByEvalGroups( new String[] {EvalTestDataLoad.SITE1_REF, EvalTestDataLoad.SITE2_REF}, null, null, false, 0, 0); assertNotNull(l); assertEquals(5, l.size()); ids = EvalTestDataLoad.makeIdList(l); assertTrue(ids.contains( etdl.evaluationNewAdmin.getId() )); assertTrue(ids.contains( etdl.evaluationActive.getId() )); assertTrue(ids.contains( etdl.evaluationClosed.getId() )); assertTrue(ids.contains( etdl.evaluationClosedUntaken.getId() )); assertTrue(ids.contains( etdl.evaluationViewable.getId() )); // test getting assigned evaluations by one evalGroupId l = evaluationDao.getEvaluationsByEvalGroups( new String[] {EvalTestDataLoad.SITE1_REF}, null, null, null, 0, 0); assertNotNull(l); assertEquals(6, l.size()); ids = EvalTestDataLoad.makeIdList(l); assertTrue(ids.contains( etdl.evaluationNewAdmin.getId() )); assertTrue(ids.contains( etdl.evaluationActive.getId() )); assertTrue(ids.contains( etdl.evaluationActiveUntaken.getId() )); assertTrue(ids.contains( etdl.evaluationClosed.getId() )); assertTrue(ids.contains( etdl.evaluationClosedUntaken.getId() )); l = evaluationDao.getEvaluationsByEvalGroups( new String[] {EvalTestDataLoad.SITE2_REF}, null, null, null, 0, 0); assertNotNull(l); assertEquals(3, l.size()); ids = EvalTestDataLoad.makeIdList(l); assertTrue(! ids.contains( etdl.evaluationActive.getId() )); assertTrue(ids.contains( etdl.evaluationNewAdmin.getId() )); assertTrue(ids.contains( etdl.evaluationClosed.getId() )); assertTrue(ids.contains( etdl.evaluationViewable.getId() )); // test getting by groupId and including anons (should not get any deleted or partial evals) l = evaluationDao.getEvaluationsByEvalGroups( new String[] {EvalTestDataLoad.SITE1_REF}, null, null, true, 0, 0); assertNotNull(l); assertEquals(6, l.size()); ids = EvalTestDataLoad.makeIdList(l); assertTrue(ids.contains( etdl.evaluationNewAdmin.getId() )); assertTrue(ids.contains( etdl.evaluationActive.getId() )); assertTrue(ids.contains( etdl.evaluationActiveUntaken.getId() )); assertTrue(ids.contains( etdl.evaluationClosed.getId() )); assertTrue(ids.contains( etdl.evaluationClosedUntaken.getId() )); // test that the get active part works l = evaluationDao.getEvaluationsByEvalGroups( new String[] {EvalTestDataLoad.SITE1_REF}, true, null, null, 0, 0); assertNotNull(l); assertEquals(3, l.size()); ids = EvalTestDataLoad.makeIdList(l); assertTrue(ids.contains( etdl.evaluationActive.getId() )); assertTrue(ids.contains( etdl.evaluationActiveUntaken.getId() )); assertTrue(ids.contains( etdl.evaluationGracePeriod.getId() )); l = evaluationDao.getEvaluationsByEvalGroups( new String[] {EvalTestDataLoad.SITE2_REF}, true, null, null, 0, 0); assertNotNull(l); assertEquals(0, l.size()); // active minus anon l = evaluationDao.getEvaluationsByEvalGroups( new String[] {EvalTestDataLoad.SITE1_REF}, true, null, false, 0, 0); assertNotNull(l); assertEquals(1, l.size()); ids = EvalTestDataLoad.makeIdList(l); assertTrue(ids.contains( etdl.evaluationActive.getId() )); // test that the get active plus anon works l = evaluationDao.getEvaluationsByEvalGroups( new String[] {EvalTestDataLoad.SITE2_REF}, true, null, true, 0, 0); assertNotNull(l); assertEquals(2, l.size()); ids = EvalTestDataLoad.makeIdList(l); assertTrue(ids.contains( etdl.evaluationActiveUntaken.getId() )); assertTrue(ids.contains( etdl.evaluationGracePeriod.getId() )); // test getting from an invalid evalGroupId l = evaluationDao.getEvaluationsByEvalGroups( new String[] {EvalTestDataLoad.INVALID_CONTEXT}, null, null, null, 0, 0); assertNotNull(l); assertEquals(0, l.size()); // test getting all anonymous evals l = evaluationDao.getEvaluationsByEvalGroups( new String[] {}, null, null, true, 0, 0); assertNotNull(l); assertEquals(2, l.size()); ids = EvalTestDataLoad.makeIdList(l); assertTrue(ids.contains( etdl.evaluationActiveUntaken.getId() )); // testing getting no evals l = evaluationDao.getEvaluationsByEvalGroups(null, null, null, false, 0, 0); assertNotNull(l); assertEquals(0, l.size()); // test unapproved assigned evaluations l = evaluationDao.getEvaluationsByEvalGroups( new String[] {EvalTestDataLoad.SITE1_REF}, null, false, null, 0, 0); assertNotNull(l); assertEquals(1, l.size()); ids = EvalTestDataLoad.makeIdList(l); assertTrue(ids.contains( etdl.evaluationNewAdmin.getId() )); l = evaluationDao.getEvaluationsByEvalGroups( new String[] {EvalTestDataLoad.SITE1_REF, EvalTestDataLoad.SITE2_REF}, null, false, null, 0, 0); assertNotNull(l); assertEquals(2, l.size()); ids = EvalTestDataLoad.makeIdList(l); assertTrue(ids.contains( etdl.evaluationNewAdmin.getId() )); assertTrue(ids.contains( etdl.evaluationViewable.getId() )); // test getting all APPROVED assigned evaluations l = evaluationDao.getEvaluationsByEvalGroups( new String[] {EvalTestDataLoad.SITE1_REF}, null, true, null, 0, 0); assertNotNull(l); assertEquals(5, l.size()); ids = EvalTestDataLoad.makeIdList(l); assertTrue(ids.contains( etdl.evaluationActive.getId() )); assertTrue(ids.contains( etdl.evaluationActiveUntaken.getId() )); assertTrue(ids.contains( etdl.evaluationClosed.getId() )); assertTrue(ids.contains( etdl.evaluationClosedUntaken.getId() )); l = evaluationDao.getEvaluationsByEvalGroups( new String[] {EvalTestDataLoad.SITE1_REF, EvalTestDataLoad.SITE2_REF}, null, true, null, 0, 0); assertNotNull(l); assertEquals(6, l.size()); ids = EvalTestDataLoad.makeIdList(l); assertTrue(ids.contains( etdl.evaluationNewAdmin.getId() )); assertTrue(ids.contains( etdl.evaluationActive.getId() )); assertTrue(ids.contains( etdl.evaluationActiveUntaken.getId() )); assertTrue(ids.contains( etdl.evaluationClosed.getId() )); assertTrue(ids.contains( etdl.evaluationClosedUntaken.getId() )); // // test getting taken evals only // l = evaluationDao.getEvaluationsByEvalGroups( // new String[] {EvalTestDataLoad.SITE1_REF, EvalTestDataLoad.SITE2_REF}, null, null, null, true, EvalTestDataLoad.USER_ID, 0, 0); // assertNotNull(l); // assertEquals(3, l.size()); // ids = EvalTestDataLoad.makeIdList(l); // assertTrue(ids.contains( etdl.evaluationActive.getId() )); // assertTrue(ids.contains( etdl.evaluationClosed.getId() )); // assertTrue(ids.contains( etdl.evaluationViewable.getId() )); // l = evaluationDao.getEvaluationsByEvalGroups( // new String[] {EvalTestDataLoad.SITE1_REF}, null, null, null, true, EvalTestDataLoad.USER_ID, 0, 0); // assertNotNull(l); // assertEquals(2, l.size()); // ids = EvalTestDataLoad.makeIdList(l); // assertTrue(ids.contains( etdl.evaluationActive.getId() )); // assertTrue(ids.contains( etdl.evaluationClosed.getId() )); // l = evaluationDao.getEvaluationsByEvalGroups( // new String[] {EvalTestDataLoad.SITE2_REF}, null, null, null, true, EvalTestDataLoad.USER_ID, 0, 0); // assertNotNull(l); // assertEquals(2, l.size()); // ids = EvalTestDataLoad.makeIdList(l); // assertTrue(ids.contains( etdl.evaluationClosed.getId() )); // assertTrue(ids.contains( etdl.evaluationViewable.getId() )); // // test getting untaken evals only // l = evaluationDao.getEvaluationsByEvalGroups( // new String[] {EvalTestDataLoad.SITE1_REF, EvalTestDataLoad.SITE2_REF}, null, null, null, false, EvalTestDataLoad.USER_ID, 0, 0); // assertNotNull(l); // assertEquals(3, l.size()); // ids = EvalTestDataLoad.makeIdList(l); // assertTrue(ids.contains( etdl.evaluationNewAdmin.getId() )); // assertTrue(ids.contains( etdl.evaluationActiveUntaken.getId() )); // assertTrue(ids.contains( etdl.evaluationClosedUntaken.getId() )); // l = evaluationDao.getEvaluationsByEvalGroups( // new String[] {EvalTestDataLoad.SITE2_REF}, null, null, null, false, EvalTestDataLoad.USER_ID, 0, 0); // assertNotNull(l); // assertEquals(4, l.size()); // ids = EvalTestDataLoad.makeIdList(l); // assertTrue(ids.contains( etdl.evaluationNewAdmin.getId() )); // assertTrue(ids.contains( etdl.evaluationActive.getId() )); // assertTrue(ids.contains( etdl.evaluationActiveUntaken.getId() )); // assertTrue(ids.contains( etdl.evaluationClosedUntaken.getId() )); } public void testGetEvaluationsForOwnerAndGroups() { List<EvalEvaluation> l = null; List<Long> ids = null; // test getting all evals l = evaluationDao.getEvaluationsForOwnerAndGroups(null, null, null, 0, 0, false); assertNotNull(l); assertEquals(19, l.size()); // check the order ids = EvalTestDataLoad.makeIdList(l); assertEquals(ids.get(0), etdl.evaluationViewable.getId()); assertEquals(ids.get(1), etdl.evaluationClosed_viewIgnoreDates.getId()); assertEquals(ids.get(2), etdl.evaluationClosed.getId()); assertEquals(ids.get(3), etdl.evaluationClosedUntaken.getId()); assertEquals(ids.get(4), etdl.evaluationGracePeriod.getId()); assertEquals(ids.get(5), etdl.evaluationDue_viewIgnoreDates.getId()); assertEquals(ids.get(6), etdl.evaluationActive.getId()); assertEquals(ids.get(7), etdl.evaluationProvided.getId()); assertEquals(ids.get(8), etdl.evaluationActiveUntaken.getId()); assertEquals(ids.get(9), etdl.evaluationActive_viewIgnoreDates.getId()); assertEquals(ids.get(10), evalUnLocked.getId()); assertEquals(ids.get(11), etdl.evaluationNewAdmin.getId()); assertEquals(ids.get(12), etdl.evaluationNew.getId()); assertEquals(ids.get(13), etdl.evaluation_allRoleAssignments_allRolesParticipate.getId()); assertEquals(ids.get(14), etdl.evaluation_allRoleAssignments_notAllRolesParticipate.getId()); assertEquals(ids.get(15), etdl.evaluation_noAssignments_allRolesParticipate.getId()); assertEquals(ids.get(16), etdl.evaluation_noAssignments_notAllRolesParticipate.getId()); assertEquals(ids.get(17), etdl.evaluation_simpleAssignments_allRolesParticipate.getId()); assertEquals(ids.get(18), etdl.evaluation_simpleAssignments_notAllRolesParticipate.getId()); // test getting all evals with limit l = evaluationDao.getEvaluationsForOwnerAndGroups(null, null, null, 0, 4, false); assertNotNull(l); assertEquals(4, l.size()); ids = EvalTestDataLoad.makeIdList(l); // check order and return values assertEquals(ids.get(0), etdl.evaluationViewable.getId() ); assertEquals(ids.get(1), etdl.evaluationClosed_viewIgnoreDates.getId() ); assertEquals(ids.get(2), etdl.evaluationClosed.getId() ); assertEquals(ids.get(3), etdl.evaluationClosedUntaken.getId() ); l = evaluationDao.getEvaluationsForOwnerAndGroups(null, null, null, 3, 5, false); assertNotNull(l); assertEquals(5, l.size()); ids = EvalTestDataLoad.makeIdList(l); // check order and return values assertEquals(ids.get(0), etdl.evaluationClosedUntaken.getId() ); assertEquals(ids.get(1), etdl.evaluationGracePeriod.getId() ); assertEquals(ids.get(2), etdl.evaluationDue_viewIgnoreDates.getId() ); assertEquals(ids.get(3), etdl.evaluationActive.getId() ); assertEquals(ids.get(4), etdl.evaluationProvided.getId() ); // test filtering by owner l = evaluationDao.getEvaluationsForOwnerAndGroups(EvalTestDataLoad.ADMIN_USER_ID, null, null, 0, 0, false); assertNotNull(l); assertEquals(5, l.size()); ids = EvalTestDataLoad.makeIdList(l); assertTrue(ids.contains( etdl.evaluationNewAdmin.getId() )); assertTrue(ids.contains( etdl.evaluationClosed.getId() )); assertTrue(ids.contains( etdl.evaluationClosedUntaken.getId() )); assertTrue(ids.contains( etdl.evaluationGracePeriod.getId() )); assertTrue(ids.contains( etdl.evaluationViewable.getId() )); l = evaluationDao.getEvaluationsForOwnerAndGroups(EvalTestDataLoad.USER_ID, null, null, 0, 0, false); assertNotNull(l); assertEquals(0, l.size()); ids = EvalTestDataLoad.makeIdList(l); // test filtering by groups l = evaluationDao.getEvaluationsForOwnerAndGroups(null, new String[] {EvalTestDataLoad.SITE1_REF}, null, 0, 0, false); assertNotNull(l); assertEquals(6, l.size()); ids = EvalTestDataLoad.makeIdList(l); assertTrue(ids.contains( etdl.evaluationActive.getId() )); assertTrue(ids.contains( etdl.evaluationActiveUntaken.getId() )); assertTrue(ids.contains( etdl.evaluationClosed.getId() )); assertTrue(ids.contains( etdl.evaluationClosedUntaken.getId() )); assertTrue(ids.contains( etdl.evaluationGracePeriod.getId() )); assertTrue(ids.contains( etdl.evaluationNewAdmin.getId() )); // test filtering by owner and groups l = evaluationDao.getEvaluationsForOwnerAndGroups(EvalTestDataLoad.ADMIN_USER_ID, new String[] {EvalTestDataLoad.SITE1_REF}, null, 0, 0, false); assertNotNull(l); assertEquals(7, l.size()); ids = EvalTestDataLoad.makeIdList(l); assertTrue(ids.contains( etdl.evaluationActive.getId() )); assertTrue(ids.contains( etdl.evaluationActiveUntaken.getId() )); assertTrue(ids.contains( etdl.evaluationClosed.getId() )); assertTrue(ids.contains( etdl.evaluationClosedUntaken.getId() )); assertTrue(ids.contains( etdl.evaluationGracePeriod.getId() )); assertTrue(ids.contains( etdl.evaluationNewAdmin.getId() )); assertTrue(ids.contains( etdl.evaluationViewable.getId() )); } /** * Test method for {@link org.sakaiproject.evaluation.dao.EvaluationDaoImpl#getAnswers(java.lang.Long, java.lang.Long)}. */ public void testGetAnswers() { Set<EvalAnswer> s = null; List<EvalAnswer> l = null; List<Long> ids = null; s = etdl.response2.getAnswers(); assertNotNull(s); assertEquals(2, s.size()); ids = EvalTestDataLoad.makeIdList(s); assertTrue(ids.contains( etdl.answer2_2A.getId() )); assertTrue(ids.contains( etdl.answer2_5A.getId() )); // test getting all answers first l = evaluationDao.getAnswers(etdl.evaluationClosed.getId(), null, null); assertNotNull(l); assertEquals(3, l.size()); ids = EvalTestDataLoad.makeIdList(l); assertTrue(ids.contains( etdl.answer2_2A.getId() )); assertTrue(ids.contains( etdl.answer2_5A.getId() )); assertTrue(ids.contains( etdl.answer3_2A.getId() )); // restrict to template item l = evaluationDao.getAnswers(etdl.evaluationClosed.getId(), null, new Long[] {etdl.templateItem2A.getId()}); assertNotNull(l); assertEquals(2, l.size()); ids = EvalTestDataLoad.makeIdList(l); assertTrue(ids.contains( etdl.answer2_2A.getId() )); assertTrue(ids.contains( etdl.answer3_2A.getId() )); // restrict to multiple template items l = evaluationDao.getAnswers(etdl.evaluationClosed.getId(), null, new Long[] {etdl.templateItem2A.getId(), etdl.templateItem5A.getId()}); assertNotNull(l); assertEquals(3, l.size()); ids = EvalTestDataLoad.makeIdList(l); assertTrue(ids.contains( etdl.answer2_2A.getId() )); assertTrue(ids.contains( etdl.answer2_5A.getId() )); assertTrue(ids.contains( etdl.answer3_2A.getId() )); // test restricting to groups l = evaluationDao.getAnswers(etdl.evaluationClosed.getId(), new String[] {EvalTestDataLoad.SITE1_REF}, null); assertNotNull(l); assertEquals(2, l.size()); ids = EvalTestDataLoad.makeIdList(l); assertTrue(ids.contains( etdl.answer2_2A.getId() )); assertTrue(ids.contains( etdl.answer2_5A.getId() )); l = evaluationDao.getAnswers(etdl.evaluationClosed.getId(), new String[] {EvalTestDataLoad.SITE2_REF}, null); assertNotNull(l); assertEquals(1, l.size()); ids = EvalTestDataLoad.makeIdList(l); assertTrue(ids.contains( etdl.answer3_2A.getId() )); // test restricting to groups and TIs l = evaluationDao.getAnswers(etdl.evaluationClosed.getId(), new String[] {EvalTestDataLoad.SITE1_REF}, new Long[] {etdl.templateItem2A.getId()}); assertNotNull(l); assertEquals(1, l.size()); ids = EvalTestDataLoad.makeIdList(l); assertTrue(ids.contains( etdl.answer2_2A.getId() )); l = evaluationDao.getAnswers(etdl.evaluationClosed.getId(), new String[] {EvalTestDataLoad.SITE2_REF}, new Long[] {etdl.templateItem2A.getId()}); assertNotNull(l); assertEquals(1, l.size()); ids = EvalTestDataLoad.makeIdList(l); assertTrue(ids.contains( etdl.answer3_2A.getId() )); // test restricting to answers not in this group l = evaluationDao.getAnswers(etdl.evaluationClosed.getId(), new String[] {EvalTestDataLoad.SITE2_REF}, new Long[] {etdl.templateItem5A.getId()}); assertNotNull(l); assertEquals(0, l.size()); // test template item that is not in this evaluation l = evaluationDao.getAnswers(etdl.evaluationClosed.getId(), null, new Long[] {etdl.templateItem1U.getId()}); assertNotNull(l); assertEquals(0, l.size()); // test invalid eval id returns nothing l = evaluationDao.getAnswers(EvalTestDataLoad.INVALID_LONG_ID, null, null); assertNotNull(l); assertEquals(0, l.size()); } /** * Test method for {@link org.sakaiproject.evaluation.dao.EvaluationDaoImpl#removeTemplateItems(org.sakaiproject.evaluation.model.EvalTemplateItem[])}. */ public void testRemoveTemplateItems() { // test removing a single templateItem EvalTemplateItem eti1 = (EvalTemplateItem) evaluationDao.findById(EvalTemplateItem.class, etdl.templateItem1User.getId()); // verify that the item/template link exists before removal assertNotNull( eti1 ); assertNotNull( eti1.getItem() ); assertNotNull( eti1.getTemplate() ); assertNotNull( eti1.getItem().getTemplateItems() ); assertNotNull( eti1.getTemplate().getTemplateItems() ); assertFalse( eti1.getItem().getTemplateItems().isEmpty() ); assertFalse( eti1.getTemplate().getTemplateItems().isEmpty() ); assertTrue( eti1.getItem().getTemplateItems().contains( eti1 ) ); assertTrue( eti1.getTemplate().getTemplateItems().contains( eti1 ) ); int itemsSize = eti1.getItem().getTemplateItems().size(); int templatesSize = eti1.getTemplate().getTemplateItems().size(); // test removing templateItem OK evaluationDao.removeTemplateItems( new EvalTemplateItem[] {etdl.templateItem1User} ); assertNull( evaluationDao.findById(EvalTemplateItem.class, etdl.templateItem1User.getId()) ); // verify that the item/template link no longer exists assertNotNull( eti1.getItem().getTemplateItems() ); assertNotNull( eti1.getTemplate().getTemplateItems() ); assertFalse( eti1.getItem().getTemplateItems().isEmpty() ); assertFalse( eti1.getTemplate().getTemplateItems().isEmpty() ); assertEquals( itemsSize-1, eti1.getItem().getTemplateItems().size() ); assertEquals( templatesSize-1, eti1.getTemplate().getTemplateItems().size() ); assertTrue(! eti1.getItem().getTemplateItems().contains( eti1 ) ); assertTrue(! eti1.getTemplate().getTemplateItems().contains( eti1 ) ); // test removing a group of templateItems (item 3 and 5 from UnUsed) EvalTemplateItem eti3 = (EvalTemplateItem) evaluationDao.findById(EvalTemplateItem.class, etdl.templateItem3U.getId()); EvalTemplateItem eti5 = (EvalTemplateItem) evaluationDao.findById(EvalTemplateItem.class, etdl.templateItem5U.getId()); // verify that the item/template link exists before removal assertNotNull( eti3 ); assertNotNull( eti3.getItem() ); assertNotNull( eti3.getTemplate() ); assertNotNull( eti3.getItem().getTemplateItems() ); assertNotNull( eti3.getTemplate().getTemplateItems() ); assertFalse( eti3.getItem().getTemplateItems().isEmpty() ); assertFalse( eti3.getTemplate().getTemplateItems().isEmpty() ); assertTrue( eti3.getItem().getTemplateItems().contains( eti3 ) ); assertTrue( eti3.getTemplate().getTemplateItems().contains( eti3 ) ); int itemsSize3 = eti3.getItem().getTemplateItems().size(); assertNotNull( eti5 ); assertNotNull( eti5.getItem() ); assertNotNull( eti5.getTemplate() ); assertNotNull( eti5.getItem().getTemplateItems() ); assertNotNull( eti5.getTemplate().getTemplateItems() ); assertFalse( eti5.getItem().getTemplateItems().isEmpty() ); assertFalse( eti5.getTemplate().getTemplateItems().isEmpty() ); assertTrue( eti5.getItem().getTemplateItems().contains( eti5 ) ); assertTrue( eti5.getTemplate().getTemplateItems().contains( eti5 ) ); int itemsSize5 = eti5.getItem().getTemplateItems().size(); // test removing templateItem OK evaluationDao.removeTemplateItems( new EvalTemplateItem[] {etdl.templateItem3U, etdl.templateItem5U} ); assertNull( evaluationDao.findById(EvalTemplateItem.class, etdl.templateItem3U.getId()) ); assertNull( evaluationDao.findById(EvalTemplateItem.class, etdl.templateItem5U.getId()) ); // verify that the item/template link no longer exists assertNotNull( eti3.getItem().getTemplateItems() ); assertFalse( eti3.getItem().getTemplateItems().isEmpty() ); assertEquals( itemsSize3-1, eti3.getItem().getTemplateItems().size() ); assertTrue(! eti3.getItem().getTemplateItems().contains( eti3 ) ); assertNotNull( eti5.getItem().getTemplateItems() ); assertFalse( eti5.getItem().getTemplateItems().isEmpty() ); assertEquals( itemsSize5-1, eti5.getItem().getTemplateItems().size() ); assertTrue(! eti5.getItem().getTemplateItems().contains( eti5 ) ); // should be only one items left in this template now assertNotNull( eti3.getTemplate().getTemplateItems() ); assertEquals(1, eti3.getTemplate().getTemplateItems().size() ); EvalTemplate template = (EvalTemplate) evaluationDao.findById(EvalTemplate.class, eti3.getTemplate().getId()); assertNotNull( template ); assertNotNull( template.getTemplateItems() ); assertEquals(1, template.getTemplateItems().size() ); } /** * Test method for {@link org.sakaiproject.evaluation.dao.EvaluationDaoImpl#getTemplateItemsByTemplate(java.lang.Long, java.lang.String[], java.lang.String[], java.lang.String[])}. */ public void testGetTemplateItemsByTemplate() { List<EvalTemplateItem> l = null; List<Long> ids = null; // test the basic return of items in the template l = evaluationDao.getTemplateItemsByTemplate(etdl.templateAdmin.getId(), null, null, null); assertNotNull(l); assertEquals(3, l.size()); ids = EvalTestDataLoad.makeIdList(l); assertTrue(ids.contains( etdl.templateItem2A.getId() )); assertTrue(ids.contains( etdl.templateItem3A.getId() )); assertTrue(ids.contains( etdl.templateItem5A.getId() )); // check that the return order is correct assertEquals( 1, ((EvalTemplateItem)l.get(0)).getDisplayOrder().intValue() ); assertEquals( 2, ((EvalTemplateItem)l.get(1)).getDisplayOrder().intValue() ); assertEquals( 3, ((EvalTemplateItem)l.get(2)).getDisplayOrder().intValue() ); // test getting just the top level items l = evaluationDao.getTemplateItemsByTemplate(etdl.templateAdminComplex.getId(), null, null, null); assertNotNull(l); assertEquals(0, l.size()); // test getting instructor items l = evaluationDao.getTemplateItemsByTemplate(etdl.templateAdminComplex.getId(), null, new String[] { EvalTestDataLoad.MAINT_USER_ID }, null); assertNotNull(l); assertEquals(1, l.size()); ids = EvalTestDataLoad.makeIdList(l); assertTrue(ids.contains( etdl.templateItem10AC1.getId() )); // test getting course items l = evaluationDao.getTemplateItemsByTemplate(etdl.templateAdminComplex.getId(), null, null, new String[] { EvalTestDataLoad.SITE1_REF, EvalTestDataLoad.SITE2_REF }); assertNotNull(l); assertEquals(2, l.size()); ids = EvalTestDataLoad.makeIdList(l); assertTrue(ids.contains( etdl.templateItem10AC2.getId() )); assertTrue(ids.contains( etdl.templateItem10AC3.getId() )); // test getting both together l = evaluationDao.getTemplateItemsByTemplate(etdl.templateAdminComplex.getId(), null, new String[] { EvalTestDataLoad.MAINT_USER_ID }, new String[] { EvalTestDataLoad.SITE1_REF, EvalTestDataLoad.SITE2_REF }); assertNotNull(l); assertEquals(3, l.size()); ids = EvalTestDataLoad.makeIdList(l); assertTrue(ids.contains( etdl.templateItem10AC1.getId() )); assertTrue(ids.contains( etdl.templateItem10AC2.getId() )); assertTrue(ids.contains( etdl.templateItem10AC3.getId() )); // test that a bunch of invalid stuff simply returns no results l = evaluationDao.getTemplateItemsByTemplate(etdl.templateAdminComplex.getId(), new String[] { EvalTestDataLoad.INVALID_CONSTANT_STRING }, new String[] { EvalTestDataLoad.INVALID_CONSTANT_STRING, EvalTestDataLoad.INVALID_CONSTANT_STRING }, new String[] { EvalTestDataLoad.INVALID_CONSTANT_STRING, EvalTestDataLoad.INVALID_CONSTANT_STRING, EvalTestDataLoad.INVALID_CONSTANT_STRING }); assertNotNull(l); assertEquals(0, l.size()); } public void testGetResponseIds() { List<Long> l = null; l = evaluationDao.getResponseIds(etdl.evaluationClosed.getId(), null, null, null); assertNotNull(l); assertEquals(3, l.size()); assertTrue( l.contains(etdl.response2.getId()) ); assertTrue( l.contains(etdl.response3.getId()) ); assertTrue( l.contains(etdl.response6.getId()) ); l = evaluationDao.getResponseIds(etdl.evaluationClosed.getId(), new String[] {EvalTestDataLoad.SITE1_REF, EvalTestDataLoad.SITE2_REF}, null, null); assertNotNull(l); assertEquals(3, l.size()); assertTrue( l.contains(etdl.response2.getId()) ); assertTrue( l.contains(etdl.response3.getId()) ); assertTrue( l.contains(etdl.response6.getId()) ); l = evaluationDao.getResponseIds(etdl.evaluationClosed.getId(), new String[] {EvalTestDataLoad.SITE1_REF}, null, null); assertNotNull(l); assertEquals(1, l.size()); assertTrue( l.contains(etdl.response2.getId()) ); // test invalid evalid l = evaluationDao.getResponseIds(EvalTestDataLoad.INVALID_LONG_ID, null, null, null); assertNotNull(l); assertEquals(0, l.size()); } public void testRemoveResponses() { // check that response and answer are removed correctly int curR = evaluationDao.countAll(EvalResponse.class); int curA = evaluationDao.countAll(EvalAnswer.class); evaluationDao.removeResponses(new Long[] {etdl.response1.getId()}); int remainR = evaluationDao.countAll(EvalResponse.class); int remainA = evaluationDao.countAll(EvalResponse.class); assertTrue(remainR < curR); assertTrue(remainA < curA); // stupid hibernate is making this test a pain -AZ // assertNull( evaluationDao.findById(EvalResponse.class, etdl.response1.getId()) ); // assertNull( evaluationDao.findById(EvalAnswer.class, etdl.answer1_1.getId()) ); } /** * Test method for {@link org.sakaiproject.evaluation.dao.EvaluationDaoImpl#getEvalCategories(String)} */ public void testGetEvalCategories() { List<String> l = null; // test the basic return of categories l = evaluationDao.getEvalCategories(null); assertNotNull(l); assertEquals(2, l.size()); assertTrue( l.contains(EvalTestDataLoad.EVAL_CATEGORY_1) ); assertTrue( l.contains(EvalTestDataLoad.EVAL_CATEGORY_2) ); // test the return of cats for a user l = evaluationDao.getEvalCategories(EvalTestDataLoad.MAINT_USER_ID); assertNotNull(l); assertEquals(1, l.size()); assertTrue( l.contains(EvalTestDataLoad.EVAL_CATEGORY_1) ); } /** * Test method for {@link org.sakaiproject.evaluation.dao.EvaluationDaoImpl#getNodeIdForEvalGroup(java.lang.String)}. */ public void testGetNodeIdForEvalGroup() { String nodeId = null; nodeId = evaluationDao.getNodeIdForEvalGroup(EvalTestDataLoad.SITE1_REF); assertNotNull(nodeId); assertEquals(EvalTestDataLoad.NODE_ID1, nodeId); nodeId = evaluationDao.getNodeIdForEvalGroup(EvalTestDataLoad.SITE2_REF); assertNotNull(nodeId); assertEquals(EvalTestDataLoad.NODE_ID1, nodeId); nodeId = evaluationDao.getNodeIdForEvalGroup(EvalTestDataLoad.SITE3_REF); assertNotNull(nodeId); assertEquals(EvalTestDataLoad.NODE_ID2, nodeId); nodeId = evaluationDao.getNodeIdForEvalGroup("xxxxxxxxxxxxxxxxx"); assertNull(nodeId); } public void testGetTemplateItemsByEvaluation() { List<EvalTemplateItem> templateItems = null; templateItems = evaluationDao.getTemplateItemsByEvaluation(etdl.evaluationActive.getId(), null, null, null); assertNotNull(templateItems); assertEquals(2, templateItems.size()); templateItems = evaluationDao.getTemplateItemsByEvaluation(etdl.evaluationClosed.getId(), null, null, null); assertNotNull(templateItems); assertEquals(3, templateItems.size()); try { templateItems = evaluationDao.getTemplateItemsByEvaluation(EvalTestDataLoad.INVALID_LONG_ID, null, null, null); fail("Should have thrown an exception"); } catch (IllegalArgumentException e) { assertNotNull(e); } } // public void testGetTemplateIdsForEvaluation() { // List<Long> templateIds = null; // templateIds = evaluationDao.getTemplateIdForEvaluation(etdl.evaluationActive.getId()); // assertNotNull(templateIds); // assertEquals(1, templateIds.size()); // assertTrue( templateIds.contains( etdl.templateUser.getId() ) ); // templateIds = evaluationDao.getTemplateIdForEvaluation(etdl.evaluationClosed.getId()); // assertNotNull(templateIds); // assertEquals(2, templateIds.size()); // assertTrue( templateIds.contains( etdl.templateAdmin.getId() ) ); // assertTrue( templateIds.contains( etdl.templateAdminComplex.getId() ) ); // templateIds = evaluationDao.getTemplateIdForEvaluation(EvalTestDataLoad.INVALID_LONG_ID); // assertNotNull(templateIds); // assertEquals(0, templateIds.size()); public void testGetResponseUserIds() { Set<String> userIds = null; // check getting responders from complete evaluation userIds = evaluationDao.getResponseUserIds(etdl.evaluationClosed.getId(), null, true); assertNotNull(userIds); assertEquals(2, userIds.size()); assertTrue(userIds.contains(EvalTestDataLoad.USER_ID)); assertTrue(userIds.contains(EvalTestDataLoad.STUDENT_USER_ID)); // check getting incomplete responders from complete evaluation userIds = evaluationDao.getResponseUserIds(etdl.evaluationClosed.getId(), null, false); assertNotNull(userIds); assertEquals(0, userIds.size()); // check getting all responders from complete evaluation userIds = evaluationDao.getResponseUserIds(etdl.evaluationClosed.getId(), null, null); assertNotNull(userIds); assertEquals(2, userIds.size()); assertTrue(userIds.contains(EvalTestDataLoad.USER_ID)); assertTrue(userIds.contains(EvalTestDataLoad.STUDENT_USER_ID)); // test getting from subset of the groups userIds = evaluationDao.getResponseUserIds(etdl.evaluationClosed.getId(), new String[] {EvalTestDataLoad.SITE1_REF}, true); assertNotNull(userIds); assertEquals(1, userIds.size()); assertTrue(userIds.contains(EvalTestDataLoad.USER_ID)); // test getting none userIds = evaluationDao.getResponseUserIds(etdl.evaluationActiveUntaken.getId(), null, true); assertNotNull(userIds); assertEquals(0, userIds.size()); // test using invalid group ids retrieves no results userIds = evaluationDao.getResponseUserIds(etdl.evaluationClosed.getId(), new String[] {"xxxxxx", "fakeyandnotreal"}, true); assertNotNull(userIds); assertEquals(0, userIds.size()); } public void testGetViewableEvalGroupIds() { Set<String> evalGroupIds = null; // check for groups that are fully enabled evalGroupIds = evaluationDao.getViewableEvalGroupIds(etdl.evaluationClosed.getId(), EvalAssignUser.TYPE_EVALUATEE, null); assertNotNull(evalGroupIds); assertEquals(1, evalGroupIds.size()); assertTrue(evalGroupIds.contains(etdl.assign3.getEvalGroupId())); evalGroupIds = evaluationDao.getViewableEvalGroupIds(etdl.evaluationClosed.getId(), EvalAssignUser.TYPE_EVALUATOR, null); assertNotNull(evalGroupIds); assertEquals(1, evalGroupIds.size()); assertTrue(evalGroupIds.contains(etdl.assign4.getEvalGroupId())); // check for mixture - not in the test data // evalGroupIds = evaluationDao.getViewableEvalGroupIds(etdl.evaluationNewAdmin.getId(), EvalAssignUser.TYPE_EVALUATEE, null); // assertNotNull(evalGroupIds); // assertEquals(2, evalGroupIds.size()); // assertTrue(evalGroupIds.contains(etdl.assign7.getEvalGroupId())); // assertTrue(evalGroupIds.contains(etdl.assignGroupProvided.getEvalGroupId())); evalGroupIds = evaluationDao.getViewableEvalGroupIds(etdl.evaluationNewAdmin.getId(), EvalAssignUser.TYPE_EVALUATOR, null); assertNotNull(evalGroupIds); assertEquals(1, evalGroupIds.size()); assertTrue(evalGroupIds.contains(etdl.assign6.getEvalGroupId())); // check for unassigned to return none evalGroupIds = evaluationDao.getViewableEvalGroupIds(etdl.evaluationNew.getId(), EvalAssignUser.TYPE_EVALUATEE, null); assertNotNull(evalGroupIds); assertEquals(0, evalGroupIds.size()); evalGroupIds = evaluationDao.getViewableEvalGroupIds(etdl.evaluationNew.getId(), EvalAssignUser.TYPE_EVALUATOR, null); assertNotNull(evalGroupIds); assertEquals(0, evalGroupIds.size()); // check that other perms return nothing evalGroupIds = evaluationDao.getViewableEvalGroupIds(etdl.evaluationNewAdmin.getId(), EvalAssignUser.TYPE_ASSISTANT, null); assertNotNull(evalGroupIds); assertEquals(0, evalGroupIds.size()); // check for limits on the returns evalGroupIds = evaluationDao.getViewableEvalGroupIds(etdl.evaluationClosed.getId(), EvalAssignUser.TYPE_EVALUATEE, new String[] {etdl.assign3.getEvalGroupId()}); assertNotNull(evalGroupIds); assertEquals(1, evalGroupIds.size()); assertTrue(evalGroupIds.contains(etdl.assign3.getEvalGroupId())); evalGroupIds = evaluationDao.getViewableEvalGroupIds(etdl.evaluationNewAdmin.getId(), EvalAssignUser.TYPE_EVALUATEE, new String[] {etdl.assign7.getEvalGroupId()}); assertNotNull(evalGroupIds); assertEquals(1, evalGroupIds.size()); assertTrue(evalGroupIds.contains(etdl.assign7.getEvalGroupId())); // check for limits on the returns which limit it to none evalGroupIds = evaluationDao.getViewableEvalGroupIds(etdl.evaluationClosed.getId(), EvalAssignUser.TYPE_EVALUATEE, new String[] {EvalTestDataLoad.INVALID_CONSTANT_STRING}); assertNotNull(evalGroupIds); assertEquals(0, evalGroupIds.size()); // check for null evaluation id try { evaluationDao.getViewableEvalGroupIds(null, EvalConstants.PERM_ASSIGN_EVALUATION, null); fail("Should have thrown an exception"); } catch (IllegalArgumentException e) { assertNotNull(e); } } public void testGetEvalAdhocGroupsByUserAndPerm() { List<EvalAdhocGroup> l = null; List<Long> ids = null; // make sure the group has the user EvalAdhocGroup checkGroup = (EvalAdhocGroup) evaluationDao.findById(EvalAdhocGroup.class, etdl.group2.getId()); assertTrue( ArrayUtils.contains(checkGroup.getParticipantIds(), etdl.user3.getUserId()) ); l = evaluationDao.getEvalAdhocGroupsByUserAndPerm(etdl.user3.getUserId(), EvalConstants.PERM_TAKE_EVALUATION); assertNotNull(l); assertEquals(1, l.size()); assertEquals(etdl.group2.getId(), l.get(0).getId()); l = evaluationDao.getEvalAdhocGroupsByUserAndPerm(EvalTestDataLoad.STUDENT_USER_ID, EvalConstants.PERM_TAKE_EVALUATION); assertNotNull(l); assertEquals(1, l.size()); assertEquals(etdl.group1.getId(), l.get(0).getId()); l = evaluationDao.getEvalAdhocGroupsByUserAndPerm(etdl.user1.getUserId(), EvalConstants.PERM_TAKE_EVALUATION); assertNotNull(l); assertEquals(2, l.size()); ids = EvalTestDataLoad.makeIdList(l); assertTrue(ids.contains(etdl.group1.getId())); assertTrue(ids.contains(etdl.group2.getId())); l = evaluationDao.getEvalAdhocGroupsByUserAndPerm(etdl.user2.getUserId(), EvalConstants.PERM_TAKE_EVALUATION); assertNotNull(l); assertEquals(0, l.size()); } public void testIsUserAllowedInAdhocGroup() { boolean allowed = false; allowed = evaluationDao.isUserAllowedInAdhocGroup(EvalTestDataLoad.USER_ID, EvalConstants.PERM_TAKE_EVALUATION, etdl.group2.getEvalGroupId()); assertTrue(allowed); allowed = evaluationDao.isUserAllowedInAdhocGroup(EvalTestDataLoad.USER_ID, EvalConstants.PERM_BE_EVALUATED, etdl.group2.getEvalGroupId()); assertFalse(allowed); allowed = evaluationDao.isUserAllowedInAdhocGroup(etdl.user1.getUserId(), EvalConstants.PERM_TAKE_EVALUATION, etdl.group1.getEvalGroupId()); assertTrue(allowed); allowed = evaluationDao.isUserAllowedInAdhocGroup(etdl.user1.getUserId(), EvalConstants.PERM_BE_EVALUATED, etdl.group1.getEvalGroupId()); assertFalse(allowed); allowed = evaluationDao.isUserAllowedInAdhocGroup(etdl.user2.getUserId(), EvalConstants.PERM_TAKE_EVALUATION, etdl.group1.getEvalGroupId()); assertFalse(allowed); allowed = evaluationDao.isUserAllowedInAdhocGroup(etdl.user2.getUserId(), EvalConstants.PERM_BE_EVALUATED, etdl.group1.getEvalGroupId()); assertFalse(allowed); } // LOCKING tests /** * Test method for {@link org.sakaiproject.evaluation.dao.EvaluationDaoImpl#lockScale(org.sakaiproject.evaluation.model.EvalScale, java.lang.Boolean)}. */ public void testLockScale() { // check that locked scale gets unlocked (no locking item) assertTrue( scaleLocked.getLocked().booleanValue() ); assertTrue( evaluationDao.lockScale( scaleLocked, Boolean.FALSE ) ); assertFalse( scaleLocked.getLocked().booleanValue() ); // check that unlocking an unlocked scale is not a problem assertFalse( evaluationDao.lockScale( scaleLocked, Boolean.FALSE ) ); // check that locked scale that is locked by an item cannot be unlocked EvalScale scale1 = (EvalScale) evaluationDao.findById(EvalScale.class, etdl.scale1.getId()); assertTrue( scale1.getLocked().booleanValue() ); assertFalse( evaluationDao.lockScale( scale1, Boolean.FALSE ) ); assertTrue( scale1.getLocked().booleanValue() ); // check that locking a locked scale is not a problem assertFalse( evaluationDao.lockScale( scale1, Boolean.TRUE ) ); // check that new scale cannot be unlocked try { evaluationDao.lockScale( new EvalScale(EvalTestDataLoad.ADMIN_USER_ID, "new scale", EvalConstants.SCALE_MODE_SCALE, EvalConstants.SHARING_PRIVATE, Boolean.FALSE), Boolean.FALSE ); fail("Should have thrown an exception"); } catch (IllegalStateException e) { assertNotNull(e); } } /** * Test method for {@link org.sakaiproject.evaluation.dao.EvaluationDaoImpl#lockItem(org.sakaiproject.evaluation.model.EvalItem, java.lang.Boolean)}. */ public void testLockItem() { // check that unlocked item gets locked (no scale) assertFalse( etdl.item7.getLocked().booleanValue() ); assertTrue( evaluationDao.lockItem( etdl.item7, Boolean.TRUE ) ); assertTrue( etdl.item7.getLocked().booleanValue() ); // check that locked item does nothing bad if locked again (no scale, not used) assertTrue( itemLocked.getLocked().booleanValue() ); assertFalse( evaluationDao.lockItem( itemLocked, Boolean.TRUE ) ); assertTrue( itemLocked.getLocked().booleanValue() ); // check that locked item gets unlocked (no scale, not used) assertTrue( itemLocked.getLocked().booleanValue() ); assertTrue( evaluationDao.lockItem( itemLocked, Boolean.FALSE ) ); assertFalse( itemLocked.getLocked().booleanValue() ); // check that locked item that is locked by a template cannot be unlocked assertTrue( etdl.item1.getLocked().booleanValue() ); assertFalse( evaluationDao.lockItem( etdl.item1, Boolean.FALSE ) ); assertTrue( etdl.item1.getLocked().booleanValue() ); // check that locked item that is locked by a template can be locked without exception assertTrue( etdl.item1.getLocked().booleanValue() ); assertFalse( evaluationDao.lockItem( etdl.item1, Boolean.TRUE ) ); assertTrue( etdl.item1.getLocked().booleanValue() ); // verify that associated scale is unlocked assertFalse( itemUnlocked.getScale().getLocked().booleanValue() ); // check that unlocked item gets locked (scale) assertFalse( itemUnlocked.getLocked().booleanValue() ); assertTrue( evaluationDao.lockItem( itemUnlocked, Boolean.TRUE ) ); assertTrue( itemUnlocked.getLocked().booleanValue() ); // verify that associated scale gets locked assertTrue( itemUnlocked.getScale().getLocked().booleanValue() ); // check that locked item gets unlocked (scale) assertTrue( itemUnlocked.getLocked().booleanValue() ); assertTrue( evaluationDao.lockItem( itemUnlocked, Boolean.FALSE ) ); assertFalse( itemUnlocked.getLocked().booleanValue() ); // verify that associated scale gets unlocked assertFalse( itemUnlocked.getScale().getLocked().booleanValue() ); // check that locked item gets unlocked (scale locked by another item) assertTrue( etdl.item4.getScale().getLocked().booleanValue() ); assertTrue( evaluationDao.lockItem( etdl.item4, Boolean.TRUE ) ); assertTrue( etdl.item4.getLocked().booleanValue() ); assertTrue( evaluationDao.lockItem( etdl.item4, Boolean.FALSE ) ); assertFalse( etdl.item4.getLocked().booleanValue() ); // verify that associated scale does not get unlocked assertTrue( etdl.item4.getScale().getLocked().booleanValue() ); // check that new item cannot be locked/unlocked try { evaluationDao.lockItem( new EvalItem( EvalTestDataLoad.ADMIN_USER_ID, "something", EvalConstants.SHARING_PRIVATE, EvalConstants.ITEM_TYPE_HEADER, Boolean.FALSE), Boolean.TRUE); fail("Should have thrown an exception"); } catch (IllegalStateException e) { assertNotNull(e); } } /** * Test method for {@link org.sakaiproject.evaluation.dao.EvaluationDaoImpl#lockTemplate(org.sakaiproject.evaluation.model.EvalTemplate, java.lang.Boolean)}. */ public void testLockTemplate() { // check that unlocked template gets locked (no items) assertFalse( etdl.templateAdminNoItems.getLocked().booleanValue() ); assertTrue( evaluationDao.lockTemplate( etdl.templateAdminNoItems, Boolean.TRUE ) ); assertTrue( etdl.templateAdminNoItems.getLocked().booleanValue() ); // check that locked template is ok with getting locked again (no problems) assertTrue( etdl.templateAdminNoItems.getLocked().booleanValue() ); assertFalse( evaluationDao.lockTemplate( etdl.templateAdminNoItems, Boolean.TRUE ) ); assertTrue( etdl.templateAdminNoItems.getLocked().booleanValue() ); // check that locked template gets unlocked (no items) assertTrue( etdl.templateAdminNoItems.getLocked().booleanValue() ); assertTrue( evaluationDao.lockTemplate( etdl.templateAdminNoItems, Boolean.FALSE ) ); assertFalse( etdl.templateAdminNoItems.getLocked().booleanValue() ); // check that locked template that is locked by an evaluation cannot be unlocked assertTrue( etdl.templateUser.getLocked().booleanValue() ); assertFalse( evaluationDao.lockTemplate( etdl.templateUser, Boolean.FALSE ) ); assertTrue( etdl.templateUser.getLocked().booleanValue() ); // check that locked template that is locked by an evaluation can be locked without exception assertTrue( etdl.templateUser.getLocked().booleanValue() ); assertFalse( evaluationDao.lockTemplate( etdl.templateUser, Boolean.TRUE ) ); assertTrue( etdl.templateUser.getLocked().booleanValue() ); // check that unlocked template gets locked (items) assertFalse( etdl.item6.getLocked().booleanValue() ); assertFalse( etdl.templateUserUnused.getLocked().booleanValue() ); assertTrue( evaluationDao.lockTemplate( etdl.templateUserUnused, Boolean.TRUE ) ); assertTrue( etdl.templateUserUnused.getLocked().booleanValue() ); // verify that related items are locked also assertTrue( etdl.item6.getLocked().booleanValue() ); // check that locked template gets unlocked (items) assertTrue( etdl.templateUserUnused.getLocked().booleanValue() ); assertTrue( evaluationDao.lockTemplate( etdl.templateUserUnused, Boolean.FALSE ) ); assertFalse( etdl.templateUserUnused.getLocked().booleanValue() ); // verify that related items are unlocked also assertFalse( etdl.item6.getLocked().booleanValue() ); // check unlocked template with locked items can be locked assertFalse( etdl.templateUnused.getLocked().booleanValue() ); assertTrue( evaluationDao.lockTemplate( etdl.templateUnused, Boolean.TRUE ) ); assertTrue( etdl.templateUnused.getLocked().booleanValue() ); // check that locked template gets unlocked (items locked by another template) assertTrue( etdl.item3.getLocked().booleanValue() ); assertTrue( etdl.item5.getLocked().booleanValue() ); assertTrue( etdl.templateUnused.getLocked().booleanValue() ); assertTrue( evaluationDao.lockTemplate( etdl.templateUnused, Boolean.FALSE ) ); assertFalse( etdl.templateUnused.getLocked().booleanValue() ); // verify that associated items locked by other template do not get unlocked assertTrue( etdl.item3.getLocked().booleanValue() ); assertTrue( etdl.item5.getLocked().booleanValue() ); // check that new template cannot be locked/unlocked try { evaluationDao.lockTemplate( new EvalTemplate(EvalTestDataLoad.ADMIN_USER_ID, EvalConstants.TEMPLATE_TYPE_STANDARD, "new template one", "description", EvalConstants.SHARING_PRIVATE, EvalTestDataLoad.NOT_EXPERT, "expert desc", null, EvalTestDataLoad.LOCKED, false), Boolean.TRUE); fail("Should have thrown an exception"); } catch (IllegalStateException e) { assertNotNull(e); } } /** * Test method for {@link org.sakaiproject.evaluation.dao.EvaluationDaoImpl#lockEvaluation(org.sakaiproject.evaluation.model.EvalEvaluation)}. */ public void testLockEvaluation() { // check that unlocked evaluation gets locked assertFalse( etdl.templatePublicUnused.getLocked().booleanValue() ); assertFalse( evalUnLocked.getLocked().booleanValue() ); assertTrue( evaluationDao.lockEvaluation( evalUnLocked, true ) ); assertTrue( evalUnLocked.getLocked().booleanValue() ); // verify that associated template gets locked assertTrue( etdl.templatePublicUnused.getLocked().booleanValue() ); // now unlock the evaluation assertTrue( evalUnLocked.getLocked().booleanValue() ); assertTrue( evaluationDao.lockEvaluation( evalUnLocked, false ) ); assertFalse( evalUnLocked.getLocked().booleanValue() ); // verify that associated template gets unlocked assertFalse( etdl.templatePublicUnused.getLocked().booleanValue() ); // check that new evaluation cannot be locked try { evaluationDao.lockEvaluation( new EvalEvaluation(EvalConstants.EVALUATION_TYPE_EVALUATION, EvalTestDataLoad.MAINT_USER_ID, "Eval new", null, etdl.tomorrow, etdl.threeDaysFuture, etdl.threeDaysFuture, etdl.fourDaysFuture, false, null, false, null, EvalConstants.EVALUATION_STATE_INQUEUE, EvalConstants.SHARING_VISIBLE, EvalConstants.INSTRUCTOR_OPT_IN, new Integer(1), null, null, null, null, etdl.templatePublic, null, Boolean.TRUE, Boolean.FALSE, Boolean.FALSE, EvalTestDataLoad.UNLOCKED, EvalConstants.EVALUATION_AUTHCONTROL_AUTH_REQ, null, null), true ); fail("Should have thrown an exception"); } catch (IllegalStateException e) { assertNotNull(e); } } /** * Test method for {@link org.sakaiproject.evaluation.dao.EvaluationDaoImpl#isUsedScale(java.lang.Long)}. */ public void testIsUsedScale() { assertTrue( evaluationDao.isUsedScale( etdl.scale1.getId() ) ); assertTrue( evaluationDao.isUsedScale( etdl.scale2.getId() ) ); assertFalse( evaluationDao.isUsedScale( etdl.scale3.getId() ) ); assertFalse( evaluationDao.isUsedScale( etdl.scale4.getId() ) ); } /** * Test method for {@link org.sakaiproject.evaluation.dao.EvaluationDaoImpl#isUsedItem(java.lang.Long)}. */ public void testIsUsedItem() { assertTrue( evaluationDao.isUsedItem( etdl.item1.getId() ) ); assertTrue( evaluationDao.isUsedItem( etdl.item2.getId() ) ); assertTrue( evaluationDao.isUsedItem( etdl.item3.getId() ) ); assertFalse( evaluationDao.isUsedItem( etdl.item4.getId() ) ); assertTrue( evaluationDao.isUsedItem( etdl.item5.getId() ) ); assertTrue( evaluationDao.isUsedItem( etdl.item6.getId() ) ); assertFalse( evaluationDao.isUsedItem( etdl.item7.getId() ) ); assertFalse( evaluationDao.isUsedItem( etdl.item8.getId() ) ); assertTrue( evaluationDao.isUsedItem( etdl.item9.getId() ) ); assertTrue( evaluationDao.isUsedItem( etdl.item10.getId() ) ); } /** * Test method for {@link org.sakaiproject.evaluation.dao.EvaluationDaoImpl#isUsedTemplate(java.lang.Long)}. */ public void testIsUsedTemplate() { assertTrue( evaluationDao.isUsedTemplate( etdl.templateAdmin.getId() ) ); assertFalse( evaluationDao.isUsedTemplate( etdl.templateAdminBlock.getId() ) ); assertFalse( evaluationDao.isUsedTemplate( etdl.templateAdminComplex.getId() ) ); assertFalse( evaluationDao.isUsedTemplate( etdl.templateAdminNoItems.getId() ) ); assertTrue( evaluationDao.isUsedTemplate( etdl.templatePublic.getId() ) ); assertTrue( evaluationDao.isUsedTemplate( etdl.templatePublicUnused.getId() ) ); // used in this file assertFalse( evaluationDao.isUsedTemplate( etdl.templateUnused.getId() ) ); assertTrue( evaluationDao.isUsedTemplate( etdl.templateUser.getId() ) ); assertFalse( evaluationDao.isUsedTemplate( etdl.templateUserUnused.getId() ) ); } public void testObtainLock() { // check I can get a lock assertTrue( evaluationDao.obtainLock("AZ.my.lock", "AZ1", 100) ); // check someone else cannot get my lock assertFalse( evaluationDao.obtainLock("AZ.my.lock", "AZ2", 100) ); // check I can get my own lock again assertTrue( evaluationDao.obtainLock("AZ.my.lock", "AZ1", 100) ); // allow the lock to expire try { Thread.sleep(500); } catch (InterruptedException e) { // nothing here but a fail fail("sleep interrupted?"); } // check someone else can get my lock assertTrue( evaluationDao.obtainLock("AZ.my.lock", "AZ2", 100) ); // check invalid arguments cause failure try { evaluationDao.obtainLock("AZ.my.lock", null, 1000); fail("Should have thrown an exception"); } catch (IllegalArgumentException e) { assertNotNull(e); } try { evaluationDao.obtainLock(null, "AZ1", 1000); fail("Should have thrown an exception"); } catch (IllegalArgumentException e) { assertNotNull(e); } } public void testReleaseLock() { // check I can get a lock assertTrue( evaluationDao.obtainLock("AZ.R.lock", "AZ1", 1000) ); // check someone else cannot get my lock assertFalse( evaluationDao.obtainLock("AZ.R.lock", "AZ2", 1000) ); // check I can release my lock assertTrue( evaluationDao.releaseLock("AZ.R.lock", "AZ1") ); // check someone else can get my lock now assertTrue( evaluationDao.obtainLock("AZ.R.lock", "AZ2", 1000) ); // check I cannot get the lock anymore assertFalse( evaluationDao.obtainLock("AZ.R.lock", "AZ1", 1000) ); // check they can release it assertTrue( evaluationDao.releaseLock("AZ.R.lock", "AZ2") ); // check invalid arguments cause failure try { evaluationDao.releaseLock("AZ.R.lock", null); fail("Should have thrown an exception"); } catch (IllegalArgumentException e) { assertNotNull(e); } try { evaluationDao.releaseLock(null, "AZ1"); fail("Should have thrown an exception"); } catch (IllegalArgumentException e) { assertNotNull(e); } } public void testGetConsolidatedEmailMapping() { // when no emails have been sent, selecting email recipients in any of several ways should return 1 int count = this.evaluationDao.selectConsolidatedEmailRecipients(true, (Date) null, false, (Date) null, EvalConstants.EMAIL_TEMPLATE_CONSOLIDATED_AVAILABLE); assertEquals(1, count); int deletions = this.evaluationDao.resetConsolidatedEmailRecipients(); assertEquals(1, deletions); count = this.evaluationDao.selectConsolidatedEmailRecipients(true, new Date(), false, (Date) null, EvalConstants.EMAIL_TEMPLATE_CONSOLIDATED_AVAILABLE); assertEquals(1, count); deletions = this.evaluationDao.resetConsolidatedEmailRecipients(); assertEquals(1, deletions); // there should be two new evals ready to send announcements to, selected because the value of availableEmailSent is null int count1 = this.evaluationDao.selectConsolidatedEmailRecipients(true, (Date) null, false, (Date) null, EvalConstants.EMAIL_TEMPLATE_CONSOLIDATED_AVAILABLE); assertEquals(1,count1); List<Map<String,Object>> mapping1 = this.evaluationDao.getConsolidatedEmailMapping(true, 100, 0); assertNotNull(mapping1); assertEquals(1, mapping1.size()); int deletions1 = this.evaluationDao.resetConsolidatedEmailRecipients(); assertEquals(1, deletions1); // Since those announcements have been sent, there should be none yet to be sent int count2 = this.evaluationDao.selectConsolidatedEmailRecipients(true, (Date) null, false, (Date) null, EvalConstants.EMAIL_TEMPLATE_CONSOLIDATED_AVAILABLE); assertEquals(0,count2); List<Map<String,Object>> mapping2 = this.evaluationDao.getConsolidatedEmailMapping(true, 100, 0); assertNotNull(mapping2); assertEquals(0, mapping2.size()); int deletions2 = this.evaluationDao.resetConsolidatedEmailRecipients(); assertEquals(0, deletions2); // if we search for notices to be sent and ignore the date, we should find them again int count3 = this.evaluationDao.selectConsolidatedEmailRecipients(false, (Date) null, false, (Date) null, EvalConstants.EMAIL_TEMPLATE_CONSOLIDATED_AVAILABLE); assertEquals(1,count3); List<Map<String,Object>> mapping3 = this.evaluationDao.getConsolidatedEmailMapping(true, 100, 0); assertNotNull(mapping3); assertEquals(1, mapping3.size()); int deletions3 = this.evaluationDao.resetConsolidatedEmailRecipients(); assertEquals(1, deletions3); // if we search for evals needing reminders based on whether an announcement or reminder has been sent in the past day, we should find none int count4 = this.evaluationDao.selectConsolidatedEmailRecipients(true, new Date(), true, new Date(), EvalConstants.EMAIL_TEMPLATE_CONSOLIDATED_REMINDER); assertEquals(0,count4); List<Map<String,Object>> mapping4 = this.evaluationDao.getConsolidatedEmailMapping(false, 100, 0); assertNotNull(mapping4); assertEquals(0, mapping4.size()); int deletions4 = this.evaluationDao.resetConsolidatedEmailRecipients(); assertEquals(0, deletions4); // if we search for evals needing reminders based on whether a reminder has been sent in the past day (ignoring when announcements were sent) we find 2 int count5 = this.evaluationDao.selectConsolidatedEmailRecipients(false, (Date) null, true, new Date(), EvalConstants.EMAIL_TEMPLATE_CONSOLIDATED_REMINDER); assertEquals(1,count5); List<Map<String,Object>> mapping5 = this.evaluationDao.getConsolidatedEmailMapping(false, 100, 0); assertNotNull(mapping5); assertEquals(1, mapping5.size()); int deletions5 = this.evaluationDao.resetConsolidatedEmailRecipients(); assertEquals(1, deletions5); // if we do the same search again, we find 0 because they have just been sent int count6 = this.evaluationDao.selectConsolidatedEmailRecipients(false, (Date) null, true, new Date(), EvalConstants.EMAIL_TEMPLATE_CONSOLIDATED_REMINDER); assertEquals(0,count6); List<Map<String,Object>> mapping6 = this.evaluationDao.getConsolidatedEmailMapping(false, 100, 0); assertNotNull(mapping6); assertEquals(0, mapping6.size()); int deletions6 = this.evaluationDao.resetConsolidatedEmailRecipients(); assertEquals(0, deletions6); // if we search for evals needing reminders as if it were tomorrow, we should find 1 int count7 = this.evaluationDao.selectConsolidatedEmailRecipients(false, (Date) null, true, new Date(System.currentTimeMillis() + MILLISECONDS_PER_DAY), EvalConstants.EMAIL_TEMPLATE_CONSOLIDATED_REMINDER); assertEquals(1,count7); List<Map<String,Object>> mapping7 = this.evaluationDao.getConsolidatedEmailMapping(false, 100, 0); assertNotNull(mapping7); assertEquals(1, mapping7.size()); int deletions7 = this.evaluationDao.resetConsolidatedEmailRecipients(); assertEquals(1, deletions7); // if we search for evals needing reminders as if it were tomorrow, we should find 1 int count8 = this.evaluationDao.selectConsolidatedEmailRecipients(false, (Date) null, true, new Date(System.currentTimeMillis() + MILLISECONDS_PER_DAY), EvalConstants.EMAIL_TEMPLATE_CONSOLIDATED_REMINDER); assertEquals(1,count8); List<EvalEmailProcessingData> list = evaluationDao.findBySearch(EvalEmailProcessingData.class, new Search()); assertNotNull(list); assertEquals(1,list.size()); // now if we reset the queue and update "completedDate" for the EvalAssignUser associated with that user and eval, we should find no evals needing notifications this.evaluationDao.resetConsolidatedEmailRecipients(); EvalEmailProcessingData eepd = list.get(0); // update EvalAssignUser with completed time EvalEvaluation evaluation = evaluationDao.findById(EvalEvaluation.class, eepd.getEvalId()); String[] properties = new String[]{"userId", "evaluation", "evalGroupId"}; Object[] values = new Object[]{eepd.getUserId(), evaluation, eepd.getGroupId()}; List<EvalAssignUser> eaus = evaluationDao.findAll(EvalAssignUser.class); assertNotNull(eaus); EvalAssignUser eau = evaluationDao.findOneBySearch(EvalAssignUser.class, new Search(properties, values)); assertNotNull(eau); if (eau != null) { Long eauId = eau.getId(); assertNotNull(eauId); eau.setCompletedDate(new Date()); evaluationDao.update(eau); EvalAssignUser eau0 = evaluationDao.findById(EvalAssignUser.class, eau.getId()); assertNotNull(eau0); assertNotNull(eau0.getCompletedDate()); } int count9 = this.evaluationDao.selectConsolidatedEmailRecipients(false, (Date) null, true, new Date(System.currentTimeMillis() + MILLISECONDS_PER_DAY), EvalConstants.EMAIL_TEMPLATE_CONSOLIDATED_REMINDER); assertEquals(0,count9); List<Map<String,Object>> mapping9 = this.evaluationDao.getConsolidatedEmailMapping(false, 100, 0); assertNotNull(mapping9); assertEquals(0, mapping9.size()); } /** * testResponsesSavedInProgress checks to see how many responses have been saved but not submitted * for both active and inactive evaluations. This depends on evaluations being open or closed and * having an incomplete response associated with it. */ public void testGetResponsesSavedInProgress() { // add an incomplete response to an active evaluation EvalResponse responseActive = etdl.response1; EvalEvaluation evalActive = etdl.evaluationActive; responseActive.setEndTime(null); responseActive.setEvaluation(evalActive); this.evaluationDao.save(responseActive); // add an incomplete response to a closed evaluation EvalResponse responseInactive = etdl.response2; EvalEvaluation evalInactive = etdl.evaluationClosed; responseInactive.setEndTime(null); responseInactive.setEvaluation(evalInactive); this.evaluationDao.save(responseInactive); List<EvalResponse> evalOpenResponses = this.evaluationDao.getResponsesSavedInProgress(true); assertNotNull(evalOpenResponses); assertEquals(1, evalOpenResponses.size()); assertEquals(evalOpenResponses.get(0).getId(), responseActive.getId()); List<EvalResponse> evalClosedResponses = this.evaluationDao.getResponsesSavedInProgress(false); assertNotNull(evalClosedResponses); assertEquals(1, evalClosedResponses.size()); assertEquals(evalClosedResponses.get(0).getId(), responseInactive.getId()); } /** * Add anything that supports the unit tests below here */ }
package com.massivedisaster.activitymanager; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.app.ActivityOptionsCompat; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.support.v4.util.Pair; import android.view.View; import com.massivedisaster.activitymanager.activity.AbstractFragmentActivity; import java.util.ArrayList; import java.util.List; /** * ActivityTransaction * The Transaction to open a new activity and inject a specified fragment. */ public class ActivityTransaction implements ITransaction<ActivityTransaction> { public static final String ACTIVITY_MANAGER_FRAGMENT = "activity_manager_fragment"; public static final String ACTIVITY_MANAGER_FRAGMENT_TAG = "activity_manager_fragment_tag"; public static final String ACTIVITY_MANAGER_FRAGMENT_SHARED_ELEMENTS = "activity_manager_fragment_shared_elements"; private final Class<? extends AbstractFragmentActivity> mAbstractBaseActivity; private final Intent mIntent; private ActivityOptionsCompat mActivityOptions; private List<Pair<View, String>> mSharedElements; private Activity mActivityBase; private Fragment mFragment; private Integer mRequestCode; /** * ActivityTransaction constructor, created to be used by an activity. * * @param activity The activity to be used to start the new activity. * @param abstractBaseActivityClass The AbstractFragmentActivity class. * @param fragmentClass The Fragment to be injected in the activityClass. */ ActivityTransaction(Activity activity, Class<? extends AbstractFragmentActivity> abstractBaseActivityClass, Class<? extends Fragment> fragmentClass) { mActivityBase = activity; mAbstractBaseActivity = abstractBaseActivityClass; mIntent = new Intent(mActivityBase, mAbstractBaseActivity); mIntent.putExtra(ACTIVITY_MANAGER_FRAGMENT, fragmentClass.getCanonicalName()); } /** * ActivityTransaction constructor, created to be used by a fragment. * * @param fragment The fragment to be used to start the new activity. * @param abstractBaseActivityClass The AbstractFragmentActivity class. * @param fragmentClass The Fragment to be injected in the activityClass. */ ActivityTransaction(Fragment fragment, Class<? extends AbstractFragmentActivity> abstractBaseActivityClass, Class<? extends Fragment> fragmentClass) { mFragment = fragment; mAbstractBaseActivity = abstractBaseActivityClass; mIntent = new Intent(mFragment.getContext(), mAbstractBaseActivity); mIntent.putExtra(ACTIVITY_MANAGER_FRAGMENT, fragmentClass.getCanonicalName()); } @Override public ActivityTransaction addTag(String tag) { mIntent.putExtra(ACTIVITY_MANAGER_FRAGMENT_TAG, tag); return this; } @Override public ActivityTransaction addBundle(Bundle bundle) { mIntent.putExtras(bundle); return this; } @Override public ActivityTransaction addSharedElement(View view, String transactionName) { mIntent.putExtra(ACTIVITY_MANAGER_FRAGMENT_SHARED_ELEMENTS, true); if (mSharedElements == null) { mSharedElements = new ArrayList<>(); } mSharedElements.add(new Pair<>(view, transactionName)); // Create the new activity options Pair[] sharedElements = mSharedElements.toArray(new Pair[mSharedElements.size()]); mActivityOptions = ActivityOptionsCompat. makeSceneTransitionAnimation(mActivityBase == null ? mFragment.getActivity() : mActivityBase, sharedElements); return this; } /** * Set the Bundle to be passed to the new Fragment. * * @param requestCode The code to be used in the {@link Activity#startActivityForResult}. * @return Return the Transaction instance. */ public ActivityTransaction addRequestCode(int requestCode) { mRequestCode = requestCode; return this; } /** * Retrieve the activity options. * * @return The activity options instance. */ public ActivityOptionsCompat getActivityOptions() { return mActivityOptions; } /** * Get the intent created with the configurations to used. * * @return The Intent to the transaction. */ public Intent getIntent() { return mIntent; } @Override public void commit() { Intent intent = getIntent(); Bundle bundleOptions = mActivityOptions != null ? mActivityOptions.toBundle() : null; if (mRequestCode == null) { if (mActivityBase != null) { ContextCompat.startActivity(mActivityBase, intent, bundleOptions); } else { mFragment.startActivity(intent, bundleOptions); } } else { if (mActivityBase != null) { ActivityCompat.startActivityForResult(mActivityBase, intent, mRequestCode, bundleOptions); } else { mFragment.startActivityForResult(intent, mRequestCode, bundleOptions); } } } }
package im.actor.runtime.se; import im.actor.runtime.generic.GenericThreadingProvider; import im.actor.runtime.threading.Dispatcher; public class JavaSeThreadingProvider extends GenericThreadingProvider { @Override public Dispatcher createDispatcher(String name) { return null; } }
package ru.yandex.qatools.allure.storages; import org.junit.Before; import org.junit.Test; import ru.yandex.qatools.allure.model.Step; import static org.hamcrest.Matchers.hasSize; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; public class StepStorageTest { private StepStorage stepStorage; @Before public void setUp() throws Exception { stepStorage = new StepStorage(); } @Test public void getLastTest() throws Exception { Step step = stepStorage.getLast(); assertNotNull(step); assertEquals(step, stepStorage.getLast()); } @Test public void putTest() throws Exception { Step step = new Step(); stepStorage.put(step); assertEquals(step, stepStorage.getLast()); } @Test public void pollLastTest() throws Exception { Step step = stepStorage.getLast(); assertEquals(step, stepStorage.pollLast()); assertThat(stepStorage.get(), hasSize(1)); } }
package au.gov.dva.sopapi.sopsupport.processingrules.rules; import au.gov.dva.sopapi.dtos.Recommendation; import au.gov.dva.sopapi.interfaces.*; import au.gov.dva.sopapi.interfaces.model.*; import au.gov.dva.sopapi.sopsupport.processingrules.Interval; import com.google.common.collect.ImmutableList; import java.util.Optional; import java.util.function.Predicate; public class MentalHealthProcessingRule extends ProcessingRuleBase implements ProcessingRule { private final IntervalSelector rhIntervalSelector; Interval rhInterval; public MentalHealthProcessingRule(ConditionConfiguration conditionConfiguration, IntervalSelector rhIntervalSelector) { super(conditionConfiguration); this.rhIntervalSelector = rhIntervalSelector; } @Override public Optional<SoP> getApplicableSop(Condition condition, ServiceHistory serviceHistory, Predicate<Deployment> isOperational, CaseTrace caseTrace) { if (super.shouldAbortProcessing(serviceHistory,condition,caseTrace)) { return Optional.empty(); } rhInterval = rhIntervalSelector.getInterval(serviceHistory,condition.getStartDate()); return super.getApplicableSop(condition,serviceHistory,isOperational,rhInterval,true,caseTrace); } @Override public ImmutableList<FactorWithSatisfaction> getSatisfiedFactors(Condition condition, SoP applicableSop, ServiceHistory serviceHistory, CaseTrace caseTrace) { ApplicableRuleConfiguration applicableRuleConfiguration = super.getApplicableRuleConfiguration(serviceHistory,condition,caseTrace).get(); Optional<? extends RuleConfigurationItem> applicableRuleConfigurationItem = applicableRuleConfiguration.getRuleConfigurationForStandardOfProof(applicableSop.getStandardOfProof()); return super.getSatisfiedFactors(condition,applicableSop,serviceHistory,rhInterval,applicableRuleConfigurationItem,caseTrace); } @Override public void attachConfiguredFactorsToCaseTrace(Condition condition, ServiceHistory serviceHistory, CaseTrace caseTrace) { super.attachConfiguredFactorsToCaseTrace(condition,serviceHistory,caseTrace); } }
package nodomain.freeyourgadget.gadgetbridge.activities.charts; import android.graphics.Color; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.github.mikephil.charting.charts.Chart; import com.github.mikephil.charting.charts.CombinedChart; import com.github.mikephil.charting.charts.PieChart; import com.github.mikephil.charting.components.LimitLine; import com.github.mikephil.charting.components.XAxis; import com.github.mikephil.charting.components.YAxis; import com.github.mikephil.charting.data.BarData; import com.github.mikephil.charting.data.BarDataSet; import com.github.mikephil.charting.data.BarEntry; import com.github.mikephil.charting.data.CombinedData; import com.github.mikephil.charting.data.PieData; import com.github.mikephil.charting.data.PieDataSet; import com.github.mikephil.charting.data.PieEntry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.text.NumberFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Locale; import nodomain.freeyourgadget.gadgetbridge.R; import nodomain.freeyourgadget.gadgetbridge.database.DBHandler; import nodomain.freeyourgadget.gadgetbridge.devices.miband.MiBandCoordinator; import nodomain.freeyourgadget.gadgetbridge.impl.GBDevice; import nodomain.freeyourgadget.gadgetbridge.model.ActivitySample; public class WeekStepsChartFragment extends AbstractChartFragment { protected static final Logger LOG = LoggerFactory.getLogger(WeekStepsChartFragment.class); private Locale mLocale; private int mTargetSteps = 10000; private PieChart mTodayStepsChart; private CombinedChart mWeekStepsChart; @Override protected ChartsData refreshInBackground(ChartsHost chartsHost, DBHandler db, GBDevice device) { Calendar day = Calendar.getInstance(); day.setTime(chartsHost.getEndDate()); //NB: we could have omitted the day, but this way we can move things to the past easily DaySteps daySteps = refreshDaySteps(db, day, device); DefaultChartsData weekBeforeStepsData = refreshWeekBeforeSteps(db, mWeekStepsChart, day, device); return new MyChartsData(daySteps, weekBeforeStepsData); } @Override protected void updateChartsnUIThread(ChartsData chartsData) { MyChartsData mcd = (MyChartsData) chartsData; // setupLegend(mWeekStepsChart); mTodayStepsChart.setCenterText(NumberFormat.getNumberInstance(mLocale).format(mcd.getDaySteps().totalSteps)); mTodayStepsChart.setData(mcd.getDaySteps().data); mWeekStepsChart.setData(null); mWeekStepsChart.setData(mcd.getWeekBeforeStepsData().getCombinedData()); mWeekStepsChart.getLegend().setEnabled(false); xIndexFormatter.setxLabels(mcd.getWeekBeforeStepsData().getXLabels()); } @Override protected void renderCharts() { mWeekStepsChart.invalidate(); mTodayStepsChart.invalidate(); } private DefaultChartsData refreshWeekBeforeSteps(DBHandler db, CombinedChart combinedChart, Calendar day, GBDevice device) { ActivityAnalysis analysis = new ActivityAnalysis(); day = (Calendar) day.clone(); // do not modify the caller's argument day.add(Calendar.DATE, -7); List<BarEntry> entries = new ArrayList<>(); ArrayList<String> labels = new ArrayList<String>(); for (int counter = 0; counter < 7; counter++) { entries.add(new BarEntry(counter, analysis.calculateTotalSteps(getSamplesOfDay(db, day, device)))); labels.add(day.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.SHORT, mLocale)); day.add(Calendar.DATE, 1); } BarDataSet set = new BarDataSet(entries, ""); set.setColor(akActivity.color); BarData barData = new BarData(set); barData.setValueTextColor(Color.GRAY); //prevent tearing other graph elements with the black text. Another approach would be to hide the values cmpletely with data.setDrawValues(false); LimitLine target = new LimitLine(mTargetSteps); combinedChart.getAxisLeft().removeAllLimitLines(); combinedChart.getAxisLeft().addLimitLine(target); CombinedData combinedData = new CombinedData(); combinedData.setData(barData); return new DefaultChartsData(combinedData, labels); } private DaySteps refreshDaySteps(DBHandler db, Calendar day, GBDevice device) { ActivityAnalysis analysis = new ActivityAnalysis(); int totalSteps = analysis.calculateTotalSteps(getSamplesOfDay(db, day, device)); PieData data = new PieData(); List<PieEntry> entries = new ArrayList<>(); List<Integer> colors = new ArrayList<>(); entries.add(new PieEntry(totalSteps, "")); //we don't want labels on the pie chart colors.add(akActivity.color); if (totalSteps < mTargetSteps) { entries.add(new PieEntry((mTargetSteps - totalSteps))); //we don't want labels on the pie chart colors.add(Color.GRAY); } PieDataSet set = new PieDataSet(entries, ""); set.setColors(colors); data.setDataSet(set); //this hides the values (numeric) added to the set. These would be shown aside the strings set with addXValue above data.setDrawValues(false); return new DaySteps(data, totalSteps); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mLocale = getResources().getConfiguration().locale; View rootView = inflater.inflate(R.layout.fragment_sleepchart, container, false); GBDevice device = getChartsHost().getDevice(); if (device != null) { // TODO: eek, this is device specific! mTargetSteps = MiBandCoordinator.getFitnessGoal(device.getAddress()); } mWeekStepsChart = (CombinedChart) rootView.findViewById(R.id.sleepchart); mTodayStepsChart = (PieChart) rootView.findViewById(R.id.sleepchart_pie_light_deep); setupWeekStepsChart(); setupTodayStepsChart(); // refresh immediately instead of use refreshIfVisible(), for perceived performance refresh(); return rootView; } @Override public String getTitle() { return getString(R.string.weekstepschart_steps_a_week); } private void setupTodayStepsChart() { mTodayStepsChart.setBackgroundColor(BACKGROUND_COLOR); mTodayStepsChart.getDescription().setTextColor(DESCRIPTION_COLOR); mTodayStepsChart.getDescription().setText(getContext().getString(R.string.weeksteps_today_steps_description, String.valueOf(mTargetSteps))); // mTodayStepsChart.setNoDataTextDescription(""); mTodayStepsChart.setNoDataText(""); mTodayStepsChart.getLegend().setEnabled(false); // setupLegend(mTodayStepsChart); } private void setupWeekStepsChart() { mWeekStepsChart.setBackgroundColor(BACKGROUND_COLOR); mWeekStepsChart.getDescription().setTextColor(DESCRIPTION_COLOR); mWeekStepsChart.getDescription().setText(""); configureBarLineChartDefaults(mWeekStepsChart); XAxis x = mWeekStepsChart.getXAxis(); x.setDrawLabels(true); x.setDrawGridLines(false); x.setEnabled(true); x.setTextColor(CHART_TEXT_COLOR); x.setDrawLimitLinesBehindData(true); x.setValueFormatter(xIndexFormatter); x.setPosition(XAxis.XAxisPosition.BOTTOM); YAxis y = mWeekStepsChart.getAxisLeft(); y.setDrawGridLines(false); y.setDrawTopYLabelEntry(false); y.setTextColor(CHART_TEXT_COLOR); y.setEnabled(true); YAxis yAxisRight = mWeekStepsChart.getAxisRight(); yAxisRight.setDrawGridLines(false); yAxisRight.setEnabled(false); yAxisRight.setDrawLabels(false); yAxisRight.setDrawTopYLabelEntry(false); yAxisRight.setTextColor(CHART_TEXT_COLOR); } @Override protected void setupLegend(Chart chart) { // List<Integer> legendColors = new ArrayList<>(1); // List<String> legendLabels = new ArrayList<>(1); // legendColors.add(akActivity.color); // legendLabels.add(getContext().getString(R.string.chart_steps)); // chart.getLegend().setCustom(legendColors, legendLabels); // chart.getLegend().setTextColor(LEGEND_TEXT_COLOR); } private List<? extends ActivitySample> getSamplesOfDay(DBHandler db, Calendar day, GBDevice device) { int startTs; int endTs; day = (Calendar) day.clone(); // do not modify the caller's argument day.set(Calendar.HOUR_OF_DAY, 0); day.set(Calendar.MINUTE, 0); day.set(Calendar.SECOND, 0); startTs = (int) (day.getTimeInMillis() / 1000); day.set(Calendar.HOUR_OF_DAY, 23); day.set(Calendar.MINUTE, 59); day.set(Calendar.SECOND, 59); endTs = (int) (day.getTimeInMillis() / 1000); return getSamples(db, device, startTs, endTs); } @Override protected List<? extends ActivitySample> getSamples(DBHandler db, GBDevice device, int tsFrom, int tsTo) { return super.getAllSamples(db, device, tsFrom, tsTo); } private static class DaySteps { private final PieData data; private final int totalSteps; public DaySteps(PieData data, int totalSteps) { this.data = data; this.totalSteps = totalSteps; } } private static class MyChartsData extends ChartsData { private final DefaultChartsData weekBeforeStepsData; private final DaySteps daySteps; public MyChartsData(DaySteps daySteps, DefaultChartsData weekBeforeStepsData) { this.daySteps = daySteps; this.weekBeforeStepsData = weekBeforeStepsData; } public DaySteps getDaySteps() { return daySteps; } public DefaultChartsData getWeekBeforeStepsData() { return weekBeforeStepsData; } } }
package org.ovirt.engine.api.restapi.types; import static org.ovirt.engine.core.compat.Guid.createGuidFromString; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.ovirt.engine.api.common.util.StatusUtils; import org.ovirt.engine.api.model.AuthorizedKey; import org.ovirt.engine.api.model.Boot; import org.ovirt.engine.api.model.BootDevice; import org.ovirt.engine.api.model.BootProtocol; import org.ovirt.engine.api.model.CloudInit; import org.ovirt.engine.api.model.Configuration; import org.ovirt.engine.api.model.ConfigurationType; import org.ovirt.engine.api.model.CpuMode; import org.ovirt.engine.api.model.CpuTune; import org.ovirt.engine.api.model.CustomProperties; import org.ovirt.engine.api.model.CustomProperty; import org.ovirt.engine.api.model.Display; import org.ovirt.engine.api.model.Domain; import org.ovirt.engine.api.model.File; import org.ovirt.engine.api.model.Files; import org.ovirt.engine.api.model.GuestInfo; import org.ovirt.engine.api.model.GuestNicConfiguration; import org.ovirt.engine.api.model.GuestNicsConfiguration; import org.ovirt.engine.api.model.HighAvailability; import org.ovirt.engine.api.model.Host; import org.ovirt.engine.api.model.IP; import org.ovirt.engine.api.model.IPs; import org.ovirt.engine.api.model.Initialization; import org.ovirt.engine.api.model.InstanceType; import org.ovirt.engine.api.model.MemoryPolicy; import org.ovirt.engine.api.model.NIC; import org.ovirt.engine.api.model.NumaTuneMode; import org.ovirt.engine.api.model.OperatingSystem; import org.ovirt.engine.api.model.OsType; import org.ovirt.engine.api.model.Payload; import org.ovirt.engine.api.model.Quota; import org.ovirt.engine.api.model.Session; import org.ovirt.engine.api.model.Sessions; import org.ovirt.engine.api.model.Template; import org.ovirt.engine.api.model.Usb; import org.ovirt.engine.api.model.UsbType; import org.ovirt.engine.api.model.User; import org.ovirt.engine.api.model.VCpuPin; import org.ovirt.engine.api.model.VM; import org.ovirt.engine.api.model.VmAffinity; import org.ovirt.engine.api.model.VmPlacementPolicy; import org.ovirt.engine.api.model.VmPool; import org.ovirt.engine.api.model.VmStatus; import org.ovirt.engine.api.model.VmType; import org.ovirt.engine.api.restapi.utils.CustomPropertiesParser; import org.ovirt.engine.api.restapi.utils.GuidUtils; import org.ovirt.engine.core.common.FeatureSupported; import org.ovirt.engine.core.common.action.RunVmOnceParams; import org.ovirt.engine.core.common.businessentities.BootSequence; import org.ovirt.engine.core.common.businessentities.GraphicsInfo; import org.ovirt.engine.core.common.businessentities.GraphicsType; import org.ovirt.engine.core.common.businessentities.MigrationSupport; import org.ovirt.engine.core.common.businessentities.OriginType; import org.ovirt.engine.core.common.businessentities.UsbPolicy; import org.ovirt.engine.core.common.businessentities.VMStatus; import org.ovirt.engine.core.common.businessentities.VmBase; import org.ovirt.engine.core.common.businessentities.VmInit; import org.ovirt.engine.core.common.businessentities.VmInitNetwork; import org.ovirt.engine.core.common.businessentities.VmPayload; import org.ovirt.engine.core.common.businessentities.VmStatic; import org.ovirt.engine.core.common.businessentities.VmTemplate; import org.ovirt.engine.core.common.businessentities.network.NetworkBootProtocol; import org.ovirt.engine.core.common.config.Config; import org.ovirt.engine.core.common.config.ConfigValues; import org.ovirt.engine.core.common.osinfo.OsRepository; import org.ovirt.engine.core.common.utils.SimpleDependecyInjector; import org.ovirt.engine.core.common.utils.VmDeviceType; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.compat.Version; public class VmMapper extends VmBaseMapper { // REVISIT retrieve from configuration private static final int DEFAULT_MEMORY_SIZE = 10 * 1024; // REVISIT once #712661 implemented by BE @Mapping(from = VmTemplate.class, to = VmStatic.class) public static VmStatic map(VmTemplate entity, VmStatic template) { return map(entity, template, null); } public static VmStatic map(VmTemplate entity, VmStatic template, Version version) { VmStatic staticVm = template != null ? template : new VmStatic(); Version clusterVersion = version == null ? Version.getLast() : version; staticVm.setId(Guid.Empty); staticVm.setVmtGuid(entity.getId()); staticVm.setVdsGroupId(entity.getVdsGroupId()); staticVm.setOsId(entity.getOsId()); staticVm.setNiceLevel(entity.getNiceLevel()); staticVm.setCpuShares(entity.getCpuShares()); staticVm.setFailBack(entity.isFailBack()); staticVm.setStateless(entity.isStateless()); staticVm.setDeleteProtected(entity.isDeleteProtected()); staticVm.setSsoMethod(entity.getSsoMethod()); staticVm.setVmType(entity.getVmType()); staticVm.setIsoPath(entity.getIsoPath()); staticVm.setKernelUrl(entity.getKernelUrl()); staticVm.setKernelParams(entity.getKernelParams()); staticVm.setInitrdUrl(entity.getInitrdUrl()); staticVm.setTimeZone(entity.getTimeZone()); staticVm.setAllowConsoleReconnect(entity.isAllowConsoleReconnect()); staticVm.setVncKeyboardLayout(entity.getVncKeyboardLayout()); staticVm.setVmInit(entity.getVmInit()); if (FeatureSupported.serialNumberPolicy(clusterVersion)) { staticVm.setSerialNumberPolicy(entity.getSerialNumberPolicy()); staticVm.setCustomSerialNumber(entity.getCustomSerialNumber()); } if (FeatureSupported.isSpiceFileTransferToggleSupported(clusterVersion)) { staticVm.setSpiceFileTransferEnabled(entity.isSpiceFileTransferEnabled()); } if (FeatureSupported.isSpiceCopyPasteToggleSupported(clusterVersion)) { staticVm.setSpiceCopyPasteEnabled(entity.isSpiceCopyPasteEnabled()); } staticVm.setRunAndPause(entity.isRunAndPause()); staticVm.setCpuProfileId(entity.getCpuProfileId()); if (FeatureSupported.autoConvergence(clusterVersion)) { staticVm.setAutoConverge(entity.getAutoConverge()); } if (FeatureSupported.migrationCompression(clusterVersion)) { staticVm.setMigrateCompressed(entity.getMigrateCompressed()); } staticVm.setCustomProperties(entity.getCustomProperties()); staticVm.setCustomEmulatedMachine(entity.getCustomEmulatedMachine()); staticVm.setCustomCpuName(entity.getCustomCpuName()); return doMapVmBaseHwPartToVmStatic(entity, staticVm); } @Mapping(from = org.ovirt.engine.core.common.businessentities.InstanceType.class, to = VmStatic.class) public static VmStatic map(org.ovirt.engine.core.common.businessentities.InstanceType entity, VmStatic vmStatic) { return doMapVmBaseHwPartToVmStatic((VmBase) entity, vmStatic != null ? vmStatic : new VmStatic()); } private static VmStatic doMapVmBaseHwPartToVmStatic(VmBase entity, VmStatic staticVm) { staticVm.setMemSizeMb(entity.getMemSizeMb()); staticVm.setAutoStartup(entity.isAutoStartup()); staticVm.setSmartcardEnabled(entity.isSmartcardEnabled()); staticVm.setDefaultBootSequence(entity.getDefaultBootSequence()); staticVm.setDefaultDisplayType(entity.getDefaultDisplayType()); staticVm.setNumOfSockets(entity.getNumOfSockets()); staticVm.setCpuPerSocket(entity.getCpuPerSocket()); staticVm.setNumOfMonitors(entity.getNumOfMonitors()); staticVm.setSingleQxlPci(entity.getSingleQxlPci()); staticVm.setPriority(entity.getPriority()); staticVm.setUsbPolicy(entity.getUsbPolicy()); staticVm.setTunnelMigration(entity.getTunnelMigration()); staticVm.setMigrationSupport(entity.getMigrationSupport()); staticVm.setMigrationDowntime(entity.getMigrationDowntime()); staticVm.setMinAllocatedMem(entity.getMinAllocatedMem()); return staticVm; } @Mapping(from = VM.class, to = VmStatic.class) public static VmStatic map(VM vm, VmStatic template) { VmStatic staticVm = template != null ? template : new VmStatic(); mapVmBaseModelToEntity(staticVm, vm); if (!vm.isSetMemory() && staticVm.getMemSizeMb()==0){ //TODO: Get rid of this logic code when Backend supports default memory. staticVm.setMemSizeMb(DEFAULT_MEMORY_SIZE); } if (vm.isSetTemplate()) { if (vm.getTemplate().getId() != null) { staticVm.setVmtGuid(GuidUtils.asGuid(vm.getTemplate().getId())); } // There is no need to pass this property to backend if // no template was specified. // If user passes this property for a stateful vm which is not supported, // it will be handled by the backend. if (vm.isSetUseLatestTemplateVersion()) { staticVm.setUseLatestVersion(vm.isUseLatestTemplateVersion()); } } if (vm.isSetCpu()) { if (vm.getCpu().isSetMode()) { staticVm.setUseHostCpuFlags(CpuMode.fromValue(vm.getCpu().getMode()) == CpuMode.HOST_PASSTHROUGH); } if (vm.getCpu().isSetCpuTune()) { staticVm.setCpuPinning(cpuTuneToString(vm.getCpu().getCpuTune())); } } if (vm.isSetPlacementPolicy() && vm.getPlacementPolicy().isSetAffinity()) { VmAffinity vmAffinity = VmAffinity.fromValue(vm.getPlacementPolicy().getAffinity()); if (vmAffinity!=null) { staticVm.setMigrationSupport(map(vmAffinity, null)); } } if (vm.isSetPlacementPolicy() && vm.getPlacementPolicy().isSetHost()) { staticVm.setDedicatedVmForVds(createGuidFromString(vm.getPlacementPolicy().getHost().getId())); } if (vm.isSetMemoryPolicy() && vm.getMemoryPolicy().isSetGuaranteed()) { Long memGuaranteed = vm.getMemoryPolicy().getGuaranteed() / BYTES_PER_MB; staticVm.setMinAllocatedMem(memGuaranteed.intValue()); } if (vm.isSetQuota() && vm.getQuota().isSetId()) { staticVm.setQuotaId(GuidUtils.asGuid(vm.getQuota().getId())); } if (vm.isSetInitialization()) { staticVm.setVmInit(map(vm.getInitialization(), new VmInit())); } // The Domain is now set to VmInit // we only set it for backward compatibility, // if the Domain set via VmInit we ignore it if (vm.isSetDomain() && vm.getDomain().isSetName()) { if (staticVm.getVmInit() == null) { staticVm.setVmInit(new VmInit()); } // We don't want to override the domain if it set via the Initialization object if (!vm.isSetInitialization() || !vm.getInitialization().isSetDomain()) { staticVm.getVmInit().setDomain(vm.getDomain().getName()); } } if (vm.isSetNumaTuneMode()) { NumaTuneMode mode = NumaTuneMode.fromValue(vm.getNumaTuneMode()); if (mode != null) { staticVm.setNumaTuneMode(map(mode, null)); } } return staticVm; } public static int mapOsType(String type) { //TODO remove this treatment when OsType enum is deleted. //backward compatibility code - UNASSIGNED is mapped to OTHER if (OsType.UNASSIGNED.name().equalsIgnoreCase(type)) { type = OsType.OTHER.name(); } return SimpleDependecyInjector.getInstance().get(OsRepository.class).getOsIdByUniqueName(type); } @Mapping(from = VmAffinity.class, to = MigrationSupport.class) public static MigrationSupport map(VmAffinity vmAffinity, MigrationSupport template) { if(vmAffinity!=null){ switch (vmAffinity) { case MIGRATABLE: return MigrationSupport.MIGRATABLE; case USER_MIGRATABLE: return MigrationSupport.IMPLICITLY_NON_MIGRATABLE; case PINNED: return MigrationSupport.PINNED_TO_HOST; default: return null; } } return null; } @Mapping(from = MigrationSupport.class, to = VmAffinity.class) public static VmAffinity map(MigrationSupport migrationSupport, VmAffinity template) { if(migrationSupport!=null){ switch (migrationSupport) { case MIGRATABLE: return VmAffinity.MIGRATABLE; case IMPLICITLY_NON_MIGRATABLE: return VmAffinity.USER_MIGRATABLE; case PINNED_TO_HOST: return VmAffinity.PINNED; default: return null; } } return null; } @Mapping(from = org.ovirt.engine.core.common.businessentities.VM.class, to = VM.class) public static VM map(org.ovirt.engine.core.common.businessentities.VM entity, VM template) { return map(entity, template, true); } public static VM map(org.ovirt.engine.core.common.businessentities.VM entity, VM template, boolean showDynamicInfo) { VM model = template != null ? template : new VM(); mapVmBaseEntityToModel(model, entity.getStaticData()); if (entity.getVmtGuid() != null) { model.setTemplate(new Template()); model.getTemplate().setId(entity.getVmtGuid().toString()); // display this property only if the vm is stateless // otherwise the value of this property is meaningless and misleading if(entity.isStateless()) { model.setUseLatestTemplateVersion(entity.isUseLatestVersion()); } } if (entity.getInstanceTypeId() != null) { model.setInstanceType(new InstanceType()); model.getInstanceType().setId(entity.getInstanceTypeId().toString()); } if (entity.getStatus() != null) { model.setStatus(StatusUtils.create(map(entity.getStatus(), null))); if (entity.getStatus()==VMStatus.Paused) { model.getStatus().setDetail(entity.getVmPauseStatus().name().toLowerCase()); } } if (entity.getStopReason() != null) { model.setStopReason(entity.getStopReason()); } if (entity.getBootSequence() != null || entity.getKernelUrl() != null || entity.getInitrdUrl() != null || entity.getKernelParams() != null) { OperatingSystem os = new OperatingSystem(); os.setType(SimpleDependecyInjector.getInstance().get(OsRepository.class).getUniqueOsNames().get(entity.getVmOsId())); os.setKernel(entity.getKernelUrl()); os.setInitrd(entity.getInitrdUrl()); os.setCmdline(entity.getKernelParams()); model.setOs(os); } if(entity.isUseHostCpuFlags()) { model.getCpu().setMode(CpuMode.HOST_PASSTHROUGH.value()); } model.getCpu().setCpuTune(stringToCpuTune(entity.getCpuPinning())); model.getCpu().setArchitecture(CPUMapper.map(entity.getClusterArch(), null)); if (entity.getVmPoolId() != null) { VmPool pool = new VmPool(); pool.setId(entity.getVmPoolId().toString()); model.setVmPool(pool); } model.setDisplay(new Display()); // some fields (like boot-order,display..) have static value (= the permanent config) // and dynamic value (current/last run value, that can be different in case of run-once or edit while running) if (showDynamicInfo && entity.getDynamicData() != null && entity.getStatus().isRunningOrPaused()) { if (model.getOs() != null && entity.getBootSequence() != null) { for (Boot boot : map(entity.getBootSequence(), null)) { model.getOs().getBoot().add(boot); } } } else { if (model.getOs() != null) { for (Boot boot : map(entity.getDefaultBootSequence(), null)) { model.getOs().getBoot().add(boot); } } } // fill dynamic data if (entity.getDynamicData() != null && !entity.getStatus().isNotRunning()) { if(entity.getRunOnVds() != null) { model.setHost(new Host()); model.getHost().setId(entity.getRunOnVds().toString()); } final boolean hasIps = entity.getVmIp() != null && !entity.getVmIp().isEmpty(); final boolean hasFqdn = entity.getVmFQDN() != null && !entity.getVmFQDN().isEmpty(); if (hasIps || hasFqdn) { model.setGuestInfo(new GuestInfo()); if (hasFqdn) { model.getGuestInfo().setFqdn(entity.getVmFQDN()); } if (hasIps){ IPs ips = new IPs(); for (String item : entity.getVmIp().split(" ")) { if (!item.equals("")) { IP ip = new IP(); ip.setAddress(item.trim()); ips.getIPs().add(ip); } } if (!ips.getIPs().isEmpty()) { model.getGuestInfo().setIps(ips); } } } if (entity.getLastStartTime() != null) { model.setStartTime(DateMapper.map(entity.getLastStartTime(), null)); } model.setRunOnce(entity.isRunOnce()); GraphicsType graphicsType = deriveGraphicsType(entity.getGraphicsInfos()); if (graphicsType != null) { model.getDisplay().setType(DisplayMapper.map(graphicsType, null).value()); GraphicsInfo graphicsInfo = entity.getGraphicsInfos().get(graphicsType); model.getDisplay().setAddress(graphicsInfo == null ? null : graphicsInfo.getIp()); Integer displayPort = graphicsInfo == null ? null : graphicsInfo.getPort(); model.getDisplay().setPort(displayPort == null || displayPort.equals(-1) ? null : displayPort); Integer displaySecurePort = graphicsInfo == null ? null : graphicsInfo.getTlsPort(); model.getDisplay().setSecurePort(displaySecurePort==null || displaySecurePort.equals(-1) ? null : displaySecurePort); } } if (entity.getLastStopTime() != null) { model.setStopTime(DateMapper.map(entity.getLastStopTime(), null)); } model.getDisplay().setMonitors(entity.getNumOfMonitors()); model.getDisplay().setSingleQxlPci(entity.getSingleQxlPci()); model.getDisplay().setAllowOverride(entity.getAllowConsoleReconnect()); model.getDisplay().setSmartcardEnabled(entity.isSmartcardEnabled()); model.getDisplay().setKeyboardLayout(entity.getDefaultVncKeyboardLayout()); model.getDisplay().setFileTransferEnabled(entity.isSpiceFileTransferEnabled()); model.getDisplay().setCopyPasteEnabled(entity.isSpiceCopyPasteEnabled()); model.getDisplay().setProxy(getEffectiveSpiceProxy(entity)); model.setStateless(entity.isStateless()); model.setDeleteProtected(entity.isDeleteProtected()); model.setSso(SsoMapper.map(entity.getSsoMethod(), null)); model.setHighAvailability(new HighAvailability()); model.getHighAvailability().setEnabled(entity.isAutoStartup()); model.getHighAvailability().setPriority(entity.getPriority()); if (entity.getOrigin() != null) { model.setOrigin(map(entity.getOrigin(), null)); } model.setPlacementPolicy(new VmPlacementPolicy()); if(entity.getDedicatedVmForVds() !=null){ model.getPlacementPolicy().setHost(new Host()); model.getPlacementPolicy().getHost().setId(entity.getDedicatedVmForVds().toString()); } VmAffinity vmAffinity = map(entity.getMigrationSupport(), null); if(vmAffinity !=null){ model.getPlacementPolicy().setAffinity(vmAffinity.value()); } MemoryPolicy policy = new MemoryPolicy(); policy.setGuaranteed((long)entity.getMinAllocatedMem() * (long)BYTES_PER_MB); model.setMemoryPolicy(policy); if (entity.getQuotaId()!=null) { Quota quota = new Quota(); quota.setId(entity.getQuotaId().toString()); model.setQuota(quota); } if (entity.getVmInit() != null) { model.setInitialization(map(entity.getVmInit(), null)); } model.setNextRunConfigurationExists(entity.isNextRunConfigurationExists()); model.setNumaTuneMode(map(entity.getNumaTuneMode(), null)); return model; } private static String getEffectiveSpiceProxy(org.ovirt.engine.core.common.businessentities.VM entity) { if (StringUtils.isNotBlank(entity.getVmPoolSpiceProxy())) { return entity.getVmPoolSpiceProxy(); } if (StringUtils.isNotBlank(entity.getVdsGroupSpiceProxy())) { return entity.getVdsGroupSpiceProxy(); } String globalSpiceProxy = Config.getValue(ConfigValues.SpiceProxyDefault); if (StringUtils.isNotBlank(globalSpiceProxy)) { return globalSpiceProxy; } return null; } // for backwards compatibility // returns graphics type of a running vm (can be different than static graphics in vm device due to run once) // if vm has multiple graphics, returns SPICE public static GraphicsType deriveGraphicsType(Map<GraphicsType, GraphicsInfo> graphicsInfos) { if (graphicsInfos != null) { if (graphicsInfos.containsKey(GraphicsType.SPICE)) { return GraphicsType.SPICE; } if (graphicsInfos.containsKey(GraphicsType.VNC)) { return GraphicsType.VNC; } } return null; } @Mapping(from = VM.class, to = RunVmOnceParams.class) public static RunVmOnceParams map(VM vm, RunVmOnceParams template) { RunVmOnceParams params = template != null ? template : new RunVmOnceParams(); if (vm.isSetStateless() && vm.isStateless()) { params.setRunAsStateless(true); } if (vm.isSetDisplay()) { if (vm.getDisplay().isSetKeyboardLayout()) { String vncKeyboardLayout = vm.getDisplay().getKeyboardLayout(); params.setVncKeyboardLayout(vncKeyboardLayout); } DisplayMapper.fillDisplayInParams(vm, params); } if (vm.isSetOs() && vm.getOs().getBoot().size() > 0) { params.setBootSequence(map(vm.getOs().getBoot(), null)); } if (vm.isSetCdroms() && vm.getCdroms().isSetCdRoms()) { String file = vm.getCdroms().getCdRoms().get(0).getFile().getId(); if (file != null) { params.setDiskPath(file); } } if (vm.isSetFloppies() && vm.getFloppies().isSetFloppies()) { String file = vm.getFloppies().getFloppies().get(0).getFile().getId(); if (file != null) { params.setFloppyPath(file); } } if (vm.isSetCustomProperties()) { params.setCustomProperties(CustomPropertiesParser.parse(vm.getCustomProperties().getCustomProperty())); } if (vm.isSetBios()) { if (vm.getBios().isSetBootMenu()) { params.setBootMenuEnabled(vm.getBios().getBootMenu().isEnabled()); } } if (vm.isSetOs()) { if (vm.getOs().isSetBoot() && vm.getOs().getBoot().size() > 0) { params.setBootSequence(map(vm.getOs().getBoot(), null)); } if (vm.getOs().isSetKernel()) { params.setKernelUrl(vm.getOs().getKernel()); } if (vm.getOs().isSetInitrd()) { params.setInitrdUrl(vm.getOs().getInitrd()); } if (vm.getOs().isSetCmdline()) { params.setKernelParams(vm.getOs().getCmdline()); } } if (vm.isSetDomain() && vm.getDomain().isSetName()) { params.setSysPrepDomainName(vm.getDomain().getName()); if (vm.getDomain().isSetUser()) { if (vm.getDomain().getUser().isSetUserName()) { params.setSysPrepUserName(vm.getDomain().getUser().getUserName()); } if (vm.getDomain().getUser().isSetPassword()) { params.setSysPrepPassword(vm.getDomain().getUser().getPassword()); } } } if (vm.isSetCpuShares()) { params.setCpuShares(vm.getCpuShares()); } if (vm.isSetCustomCpuModel()) { params.setCustomCpuName(vm.getCustomCpuModel()); } if (vm.isSetCustomEmulatedMachine()) { params.setCustomEmulatedMachine(vm.getCustomEmulatedMachine()); } return params; } @Mapping(from = String.class, to = CustomProperties.class) public static CustomProperties map(String entity, CustomProperties template) { CustomProperties model = template != null ? template : new CustomProperties(); if (entity != null) { for (String envStr : entity.split(";", -1)) { String[] parts = envStr.split("=", 2); if (parts.length >= 1) { CustomProperty env = new CustomProperty(); env.setName(parts[0]); if (parts.length == 1) { env.setValue(parts[1]); } model.getCustomProperty().add(env); } } } return model; } @Mapping(from = CustomProperties.class, to = String.class) public static String map(CustomProperties model, String template) { StringBuilder buf = template != null ? new StringBuilder(template) : new StringBuilder(); for (CustomProperty env : model.getCustomProperty()) { String envStr = map(env, null); if (envStr != null) { if (buf.length() > 0) { buf.append(";"); } buf.append(envStr); } } return buf.toString(); } @Mapping(from = CustomProperty.class, to = String.class) public static String map(CustomProperty model, String template) { if (model.isSetName()) { String ret = model.getName() + "="; if (model.isSetValue()) { ret += model.getValue(); } return ret; } else { return template; } } @Mapping(from = VmType.class, to = org.ovirt.engine.core.common.businessentities.VmType.class) public static org.ovirt.engine.core.common.businessentities.VmType map(VmType type, org.ovirt.engine.core.common.businessentities.VmType incoming) { switch (type) { case DESKTOP: return org.ovirt.engine.core.common.businessentities.VmType.Desktop; case SERVER: return org.ovirt.engine.core.common.businessentities.VmType.Server; default: return null; } } @Mapping(from = org.ovirt.engine.core.common.businessentities.VmType.class, to = String.class) public static String map(org.ovirt.engine.core.common.businessentities.VmType type, String incoming) { switch (type) { case Desktop: return VmType.DESKTOP.value(); case Server: return VmType.SERVER.value(); default: return null; } } @Mapping(from = String.class, to = OriginType.class) public static OriginType map(String type, OriginType incoming) { try { return OriginType.valueOf(type.toUpperCase()); } catch (IllegalArgumentException e) { return null; } } @Mapping(from = ConfigurationType.class, to = org.ovirt.engine.core.common.businessentities.ConfigurationType.class) public static org.ovirt.engine.core.common.businessentities.ConfigurationType map(org.ovirt.engine.api.model.ConfigurationType configurationType, org.ovirt.engine.core.common.businessentities.ConfigurationType template) { switch (configurationType) { case OVF: return org.ovirt.engine.core.common.businessentities.ConfigurationType.OVF; default: return null; } } @Mapping(from = org.ovirt.engine.core.common.businessentities.ConfigurationType.class, to = ConfigurationType.class) public static ConfigurationType map(org.ovirt.engine.core.common.businessentities.ConfigurationType configurationType, org.ovirt.engine.api.model.ConfigurationType template) { switch (configurationType) { case OVF: return ConfigurationType.OVF; default: return null; } } public static VM map(String data, ConfigurationType type, VM vm) { Initialization initialization = vm.getInitialization(); if (initialization == null) { initialization = new Initialization(); vm.setInitialization(initialization); } Configuration configuration = initialization.getConfiguration(); if (configuration == null) { configuration = new Configuration(); initialization.setConfiguration(configuration); } configuration.setData(data); configuration.setType(type.value()); return vm; } @Mapping(from = org.ovirt.engine.api.model.VmDeviceType.class, to = VmDeviceType.class) public static VmDeviceType map(org.ovirt.engine.api.model.VmDeviceType deviceType, VmDeviceType template) { switch (deviceType) { case FLOPPY: return VmDeviceType.FLOPPY; case CDROM: return VmDeviceType.CDROM; default: return null; } } @Mapping(from = VmDeviceType.class, to = org.ovirt.engine.api.model.VmDeviceType.class) public static org.ovirt.engine.api.model.VmDeviceType map(VmDeviceType deviceType, org.ovirt.engine.api.model.VmDeviceType template) { switch (deviceType) { case FLOPPY: return org.ovirt.engine.api.model.VmDeviceType.FLOPPY; case CDROM: return org.ovirt.engine.api.model.VmDeviceType.CDROM; default: return null; } } @Mapping(from = VMStatus.class, to = VmStatus.class) public static VmStatus map(VMStatus entityStatus, VmStatus template) { switch (entityStatus) { case Unassigned: return VmStatus.UNASSIGNED; case Down: return VmStatus.DOWN; case Up: return VmStatus.UP; case PoweringUp: return VmStatus.POWERING_UP; case Paused: return VmStatus.PAUSED; case MigratingFrom: return VmStatus.MIGRATING; case MigratingTo: return VmStatus.MIGRATING; case Unknown: return VmStatus.UNKNOWN; case NotResponding: return VmStatus.NOT_RESPONDING; case WaitForLaunch: return VmStatus.WAIT_FOR_LAUNCH; case RebootInProgress: return VmStatus.REBOOT_IN_PROGRESS; case SavingState: return VmStatus.SAVING_STATE; case RestoringState: return VmStatus.RESTORING_STATE; case Suspended: return VmStatus.SUSPENDED; case ImageLocked: return VmStatus.IMAGE_LOCKED; case PoweringDown: return VmStatus.POWERING_DOWN; default: return null; } } @Mapping(from = BootSequence.class, to = List.class) public static List<Boot> map(BootSequence bootSequence, List<Boot> template) { List<Boot> boots = template != null ? template : new ArrayList<Boot>(); switch (bootSequence) { case C: boots.add(getBoot(BootDevice.HD)); break; case DC: boots.add(getBoot(BootDevice.CDROM)); boots.add(getBoot(BootDevice.HD)); break; case N: boots.add(getBoot(BootDevice.NETWORK)); break; case CDN: boots.add(getBoot(BootDevice.HD)); boots.add(getBoot(BootDevice.CDROM)); boots.add(getBoot(BootDevice.NETWORK)); break; case CND: boots.add(getBoot(BootDevice.HD)); boots.add(getBoot(BootDevice.NETWORK)); boots.add(getBoot(BootDevice.CDROM)); break; case DCN: boots.add(getBoot(BootDevice.CDROM)); boots.add(getBoot(BootDevice.HD)); boots.add(getBoot(BootDevice.NETWORK)); break; case DNC: boots.add(getBoot(BootDevice.CDROM)); boots.add(getBoot(BootDevice.NETWORK)); boots.add(getBoot(BootDevice.HD)); break; case NCD: boots.add(getBoot(BootDevice.NETWORK)); boots.add(getBoot(BootDevice.HD)); boots.add(getBoot(BootDevice.CDROM)); break; case NDC: boots.add(getBoot(BootDevice.NETWORK)); boots.add(getBoot(BootDevice.CDROM)); boots.add(getBoot(BootDevice.HD)); break; case CD: boots.add(getBoot(BootDevice.HD)); boots.add(getBoot(BootDevice.CDROM)); break; case D: boots.add(getBoot(BootDevice.CDROM)); break; case CN: boots.add(getBoot(BootDevice.HD)); boots.add(getBoot(BootDevice.NETWORK)); break; case DN: boots.add(getBoot(BootDevice.CDROM)); boots.add(getBoot(BootDevice.NETWORK)); break; case NC: boots.add(getBoot(BootDevice.NETWORK)); boots.add(getBoot(BootDevice.HD)); break; case ND: boots.add(getBoot(BootDevice.NETWORK)); boots.add(getBoot(BootDevice.CDROM)); break; } return boots; } private static Boot getBoot(BootDevice device) { Boot boot = new Boot(); boot.setDev(device.value()); return boot; } @Mapping(from = Boot.class, to = List.class) public static BootSequence map(List<Boot> boot, BootSequence template) { Set<BootDevice> devSet = new LinkedHashSet<BootDevice>(); for (Boot b : boot) { if (b.isSetDev()) { BootDevice dev = BootDevice.fromValue(b.getDev()); if (dev != null) { devSet.add(dev); } } } List<BootDevice> devs = new ArrayList<BootDevice>(devSet); if (devs.size() == 1) { switch (devs.get(0)) { case CDROM: return BootSequence.D; case HD: return BootSequence.C; case NETWORK: return BootSequence.N; } } else if (devs.size() == 2) { switch (devs.get(0)) { case CDROM: switch (devs.get(1)) { case HD: return BootSequence.DC; case NETWORK: return BootSequence.DN; } break; case HD: switch (devs.get(1)) { case CDROM: return BootSequence.CD; case NETWORK: return BootSequence.CN; } break; case NETWORK: switch (devs.get(1)) { case HD: return BootSequence.NC; case CDROM: return BootSequence.ND; } break; } } else if (devs.size() == 3) { switch (devs.get(0)) { case CDROM: switch (devs.get(1)) { case HD: return BootSequence.DCN; case NETWORK: return BootSequence.DNC; } break; case HD: switch (devs.get(1)) { case CDROM: return BootSequence.CDN; case NETWORK: return BootSequence.CND; } break; case NETWORK: switch (devs.get(1)) { case HD: return BootSequence.NCD; case CDROM: return BootSequence.NDC; } break; } } return null; } @Mapping(from = VmPayload.class, to = Payload.class) public static Payload map(VmPayload entity, Payload template) { if (entity.getDeviceType() != null || entity.getFiles().isEmpty()) { Payload model = template != null ? template : new Payload(); if (entity.getDeviceType() != null) { org.ovirt.engine.api.model.VmDeviceType deviceType = map(entity.getDeviceType(), null); if (deviceType != null) { model.setType(deviceType.value()); } } model.setVolumeId(entity.getVolumeId()); if (entity.getFiles().size() > 0) { model.setFiles(new Files()); for (Map.Entry<String, String> entry : entity.getFiles().entrySet()) { File file = new File(); file.setName(entry.getKey()); file.setContent(entry.getValue()); model.getFiles().getFiles().add(file); } } return model; } return null; } @Mapping(from = Payload.class, to = VmPayload.class) public static VmPayload map(Payload model, VmPayload template) { VmPayload entity = template != null ? template : new VmPayload(); if (model.getType() != null) { org.ovirt.engine.api.model.VmDeviceType deviceType = org.ovirt.engine.api.model.VmDeviceType.fromValue(model.getType()); if (deviceType!=null) { entity.setDeviceType(map(deviceType, null)); } } if (model.isSetVolumeId()) { entity.setVolumeId(model.getVolumeId()); } if (model.isSetFiles()) { for (File file : model.getFiles().getFiles()) { entity.getFiles().put(file.getName(), file.getContent()); } } return entity; } @Mapping(from = Initialization.class, to = VmInit.class) public static VmInit map(Initialization model, VmInit template) { VmInit entity = template != null ? template : new VmInit(); if (model.isSetHostName()) { entity.setHostname(model.getHostName()); } if (model.isSetDomain()) { entity.setDomain(model.getDomain()); } if (model.isSetTimezone()) { entity.setTimeZone(model.getTimezone()); } if (model.isSetAuthorizedSshKeys()) { entity.setAuthorizedKeys(model.getAuthorizedSshKeys()); } if (model.isSetRegenerateSshKeys()) { entity.setRegenerateKeys(model.isRegenerateSshKeys()); } if (model.isSetDnsServers()) { entity.setDnsServers(model.getDnsServers()); } if (model.isSetDnsSearch()) { entity.setDnsSearch(model.getDnsSearch()); } if (model.isSetWindowsLicenseKey()) { entity.setWinKey(model.getWindowsLicenseKey()); } if (model.isSetRootPassword()) { entity.setRootPassword(model.getRootPassword()); } if (model.isSetCustomScript()) { entity.setCustomScript(model.getCustomScript()); } if (model.isSetNicConfigurations()) { List<VmInitNetwork> networks = new ArrayList<VmInitNetwork>(); for (GuestNicConfiguration nic : model.getNicConfigurations().getNicConfigurations()) { networks.add(map(nic, null)); } entity.setNetworks(networks); } if (model.isSetInputLocale()) { entity.setInputLocale(model.getInputLocale()); } if (model.isSetUiLanguage()) { entity.setUiLanguage(model.getUiLanguage()); } if (model.isSetSystemLocale()) { entity.setSystemLocale(model.getSystemLocale()); } if (model.isSetUserLocale()) { entity.setUserLocale(model.getUserLocale()); } if (model.isSetUserName()) { entity.setUserName(model.getUserName()); } if (model.isSetActiveDirectoryOu()) { entity.setUserName(model.getActiveDirectoryOu()); } if (model.isSetOrgName()) { entity.setOrgName(model.getOrgName()); } return entity; } @Mapping(from = VmInit.class, to = Initialization.class) public static Initialization map(VmInit entity, Initialization template) { Initialization model = template != null ? template : new Initialization(); if (entity.getHostname() != null) { model.setHostName(entity.getHostname()); } if (StringUtils.isNotBlank(entity.getDomain())) { model.setDomain(entity.getDomain()); } if (entity.getTimeZone() != null) { model.setTimezone(entity.getTimeZone()); } if (entity.getAuthorizedKeys() != null) { model.setAuthorizedSshKeys(entity.getAuthorizedKeys()); } if (entity.getRegenerateKeys() != null) { model.setRegenerateSshKeys(entity.getRegenerateKeys()); } if (entity.getDnsServers() != null) { model.setDnsServers(entity.getDnsServers()); } if (entity.getDnsSearch() != null) { model.setDnsSearch(entity.getDnsSearch()); } if (entity.getWinKey() != null) { model.setWindowsLicenseKey(entity.getWinKey()); } if (entity.getRootPassword() != null || entity.isPasswordAlreadyStored()) { model.setRootPassword("******"); } if (entity.getCustomScript() != null) { model.setCustomScript(entity.getCustomScript()); } if (entity.getNetworks() != null) { model.setNicConfigurations(new GuestNicsConfiguration()); for (VmInitNetwork network : entity.getNetworks()) { model.getNicConfigurations().getNicConfigurations().add(map(network, null)); } } if (entity.getInputLocale() != null) { model.setInputLocale(entity.getInputLocale()); } if (entity.getUiLanguage() != null) { model.setUiLanguage(entity.getUiLanguage()); } if (entity.getSystemLocale() != null) { model.setSystemLocale(entity.getSystemLocale()); } if (entity.getUserLocale() != null) { model.setUserLocale(entity.getUserLocale()); } if (entity.getUserName() != null) { model.setUserName(entity.getUserName()); } if (entity.getActiveDirectoryOU() != null) { model.setActiveDirectoryOu(entity.getActiveDirectoryOU()); } if (entity.getOrgName() != null) { model.setOrgName(entity.getOrgName()); } return model; } @Mapping(from = GuestNicConfiguration.class, to = VmInitNetwork.class) public static VmInitNetwork map(GuestNicConfiguration model, VmInitNetwork template) { VmInitNetwork entity = template != null ? template : new VmInitNetwork(); if (model.isSetName()) { entity.setName(model.getName()); } if (model.isOnBoot()) { entity.setStartOnBoot(model.isOnBoot()); } if (model.isSetBootProtocol()) { entity.setBootProtocol(BootProtocolMapper.map(BootProtocol.fromValue(model.getBootProtocol()), NetworkBootProtocol.NONE)); } if (model.isSetIp()) { if (model.getIp().isSetAddress()) { entity.setIp(model.getIp().getAddress()); } if (model.getIp().isSetNetmask()) { entity.setNetmask(model.getIp().getNetmask()); } if (model.getIp().isSetGateway()) { entity.setGateway(model.getIp().getGateway()); } } return entity; } @Mapping(from = VmInitNetwork.class, to = GuestNicConfiguration.class) public static GuestNicConfiguration map(VmInitNetwork entity, GuestNicConfiguration template) { GuestNicConfiguration model = template != null ? template : new GuestNicConfiguration(); model.setName(entity.getName()); model.setOnBoot(entity.getStartOnBoot()); if (entity.getBootProtocol() != null) { model.setBootProtocol(BootProtocolMapper.map(entity.getBootProtocol(), null).value()); } IP ip = new IP(); model.setIp(ip); ip.setAddress(entity.getIp()); ip.setNetmask(entity.getNetmask()); ip.setGateway(entity.getGateway()); return model; } @Mapping(from = CloudInit.class, to = VmInit.class) public static VmInit map(CloudInit model, VmInit template) { VmInit entity = template != null ? template : new VmInit(); if (model.isSetHost() && model.getHost().isSetAddress()) { entity.setHostname(model.getHost().getAddress()); } if (model.isSetAuthorizedKeys() && model.getAuthorizedKeys().isSetAuthorizedKeys() && !model.getAuthorizedKeys().getAuthorizedKeys().isEmpty()) { StringBuilder keys = new StringBuilder(); for (AuthorizedKey authKey : model.getAuthorizedKeys().getAuthorizedKeys()) { if (keys.length() > 0) { keys.append("\n"); } keys.append(authKey.getKey()); } entity.setAuthorizedKeys(keys.toString()); } if (model.isSetRegenerateSshKeys()) { entity.setRegenerateKeys(model.isRegenerateSshKeys()); } if (model.isSetNetworkConfiguration()) { if (model.getNetworkConfiguration().isSetNics()) { List<VmInitNetwork> interfaces = new ArrayList<VmInitNetwork>(); for (NIC iface : model.getNetworkConfiguration().getNics().getNics()) { VmInitNetwork vmInitInterface = new VmInitNetwork(); if (iface.isSetName()) { vmInitInterface.setName(iface.getName()); } interfaces.add(vmInitInterface); if (iface.isSetBootProtocol()) { NetworkBootProtocol protocol = BootProtocolMapper.map (BootProtocol.fromValue(iface.getBootProtocol()), vmInitInterface.getBootProtocol()); vmInitInterface.setBootProtocol(protocol); if (protocol != NetworkBootProtocol.DHCP && iface.isSetNetwork() && iface.getNetwork().isSetIp()) { if (iface.getNetwork().getIp().isSetAddress()) { vmInitInterface.setIp(iface.getNetwork().getIp().getAddress()); } if (iface.getNetwork().getIp().isSetNetmask()) { vmInitInterface.setNetmask(iface.getNetwork().getIp().getNetmask()); } if (iface.getNetwork().getIp().isSetGateway()) { vmInitInterface.setGateway(iface.getNetwork().getIp().getGateway()); } } if (iface.isSetOnBoot() && iface.isOnBoot()) { vmInitInterface.setStartOnBoot(true); } } } entity.setNetworks(interfaces); } if (model.getNetworkConfiguration().isSetDns()) { if (model.getNetworkConfiguration().getDns().isSetServers() && model.getNetworkConfiguration().getDns().getServers().isSetHosts() && !model.getNetworkConfiguration().getDns().getServers().getHosts().isEmpty()) { StringBuilder dnsServers = new StringBuilder(); for (Host host : model.getNetworkConfiguration().getDns().getServers().getHosts()) { if (host.isSetAddress()) { dnsServers.append(host.getAddress()); } } entity.setDnsServers(dnsServers.toString()); } if (model.getNetworkConfiguration().getDns().isSetSearchDomains() && model.getNetworkConfiguration().getDns().getSearchDomains().isSetHosts() && !model.getNetworkConfiguration().getDns().getSearchDomains().getHosts().isEmpty()) { StringBuilder searchDomains = new StringBuilder(); for (Host host : model.getNetworkConfiguration().getDns().getSearchDomains().getHosts()) { if (host.isSetAddress()) { searchDomains.append(host.getAddress()); } } entity.setDnsSearch(searchDomains.toString()); } } } if (model.isSetTimezone() && model.getTimezone() != null) { entity.setTimeZone(model.getTimezone()); } if (model.isSetUsers()) { for (User user : model.getUsers().getUsers()) { String userName = user.getUserName(); if (StringUtils.equals(userName, "root")) { entity.setUserName(userName); String userPassword = user.getPassword(); if (userPassword != null) { entity.setRootPassword(userPassword); } } } } // files is Deprecated, we are using the Payload for passing files // We are storing the first file as a Cloud Init custom script // for RunOnce backward compatibility. if (model.isSetFiles() && model.getFiles().isSetFiles() && !model.getFiles().getFiles().isEmpty()) { File file = model.getFiles().getFiles().get(0); entity.setCustomScript(file.getContent()); } return entity; } static String cpuTuneToString(final CpuTune tune) { final StringBuilder builder = new StringBuilder(); boolean first = true; for(final VCpuPin pin : tune.getVCpuPin()) { if(first) { first = false; } else { builder.append("_"); } builder.append(pin.getVcpu()).append('#').append(pin.getCpuSet()); } return builder.toString(); } /** * Maps the stringified CPU-pinning to the API format. * @param string * @return */ static CpuTune stringToCpuTune(String cpuPinning) { if(cpuPinning == null || cpuPinning.equals("")) { return null; } final CpuTune cpuTune = new CpuTune(); for(String strCpu : cpuPinning.split("_")) { VCpuPin pin = stringToVCpupin(strCpu); cpuTune.getVCpuPin().add(pin); } return cpuTune; } static VCpuPin stringToVCpupin(final String strCpu) { final String[] strPin = strCpu.split(" if (strPin.length != 2) { throw new IllegalArgumentException("Bad format: " + strCpu); } final VCpuPin pin = new VCpuPin(); try { pin.setVcpu(Integer.parseInt(strPin[0])); } catch (NumberFormatException e) { throw new IllegalArgumentException("Bad format: " + strCpu, e); } if (strPin[1].matches("\\^?(\\d+(\\-\\d+)?)(,\\^?((\\d+(\\-\\d+)?)))*")) { pin.setCpuSet(strPin[1]); } else { throw new IllegalArgumentException("Bad format: " + strPin[1]); } return pin; } public static UsbPolicy getUsbPolicyOnCreate(Usb usb, Version vdsGroupVersion) { if (usb == null || !usb.isSetEnabled() || !usb.isEnabled()) { return UsbPolicy.DISABLED; } else { UsbType usbType = getUsbType(usb); if (usbType == null) { return getUsbPolicyAccordingToClusterVersion(vdsGroupVersion); } else { return getUsbPolicyAccordingToUsbType(usbType); } } } public static UsbPolicy getUsbPolicyOnUpdate(Usb usb, UsbPolicy currentPolicy, Version vdsGroupVersion) { if (usb == null) return currentPolicy; if (usb.isSetEnabled()) { if (!usb.isEnabled()) return UsbPolicy.DISABLED; else { UsbType usbType = getUsbType(usb); if (usbType != null) { return getUsbPolicyAccordingToUsbType(usbType); } else { return currentPolicy == UsbPolicy.DISABLED ? getUsbPolicyAccordingToClusterVersion(vdsGroupVersion) : currentPolicy; } } } else { if (currentPolicy == UsbPolicy.DISABLED) return UsbPolicy.DISABLED; UsbType usbType = getUsbType(usb); if (usbType != null) { return getUsbPolicyAccordingToUsbType(UsbType.fromValue(usb.getType())); } else { return currentPolicy; } } } private static UsbType getUsbType(Usb usb) { return usb.isSetType() ? UsbType.fromValue(usb.getType()) : null; } private static UsbPolicy getUsbPolicyAccordingToClusterVersion(Version vdsGroupVersion) { return vdsGroupVersion.compareTo(Version.v3_1) >= 0 ? UsbPolicy.ENABLED_NATIVE : UsbPolicy.ENABLED_LEGACY; } private static UsbPolicy getUsbPolicyAccordingToUsbType(UsbType usbType) { switch (usbType) { case LEGACY: return UsbPolicy.ENABLED_LEGACY; case NATIVE: return UsbPolicy.ENABLED_NATIVE; default: return null; // Should never get here } } /** * This method maps the VM's open sessions with users. Engine currently does not regard sessions as business * entities, and therefore a session doesn't have an ID. Generating IDs for sessions is outside the scope of this * method and should be done by the method's invoker. * * The session involves a user. Sometimes this is an ovirt-user, and sometimes not. Engine provides only the user * name, and this method maps it by placing it inside a 'User' object in the session. If invokers want to identify * the ovirt user and provide a link to it, it's their responsibility to do so; this is out of the scope of this * method. */ public static Sessions map(org.ovirt.engine.core.common.businessentities.VM vm, Sessions sessions) { if (sessions == null) { sessions = new Sessions(); } mapConsoleSession(vm, sessions); mapGuestSessions(vm, sessions); return sessions; } /** * This method maps the session of the 'console user', if exists. This is the ovirt user who opened a session * through the user-console; the one who is said to be 'logged in' (or 'have the ticket') to this VM. Currently * engine makes available only the name and IP of this user. In the future it may make available also the connection * protocol used in the session (spice/vnc). */ private static Sessions mapConsoleSession(org.ovirt.engine.core.common.businessentities.VM vm, Sessions sessions) { String consoleUserName = vm.getConsoleCurentUserName(); // currently in format user@domain, so needs to be // parsed. if (consoleUserName != null && !consoleUserName.isEmpty()) { String userName = parseUserName(consoleUserName); String domainName = parseDomainName(consoleUserName); User consoleUser = new User(); consoleUser.setUserName(userName); consoleUser.setDomain(new Domain()); consoleUser.getDomain().setName(domainName); Session consoleSession = new Session(); consoleSession.setUser(consoleUser); if (vm.getClientIp()!=null && !vm.getClientIp().isEmpty()) { IP ip = new IP(); ip.setAddress(vm.getClientIp()); consoleSession.setIp(ip); } consoleSession.setConsoleUser(true); // TODO: in the future, map the connection protocol as well sessions.getSessions().add(consoleSession); } return sessions; } /** * Parse the user name out of the provided string. Expects 'user@domain', but if no '@' found, will assume that * domain was omitted and that the whole String is the user-name. */ private static String parseDomainName(String consoleUserName) { return consoleUserName.contains("@") ? consoleUserName.substring(consoleUserName.indexOf("@") + 1, consoleUserName.length()) : null; } /** * Parse the domain name out of the provided string. Expects 'user@domain'. If no '@' found, will assume that domain * name was omitted and return null. */ private static String parseUserName(String consoleUserName) { return consoleUserName.contains("@") ? consoleUserName.substring(0, consoleUserName.indexOf("@")) : consoleUserName; } /** * This method maps the sessions of users who are connected to the VM, but are not the 'logged-in'/'console' user. * Currently the information that engine supplies about these users is only a string, which contains the name of * only one such user, if exists (the user is not necessarily an ovirt user). In the future the engine may pass * multiple 'guest' users, along with their IPs and perhaps also the connection protocols that they are using (SSH, * RDP...) */ private static Sessions mapGuestSessions(org.ovirt.engine.core.common.businessentities.VM vm, Sessions sessions) { String guestUserName = vm.getGuestCurentUserName(); if (guestUserName != null && !guestUserName.isEmpty()) { Session guestSession = new Session(); User user = new User(); user.setUserName(guestUserName); guestSession.setUser(user); // TODO: in the future, map the user-IP and connection protocol as well sessions.getSessions().add(guestSession); } return sessions; } @Mapping(from = NumaTuneMode.class, to = org.ovirt.engine.core.common.businessentities.NumaTuneMode.class) public static org.ovirt.engine.core.common.businessentities.NumaTuneMode map(NumaTuneMode mode, org.ovirt.engine.core.common.businessentities.NumaTuneMode incoming) { switch (mode) { case STRICT: return org.ovirt.engine.core.common.businessentities.NumaTuneMode.STRICT; case INTERLEAVE: return org.ovirt.engine.core.common.businessentities.NumaTuneMode.INTERLEAVE; case PREFERRED: return org.ovirt.engine.core.common.businessentities.NumaTuneMode.PREFERRED; default: return null; } } @Mapping(from = org.ovirt.engine.core.common.businessentities.NumaTuneMode.class, to = String.class) public static String map(org.ovirt.engine.core.common.businessentities.NumaTuneMode mode, String incoming) { if (mode == null) { return null; } switch (mode) { case STRICT: return NumaTuneMode.STRICT.value(); case INTERLEAVE: return NumaTuneMode.INTERLEAVE.value(); case PREFERRED: return NumaTuneMode.PREFERRED.value(); default: return null; } } }
package org.ovirt.engine.core.utils.servlet; 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.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyObject; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.io.File; import java.io.IOException; import java.util.Locale; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; /** * Unit tests for the {@code DocsServlet} class. */ @RunWith(MockitoJUnitRunner.class) public class DocsServletTest { DocsServlet testServlet; /** * The mockRequest used in the test. */ @Mock HttpServletRequest mockRequest; @Mock HttpServletResponse mockResponse; @Mock HttpSession mockSession; @Mock ServletConfig mockConfig; @Before public void setUp() throws Exception { testServlet = new DocsServlet(); when(mockConfig.getInitParameter("file")).thenReturn(this.getClass().getResource("filetest").toURI(). toASCIIString().replaceAll("file:", "")); ServletContext mockContext = mock(ServletContext.class); when(mockConfig.getServletContext()).thenReturn(mockContext); testServlet.init(mockConfig); when(mockRequest.getSession(true)).thenReturn(mockSession); } /** * Test method for {@link org.ovirt.engine.core.DocsServlet#doGet(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse)}. * @throws ServletException If test fails * @throws IOException If test fails */ @Test public void testDoGet_CheckIndex() throws ServletException, IOException { //Because we would have found the index file, we do a redirect and thus the response is committed. when(mockResponse.isCommitted()).thenReturn(Boolean.TRUE); when(mockRequest.getServletPath()).thenReturn("/docs"); testServlet.doGet(mockRequest, mockResponse); verify(mockResponse).sendRedirect("/docs/index.html"); } /** * Test method for {@link org.ovirt.engine.core.DocsServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)}. * @throws IOException * @throws ServletException */ @Test public void testDoGet_NotFound() throws ServletException, IOException { when(mockRequest.getPathInfo()).thenReturn("/abc/def"); when(mockRequest.getServletPath()).thenReturn("/docs"); testServlet.doGet(mockRequest, mockResponse); verify(mockResponse).sendError(HttpServletResponse.SC_NOT_FOUND); } /** * Test method for {@link org.ovirt.engine.core.DocsServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)}. * @throws IOException * @throws ServletException */ @Test public void testDoGet_ResponseLangOkay() throws ServletException, IOException { ServletOutputStream responseOut = mock(ServletOutputStream.class); when(mockResponse.getOutputStream()).thenReturn(responseOut); when(mockRequest.getPathInfo()).thenReturn("/fr/index.html"); when(mockRequest.getServletPath()).thenReturn("/docs"); testServlet.doGet(mockRequest, mockResponse); verify(responseOut).write((byte[])anyObject(), eq(0), anyInt()); } /** * Test method for {@link org.ovirt.engine.core.DocsServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)}. * @throws IOException * @throws ServletException */ @Test public void testDoGet_Lang_MissingFirstTimeNoDispatcher() throws ServletException, IOException { ServletOutputStream responseOut = mock(ServletOutputStream.class); ServletContext mockContext = mock(ServletContext.class); when(mockConfig.getServletContext()).thenReturn(mockContext); when(mockResponse.getOutputStream()).thenReturn(responseOut); when(mockRequest.getPathInfo()).thenReturn("/ja/index.html"); when(mockRequest.getServletPath()).thenReturn("/docs"); testServlet.doGet(mockRequest, mockResponse); verify(mockResponse).sendError(eq(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), anyString()); } /** * Test method for {@link org.ovirt.engine.core.DocsServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)}. * @throws IOException * @throws ServletException */ @Test public void testDoGet_Lang_MissingFirstTimeNoDispatcher_SessionFalse() throws ServletException, IOException { ServletOutputStream responseOut = mock(ServletOutputStream.class); ServletContext mockContext = mock(ServletContext.class); when(mockSession.getAttribute(DocsServlet.LANG_PAGE_SHOWN)).thenReturn(Boolean.FALSE); when(mockConfig.getServletContext()).thenReturn(mockContext); when(mockResponse.getOutputStream()).thenReturn(responseOut); when(mockRequest.getPathInfo()).thenReturn("/ja/index.html"); when(mockRequest.getServletPath()).thenReturn("/docs"); testServlet.doGet(mockRequest, mockResponse); verify(mockResponse).sendError(eq(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), anyString()); } /** * Test method for {@link org.ovirt.engine.core.DocsServlet#determineActualFile(javax.servlet.http.HttpServletRequest, java.lang.String)}. */ @Test public void testDetermineActualFile_US() { File originalFile = ServletUtils.makeFileFromSanePath("/" + Locale.US.toLanguageTag(), testServlet.base); when(mockRequest.getPathInfo()).thenReturn("/" + Locale.US.toLanguageTag()); File actualFile = testServlet.determineActualFile(mockRequest, Locale.US); assertNotNull("actualFile should not be null", actualFile); assertTrue("actualFile should exist", actualFile.exists()); assertEquals("original and actual should match", originalFile, actualFile); } /** * Test method for {@link org.ovirt.engine.core.DocsServlet#determineActualFile(javax.servlet.http.HttpServletRequest, java.lang.String)}. */ @Test public void testDetermineActualFile_Fr() { //Fr exists, so the original and actual should match. File originalFile = ServletUtils.makeFileFromSanePath("/" + Locale.FRENCH.toLanguageTag(), testServlet.base); when(mockRequest.getPathInfo()).thenReturn("/" + Locale.FRENCH.toLanguageTag()); File actualFile = testServlet.determineActualFile(mockRequest, Locale.US); assertNotNull("actualFile should not be null", actualFile); assertTrue("actualFile should exist", actualFile.exists()); assertEquals("original and actual should match", originalFile, actualFile); } /** * Test method for {@link org.ovirt.engine.core.DocsServlet#determineActualFile(javax.servlet.http.HttpServletRequest, java.lang.String)}. */ @Test public void testDetermineActualFile_Jp() { //Japanese does not exist, so the original and actual should NOT match. File originalFile = ServletUtils.makeFileFromSanePath("/" + Locale.JAPANESE.toLanguageTag(), testServlet.base); when(mockRequest.getPathInfo()).thenReturn("/" + Locale.JAPANESE.toLanguageTag()); File actualFile = testServlet.determineActualFile(mockRequest, Locale.JAPANESE); assertNotNull("actualFile should not be null", actualFile); assertFalse("original and actual should not match", originalFile.equals(actualFile)); assertTrue("actual file should end in /en-US", actualFile.toString().endsWith(Locale.US.toLanguageTag())); } /** * Test method for {@link org.ovirt.engine.core.DocsServlet# * getLocaleFromRequest(javax.servlet.http.HttpServletRequest)}. */ @Test public void testGetLocaleFromRequest() { Locale result = testServlet.getLocaleFromRequest(mockRequest); assertEquals("The locale should be en-US", Locale.US, result); when(mockRequest.getHeader(DocsServlet.REFERER)).thenReturn("http://127.0.0.1:8700/webadmin/webadmin/WebAdmin.html?locale=fr"); result = testServlet.getLocaleFromRequest(mockRequest); assertEquals("The locale should be fr", Locale.FRENCH, result); } /** * Test method for {@link org.ovirt.engine.core.DocsServlet# * getLocaleFromRequest(javax.servlet.http.HttpServletRequest)}. */ @Test public void testGetLocaleFromRequest_withHash() { Locale result = testServlet.getLocaleFromRequest(mockRequest); assertEquals("The locale should be en-US", Locale.US, result); when(mockRequest.getHeader(DocsServlet.REFERER)).thenReturn("http://127.0.0.1:8700/webadmin/webadmin/WebAdmin.html?locale=fr#basic"); result = testServlet.getLocaleFromRequest(mockRequest); assertEquals("The locale should be fr", Locale.FRENCH, result); } /** * Test method for {@link org.ovirt.engine.core.DocsServlet#getLocaleFromRequest(javax.servlet.http.HttpServletRequest)}. */ @Test public void testGetLocaleFromRequest_Brazilian() { Locale result = testServlet.getLocaleFromRequest(mockRequest); assertEquals("The locale should be en-US", Locale.US, result); when(mockRequest.getHeader(DocsServlet.REFERER)).thenReturn("http://127.0.0.1:8700/webadmin/webadmin/WebAdmin.html?locale=pt_BR"); result = testServlet.getLocaleFromRequest(mockRequest); assertEquals("The locale should be pt_BR", new Locale("pt", "BR"), result); } /** * Test method for {@link org.ovirt.engine.core.DocsServlet#getLocaleFromRequest(javax.servlet.http.HttpServletRequest)}. */ @Test public void testGetLocaleFromRequest_Path() { when(mockRequest.getPathInfo()).thenReturn("/ja/index.html"); Locale result = testServlet.getLocaleFromRequest(mockRequest); assertEquals("The locale should be ja", Locale.JAPANESE, result); } /** * Test method for {@link org.ovirt.engine.core.DocsServlet#getLocaleFromRequest(javax.servlet.http.HttpServletRequest)}. */ @Test public void testGetLocaleFromRequest_Path_Underscore() { when(mockRequest.getPathInfo()).thenReturn("/ja-JP/index.html"); Locale result = testServlet.getLocaleFromRequest(mockRequest); assertEquals("The locale should be ja_JP", Locale.JAPAN, result); } /** * Test method for {@link org.ovirt.engine.core.DocsServlet#getLocaleStringFromPath(java.lang.String)}. */ @Test public void testGetLocaleStringFromPath() { String result = testServlet.getLocaleStringFromPath(null); assertNull("There should be no result", result); result = testServlet.getLocaleStringFromPath("/index.html"); assertNull("There should be no result", result); //File doesn't exist, it will end up with a 404 eventually result = testServlet.getLocaleStringFromPath("/index2.html"); assertNotNull("There should be a result", result); assertEquals("locale should be 'index2.html'", "index2.html", result); //File does exist, but it is a directory. result = testServlet.getLocaleStringFromPath("/fr/index.html"); assertNotNull("There should be a result", result); assertEquals("locale should be 'fr'", "fr", result); } /** * Test method for {@link org.ovirt.engine.core.DocsServlet#getLocaleStringFromPath(java.lang.String)}. */ @Test public void testGetLocaleStringFromPath_IllegalPath() { assertNull("Path without '/' should return null", testServlet.getLocaleStringFromPath("index.html")); } /** * Test method for {@link org.ovirt.engine.core.DocsServlet#getLocaleStringFromReferer(javax.servlet.http.HttpServletRequest)}. */ @Test public void testGetLocaleStringFromReferer() { String result = testServlet.getLocaleStringFromReferer(mockRequest); assertNull("There should be no result", result); when(mockRequest.getHeader(DocsServlet.REFERER)).thenReturn("123thisisnot a uri"); result = testServlet.getLocaleStringFromReferer(mockRequest); assertNull("There should be no result", result); when(mockRequest.getHeader(DocsServlet.REFERER)).thenReturn("http://127.0.0.1:8700/webadmin/webadmin/WebAdmin.html#noparam"); result = testServlet.getLocaleStringFromReferer(mockRequest); assertNull("There should be no result", result); when(mockRequest.getHeader(DocsServlet.REFERER)).thenReturn("http://127.0.0.1:8700/webadmin/webadmin/WebAdmin.html?param1=something&param2=somethingelse"); result = testServlet.getLocaleStringFromReferer(mockRequest); assertNull("There should be no result", result); } /** * Test method for {@link org.ovirt.engine.core.DocsServlet#getLocaleStringFromReferer(javax.servlet.http.HttpServletRequest)}. */ @Test public void testGetLocaleStringFromReferer_Valid() { when(mockRequest.getHeader(DocsServlet.REFERER)).thenReturn("http://127.0.0.1:8700/webadmin/webadmin/WebAdmin.html?locale=fr"); String result = testServlet.getLocaleStringFromReferer(mockRequest); assertEquals("The result should be 'fr'", "fr", result); when(mockRequest.getHeader(DocsServlet.REFERER)).thenReturn("http://127.0.0.1:8700/webadmin/webadmin/WebAdmin.html?param1=xxx&locale=fr"); result = testServlet.getLocaleStringFromReferer(mockRequest); assertEquals("The result should be 'fr'", "fr", result); when(mockRequest.getHeader(DocsServlet.REFERER)).thenReturn("http://127.0.0.1:8700/webadmin/webadmin/WebAdmin.html?param1=xxx&locale=fr&param2=yyy"); result = testServlet.getLocaleStringFromReferer(mockRequest); assertEquals("The result should be 'fr'", "fr", result); } }
package org.openecard.richclient.gui.manage.addon; import java.io.IOException; import java.util.List; import org.openecard.addon.AddonPropertiesException; import org.openecard.addon.manifest.ConfigurationEntry; import org.openecard.addon.manifest.EnumEntry; import org.openecard.addon.manifest.EnumListEntry; import org.openecard.addon.manifest.FileEntry; import org.openecard.addon.manifest.FileListEntry; import org.openecard.addon.manifest.ScalarEntry; import org.openecard.addon.manifest.ScalarEntryType; import org.openecard.addon.manifest.ScalarListEntry; import org.openecard.richclient.gui.manage.SettingsFactory.Settings; import org.openecard.richclient.gui.manage.SettingsGroup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * SettingsGroup that can be used as default. * For every ConfigurationEntry in the given AddonSpecification an according item will be added. * * @author Dirk Petrautzki <dirk.petrautzki@hs-coburg.de> * @author Hans-Martin Haase <hans-martin.haase@ecsec.de> */ public class DefaultSettingsGroup extends SettingsGroup { private static final long serialVersionUID = 1L; private static final Logger logger = LoggerFactory.getLogger(DefaultSettingsGroup.class); private static final String LANGUAGE_CODE = System.getProperty("user.language"); public DefaultSettingsGroup(String title, Settings settings, List<ConfigurationEntry> configEntries) { super(title, settings); for (ConfigurationEntry entry : configEntries) { String name = entry.getLocalizedName(LANGUAGE_CODE); String description = entry.getLocalizedDescription(LANGUAGE_CODE); // match entry types with class, else the type hierarchy is implicit in the if an that is a bad thing if (ScalarEntry.class.equals(entry.getClass())) { ScalarEntry scalarEntry = (ScalarEntry) entry; if (scalarEntry.getType().equals(ScalarEntryType.STRING.name())) { addInputItem(name, description, entry.getKey()); } else if (scalarEntry.getType().equals(ScalarEntryType.BOOLEAN.name())) { addBoolItem(name, description, entry.getKey()); } else if (scalarEntry.getType().equals(ScalarEntryType.BIGDECIMAL.name())) { addScalarEntryTypNumber(name, description, scalarEntry.getKey(), scalarEntry.getType()); } else if (scalarEntry.getType().equals(ScalarEntryType.BIGINTEGER.name())) { addScalarEntryTypNumber(name, description, scalarEntry.getKey(), scalarEntry.getType()); } else { logger.error("Untreated ScalarEntry type: {}", scalarEntry.getType()); } } else if (ScalarListEntry.class.equals(entry.getClass())) { // TODO should not allow boolean type addScalarListItem(name, description, entry.getKey()); } else if (EnumEntry.class.equals(entry.getClass())) { EnumEntry enumEntry = (EnumEntry) entry; List<String> values = enumEntry.getValues(); addSingleSelectionItem(name, description, enumEntry.getKey(), values); } else if (EnumListEntry.class.equals(entry.getClass())) { EnumListEntry enumEntry = (EnumListEntry) entry; List<String> values = enumEntry.getValues(); addMultiSelectionItem(name, description, entry.getKey(), values); } else if (FileEntry.class.equals(entry.getClass())) { FileEntry fEntry = (FileEntry) entry; addFileEntry(name, description, entry.getKey(), fEntry.getFileType(), fEntry.isRequiredBeforeAction()); } else if (FileListEntry.class.equals(entry.getClass())) { FileListEntry fEntry = (FileListEntry) entry; addFileListEntry(name, description, entry.getKey(), fEntry.getFileType(), fEntry.isRequiredBeforeAction()); } else { logger.error("Untreated entry type: {}", entry.getClass().getName()); } } } @Override protected void saveProperties() throws IOException, SecurityException, AddonPropertiesException { super.saveProperties(); } }
package io.github.aquerr.eaglefactions.common.storage.file.hocon; import com.google.common.reflect.TypeToken; import io.github.aquerr.eaglefactions.api.entities.*; import io.github.aquerr.eaglefactions.common.entities.FactionChestImpl; import io.github.aquerr.eaglefactions.common.entities.FactionImpl; import io.github.aquerr.eaglefactions.common.entities.FactionPlayerImpl; import ninja.leaping.configurate.ConfigurationNode; import ninja.leaping.configurate.hocon.HoconConfigurationLoader; import ninja.leaping.configurate.objectmapping.ObjectMappingException; import org.spongepowered.api.text.Text; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.time.Instant; import java.util.*; import java.util.stream.Collectors; public class ConfigurateHelper { public static boolean putFactionInNode(final ConfigurationNode configNode, final Faction faction) { try { configNode.getNode(faction.getName(), "tag").setValue(TypeToken.of(Text.class), faction.getTag()); configNode.getNode(faction.getName(), "leader").setValue(faction.getLeader().toString()); configNode.getNode(faction.getName(), "description").setValue(faction.getDescription()); configNode.getNode(faction.getName(), "motd").setValue(faction.getMessageOfTheDay()); configNode.getNode(faction.getName(), "officers").setValue(new TypeToken<ArrayList<UUID>>() {}, new ArrayList<>(faction.getOfficers())); configNode.getNode(faction.getName(), "members").setValue(new TypeToken<ArrayList<UUID>>() {}, new ArrayList<>(faction.getMembers())); configNode.getNode(faction.getName(), "recruits").setValue(new TypeToken<ArrayList<UUID>>() {}, new ArrayList<>(faction.getRecruits())); configNode.getNode(faction.getName(), "truces").setValue(faction.getTruces()); configNode.getNode(faction.getName(), "alliances").setValue(faction.getAlliances()); configNode.getNode(faction.getName(), "enemies").setValue(faction.getEnemies()); configNode.getNode(faction.getName(), "claims").setValue(faction.getClaims().stream().map(Claim::toString).collect(Collectors.toList())); configNode.getNode(faction.getName(), "last_online").setValue(faction.getLastOnline().toString()); configNode.getNode(faction.getName(), "perms").setValue(faction.getPerms()); configNode.getNode(faction.getName(), "chest").setValue(new TypeToken<List<FactionChest.SlotItem>>(){}, faction.getChest().getItems()); configNode.getNode(faction.getName(), "isPublic").setValue(faction.isPublic()); if(faction.getHome() == null) { configNode.getNode(faction.getName(), "home").setValue(faction.getHome()); } else { configNode.getNode(faction.getName(), "home").setValue(faction.getHome().getWorldUUID().toString() + '|' + faction.getHome().getBlockPosition().toString()); } return true; } catch(final Exception exception) { exception.printStackTrace(); return false; } } public static boolean putPlayerInNode(final ConfigurationNode configNode, final FactionPlayer factionPlayer) { try { configNode.getNode("faction").setValue(factionPlayer.getFactionName().orElse("")); configNode.getNode("faction-member-type").setValue(factionPlayer.getFactionRole().isPresent() ? factionPlayer.getFactionRole().get().toString() : ""); configNode.getNode("name").setValue(factionPlayer.getName()); configNode.getNode("power").setValue(factionPlayer.getPower()); configNode.getNode("maxpower").setValue(factionPlayer.getMaxPower()); configNode.getNode("death-in-warzone").setValue(factionPlayer.diedInWarZone()); return true; } catch (Exception exception) { exception.printStackTrace(); return false; } } public static List<Faction> getFactionsFromNode(final ConfigurationNode configNode) { final List<Faction> factions = new ArrayList<>(); try { final Set<Object> keySet = configNode.getChildrenMap().keySet(); for(Object object : keySet) { if(object instanceof String) { final Faction faction = getFactionFromNode(configNode.getNode(object)); factions.add(faction); } } } catch (ObjectMappingException e) { e.printStackTrace(); } return factions; } public static Faction getFactionFromNode(final ConfigurationNode configNode) throws ObjectMappingException { final String factionName = String.valueOf(configNode.getKey()); final Text tag = configNode.getNode("tag").getValue(TypeToken.of(Text.class)); final String description = configNode.getNode("description").getString(); final String messageOfTheDay = configNode.getNode("motd").getString(); final UUID leader = configNode.getNode("leader").getValue(TypeToken.of(UUID.class), new UUID(0,0)); final FactionHome home = FactionHome.from(String.valueOf(configNode.getNode("home").getValue(""))); final Set<UUID> officers = configNode.getNode("officers").getValue(new TypeToken<Set<UUID>>(){}, new HashSet<>()); final Set<UUID> members = configNode.getNode("members").getValue(new TypeToken<Set<UUID>>(){}, new HashSet<>()); final Set<UUID> recruits = configNode.getNode("recruits").getValue(new TypeToken<Set<UUID>>(){}, new HashSet<>()); final Set<String> alliances = new HashSet<>(configNode.getNode("alliances").getList(TypeToken.of(String.class), new ArrayList<>())); final Set<String> enemies = new HashSet<>(configNode.getNode("enemies").getList(TypeToken.of(String.class), new ArrayList<>())); final Set<Claim> claims = configNode.getNode("claims").getList(TypeToken.of(String.class), new ArrayList<>()).stream().map(Claim::valueOf).collect(Collectors.toSet()); final Instant lastOnline = configNode.getNode("last_online").getValue() != null ? Instant.parse(configNode.getNode("last_online").getString()) : Instant.now(); final Map<FactionMemberType, Map<FactionPermType, Boolean>> perms = getFactionPermsFromNode(configNode.getNode("perms")); List<FactionChest.SlotItem> slotItems = configNode.getNode("chest").getValue(new TypeToken<List<FactionChest.SlotItem>>() {}); FactionChest chest; if (slotItems == null) chest = new FactionChestImpl(factionName); else chest = new FactionChestImpl(factionName, slotItems); final boolean isPublic = configNode.getNode("isPublic").getBoolean(false); return FactionImpl.builder(factionName, tag, leader) .setDescription(description) .setMessageOfTheDay(messageOfTheDay) .setHome(home) .setOfficers(officers) .setMembers(members) .setRecruits(recruits) .setAlliances(alliances) .setEnemies(enemies) .setClaims(claims) .setLastOnline(lastOnline) .setPerms(perms) .setChest(chest) .setIsPublic(isPublic) .build(); } public static FactionPlayer getPlayerFromFile(final File file) { HoconConfigurationLoader playerConfigLoader = HoconConfigurationLoader.builder().setFile(file).build(); try { ConfigurationNode playerNode = playerConfigLoader.load(); String playerName = playerNode.getNode("name").getString(""); UUID playerUUID; try { playerUUID = UUID.fromString(file.getName().substring(0, file.getName().indexOf('.'))); } catch(Exception exception) { exception.printStackTrace(); Files.delete(file.toPath()); return null; } String factionName = playerNode.getNode("faction").getString(""); String factionMemberTypeString = playerNode.getNode("faction-member-type").getString(""); float power = playerNode.getNode("power").getFloat(0.0f); float maxpower = playerNode.getNode("maxpower").getFloat(0.0f); boolean diedInWarZone = playerNode.getNode("death-in-warzone").getBoolean(false); FactionMemberType factionMemberType = null; if(!factionMemberTypeString.equals("")) factionMemberType = FactionMemberType.valueOf(factionMemberTypeString); return new FactionPlayerImpl(playerName, playerUUID, factionName, power, maxpower, factionMemberType, diedInWarZone); } catch(IOException e) { e.printStackTrace(); return null; } } public static Map<FactionMemberType, Map<FactionPermType, Boolean>> getFactionPermsFromNode(final ConfigurationNode factionNode) { Map<FactionMemberType, Map<FactionPermType, Boolean>> flagMap = new LinkedHashMap<>(); Map<FactionPermType, Boolean> leaderMap = new LinkedHashMap<>(); Map<FactionPermType, Boolean> officerMap = new LinkedHashMap<>(); Map<FactionPermType, Boolean> membersMap = new LinkedHashMap<>(); Map<FactionPermType, Boolean> recruitMap = new LinkedHashMap<>(); Map<FactionPermType, Boolean> allyMap = new LinkedHashMap<>(); //Get leader perms boolean leaderUSE = factionNode.getNode("LEADER", "USE").getBoolean(true); boolean leaderPLACE = factionNode.getNode("LEADER", "PLACE").getBoolean(true); boolean leaderDESTROY = factionNode.getNode("LEADER", "DESTROY").getBoolean(true); boolean leaderCLAIM = factionNode.getNode("LEADER", "CLAIM").getBoolean(true); boolean leaderATTACK = factionNode.getNode("LEADER", "ATTACK").getBoolean(true); boolean leaderINVITE = factionNode.getNode("LEADER", "INVITE").getBoolean(true); //Get officer perms boolean officerUSE = factionNode.getNode("OFFICER", "USE").getBoolean(true); boolean officerPLACE = factionNode.getNode("OFFICER", "PLACE").getBoolean(true); boolean officerDESTROY = factionNode.getNode("OFFICER", "DESTROY").getBoolean(true); boolean officerCLAIM = factionNode.getNode("OFFICER", "CLAIM").getBoolean(true); boolean officerATTACK = factionNode.getNode("LEADER", "ATTACK").getBoolean(true); boolean officerINVITE = factionNode.getNode("OFFICER", "INVITE").getBoolean(true); //Get member perms boolean memberUSE = factionNode.getNode("MEMBER", "USE").getBoolean(true); boolean memberPLACE = factionNode.getNode("MEMBER", "PLACE").getBoolean(true); boolean memberDESTROY = factionNode.getNode("MEMBER", "DESTROY").getBoolean(true); boolean memberCLAIM = factionNode.getNode("MEMBER", "CLAIM").getBoolean(false); boolean memberATTACK = factionNode.getNode("LEADER", "ATTACK").getBoolean(false); boolean memberINVITE = factionNode.getNode("MEMBER", "INVITE").getBoolean(true); //Get recruit perms boolean recruitUSE = factionNode.getNode("RECRUIT", "USE").getBoolean(true); boolean recruitPLACE = factionNode.getNode("RECRUIT", "PLACE").getBoolean(true); boolean recruitDESTROY = factionNode.getNode("RECRUIT", "DESTROY").getBoolean(true); boolean recruitCLAIM = factionNode.getNode("RECRUIT", "CLAIM").getBoolean(false); boolean recruitATTACK = factionNode.getNode("RECRUIT", "ATTACK").getBoolean(false); boolean recruitINVITE = factionNode.getNode("RECRUIT", "INVITE").getBoolean(false); //Get ally perms boolean allyUSE = factionNode.getNode("ALLY", "USE").getBoolean(true); boolean allyPLACE = factionNode.getNode( "ALLY", "PLACE").getBoolean(false); boolean allyDESTROY = factionNode.getNode("ALLY", "DESTROY").getBoolean(false); leaderMap.put(FactionPermType.USE, leaderUSE); leaderMap.put(FactionPermType.PLACE, leaderPLACE); leaderMap.put(FactionPermType.DESTROY, leaderDESTROY); leaderMap.put(FactionPermType.CLAIM, leaderCLAIM); leaderMap.put(FactionPermType.ATTACK, leaderATTACK); leaderMap.put(FactionPermType.INVITE, leaderINVITE); officerMap.put(FactionPermType.USE, officerUSE); officerMap.put(FactionPermType.PLACE, officerPLACE); officerMap.put(FactionPermType.DESTROY, officerDESTROY); officerMap.put(FactionPermType.CLAIM, officerCLAIM); officerMap.put(FactionPermType.ATTACK, officerATTACK); officerMap.put(FactionPermType.INVITE, officerINVITE); membersMap.put(FactionPermType.USE, memberUSE); membersMap.put(FactionPermType.PLACE, memberPLACE); membersMap.put(FactionPermType.DESTROY, memberDESTROY); membersMap.put(FactionPermType.CLAIM, memberCLAIM); membersMap.put(FactionPermType.ATTACK, memberATTACK); membersMap.put(FactionPermType.INVITE, memberINVITE); recruitMap.put(FactionPermType.USE, recruitUSE); recruitMap.put(FactionPermType.PLACE, recruitPLACE); recruitMap.put(FactionPermType.DESTROY, recruitDESTROY); recruitMap.put(FactionPermType.CLAIM, recruitCLAIM); recruitMap.put(FactionPermType.ATTACK, recruitATTACK); recruitMap.put(FactionPermType.INVITE, recruitINVITE); allyMap.put(FactionPermType.USE, allyUSE); allyMap.put(FactionPermType.PLACE, allyPLACE); allyMap.put(FactionPermType.DESTROY, allyDESTROY); flagMap.put(FactionMemberType.LEADER, leaderMap); flagMap.put(FactionMemberType.OFFICER, officerMap); flagMap.put(FactionMemberType.MEMBER, membersMap); flagMap.put(FactionMemberType.RECRUIT, recruitMap); flagMap.put(FactionMemberType.ALLY, allyMap); return flagMap; } }
package namewebserver; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLDecoder; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import org.apache.commons.lang3.StringUtils; import org.eclipse.jetty.util.StringUtil; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import qora.account.Account; import qora.block.Block; import qora.crypto.Crypto; import qora.naming.Name; import qora.transaction.Transaction; import qora.web.BlogBlackWhiteList; import qora.web.HTMLSearchResult; import qora.web.Profile; import qora.web.blog.BlogEntry; import settings.Settings; import utils.AccountBalanceComparator; import utils.BlogUtils; import utils.GZIP; import utils.JSonWriter; import utils.NameUtils; import utils.NameUtils.NameResult; import utils.Pair; import utils.PebbleHelper; import utils.Qorakeys; import utils.Triplet; import api.ATResource; import api.AddressesResource; import api.ApiErrorFactory; import api.BlocksResource; import api.BlogPostResource; import api.NameSalesResource; import api.NamesResource; import api.TransactionsResource; import com.mitchellbosecke.pebble.error.PebbleException; import controller.Controller; import database.DBSet; import database.NameMap; @Path("/") public class NamesWebResource { @Context HttpServletRequest request; @GET public Response Default() { return handleDefault(); } public Response handleDefault() { try { String searchValue = request.getParameter("search"); PebbleHelper pebbleHelper = PebbleHelper .getPebbleHelper("web/index.mini.html"); if (searchValue == null) { return Response.ok( PebbleHelper.getPebbleHelper("web/index.html") .evaluate(), "text/html; charset=utf-8") .build(); } else { List<Pair<String, String>> searchResults; searchResults = NameUtils.getWebsitesByValue(searchValue); List<HTMLSearchResult> results = generateHTMLSearchresults(searchResults); pebbleHelper.getContextMap().put("searchresults", results); } return Response.ok(pebbleHelper.evaluate(), "text/html; charset=utf-8").build(); } catch (Throwable e) { e.printStackTrace(); return error404(request); } } public List<HTMLSearchResult> generateHTMLSearchresults( List<Pair<String, String>> searchResults) throws IOException, PebbleException { List<HTMLSearchResult> results = new ArrayList<>(); for (Pair<String, String> result : searchResults) { String name = result.getA(); String websitecontent = result.getB(); Document htmlDoc = Jsoup.parse(websitecontent); String title = selectTitleOpt(htmlDoc); title = title == null ? "" : title; String description = selectDescriptionOpt(htmlDoc); description = description == null ? "" : description; description = StringUtils.abbreviate(description, 150); results.add(new HTMLSearchResult(title, description, name, "/" + name, "/" + name, "/namepairs:" + name)); } return results; } @Path("blogsearch.html") @GET public Response doBlogSearch() { String searchValue = request.getParameter("search"); try { PebbleHelper pebbleHelper = PebbleHelper .getPebbleHelper("web/index.mini.html"); if (StringUtil.isBlank(searchValue)) { return Response.ok(pebbleHelper.evaluate(), "text/html; charset=utf-8").build(); } List<HTMLSearchResult> results = handleBlogSearch(searchValue); pebbleHelper.getContextMap().put("searchresults", results); return Response.ok(pebbleHelper.evaluate(), "text/html; charset=utf-8").build(); } catch (Throwable e) { e.printStackTrace(); return error404(request); } } @Path("blogdirectory.html") @GET public Response doBlogdirectory() { try { PebbleHelper pebbleHelper = PebbleHelper .getPebbleHelper("web/index.mini.html"); List<HTMLSearchResult> results = handleBlogSearch(null); pebbleHelper.getContextMap().put("searchresults", results); return Response.ok(pebbleHelper.evaluate(), "text/html; charset=utf-8").build(); } catch (Throwable e) { e.printStackTrace(); return error404(request); } } @Path("settingssave.html") @GET public Response saveProfileSettings() { try { PebbleHelper pebbleHelper = PebbleHelper .getPebbleHelper("web/settings.html"); Map<String, String[]> parameterMap = request.getParameterMap(); String profileName = request.getParameter("profilename"); if (!isCompleteSubmit(parameterMap)) { return error404(request); } Name name = null; name = Controller.getInstance().getName(profileName); if (name == null) { return error404(request); } boolean blogenable = Boolean.valueOf(request .getParameter(Qorakeys.BLOGENABLE.toString())); boolean profileenable = Boolean.valueOf(request .getParameter(Qorakeys.PROFILEENABLE.toString())); String titleOpt = request.getParameter(Qorakeys.BLOGTITLE .toString()); titleOpt = decodeIfNotNull(titleOpt); String blogDescrOpt = request.getParameter(Qorakeys.BLOGDESCRIPTION .toString()); blogDescrOpt = decodeIfNotNull(blogDescrOpt); String profileAvatarOpt = request .getParameter(Qorakeys.PROFILEAVATAR.toString()); profileAvatarOpt = decodeIfNotNull(profileAvatarOpt); Profile profile = Profile.getProfile(name); profile.saveAvatarTitle(profileAvatarOpt); profile.saveBlogDescription(blogDescrOpt); profile.saveBlogTitle(titleOpt); profile.setBlogEnabled(blogenable); profile.setProfileEnabled(profileenable); try { pebbleHelper.getContextMap().put("result","<center><div class=\"alert alert-success\" role=\"alert\">Settings saved<br>" + profile.saveProfile() + "</div></center>"); } catch (WebApplicationException e) { pebbleHelper.getContextMap().put("result","<center><div class=\"alert alert-danger\" role=\"alert\">Settings not saved<br>" + e.getResponse().getEntity() + "</div></center>"); } pebbleHelper.getContextMap().put("profile", profile); pebbleHelper.getContextMap().put("name", name); List<Name> namesAsList = Controller.getInstance().getNamesAsList(); pebbleHelper.getContextMap().put("names", namesAsList); return Response.ok(pebbleHelper.evaluate(), "text/html; charset=utf-8").build(); } catch (Throwable e) { e.printStackTrace(); return error404(request); } } @Path("settings.html") @GET public Response doProfileSettings() { try { PebbleHelper pebbleHelper = PebbleHelper .getPebbleHelper("web/settings.html"); String profileName = request.getParameter("profilename"); List<Name> namesAsList = Controller.getInstance().getNamesAsList(); pebbleHelper.getContextMap().put("names", namesAsList); Name name = null; if (profileName != null) { name = Controller.getInstance().getName(profileName); } if (namesAsList.size() > 0) { if (name == null) { name = namesAsList.get(0); } Profile profile = Profile.getProfile(name); pebbleHelper.getContextMap().put("profile", profile); pebbleHelper.getContextMap().put("name", name); } else { // no name no chance } return Response.ok(pebbleHelper.evaluate(), "text/html; charset=utf-8").build(); } catch (Throwable e) { e.printStackTrace(); return error404(request); } } public String decodeIfNotNull(String parameter) throws UnsupportedEncodingException { return parameter != null ? URLDecoder.decode(parameter, "UTF-8") : null; } private boolean isCompleteSubmit(Map<String, String[]> parameterMap) { if (!parameterMap.containsKey("profilename")) { return false; } List<Qorakeys> list = Arrays.asList(Qorakeys.BLOGENABLE, Qorakeys.PROFILEENABLE, Qorakeys.BLOGTITLE, Qorakeys.PROFILEAVATAR, Qorakeys.BLOGDESCRIPTION); boolean result = true; for (Qorakeys qorakey : list) { if (!parameterMap.containsKey(qorakey.toString())) { result = false; break; } } return result; } @Path("webdirectory.html") @GET public Response doWebdirectory() { try { PebbleHelper pebbleHelper = PebbleHelper .getPebbleHelper("web/index.mini.html"); List<Pair<String, String>> websitesByValue = NameUtils .getWebsitesByValue(null); List<HTMLSearchResult> results = generateHTMLSearchresults(websitesByValue); pebbleHelper.getContextMap().put("searchresults", results); return Response.ok(pebbleHelper.evaluate(), "text/html; charset=utf-8").build(); } catch (Throwable e) { e.printStackTrace(); return error404(request); } } private List<HTMLSearchResult> handleBlogSearch(String blogSearchOpt) { List<HTMLSearchResult> results = new ArrayList<>(); List<Triplet<String, String, String>> allEnabledBlogs = BlogUtils .getEnabledBlogs(blogSearchOpt); for (Triplet<String, String, String> triplet : allEnabledBlogs) { String name = triplet.getA(); String title = triplet.getB(); String description = triplet.getC(); description = StringUtils.abbreviate(description, 150); results.add(new HTMLSearchResult(title, description, name, "/blog.html?blogname=" + name, "/blog.html?blogname=" + name, "/namepairs:" + name)); } return results; } public static String selectTitleOpt(Document htmlDoc) { String title = selectFirstElementOpt(htmlDoc, "title"); return title; } public static String selectFirstElementOpt(Document htmlDoc, String tag) { Elements titleElements = htmlDoc.select(tag); String title = null; if (titleElements.size() > 0) { title = titleElements.get(0).text(); } return title; } public static String selectDescriptionOpt(Document htmlDoc) { String result = ""; Elements descriptions = htmlDoc.select("meta[name=\"description\"]"); if (descriptions.size() > 0) { Element descr = descriptions.get(0); if (descr.hasAttr("content")) { result = descr.attr("content"); } } return result; } @Path("index.html") @GET public Response handleIndex() { return handleDefault(); } @Path("favicon.ico") @GET public Response favicon() { File file = new File("web/favicon.ico"); if (file.exists()) { return Response.ok(file, "image/vnd.microsoft.icon").build(); } else { return error404(request); } } @SuppressWarnings("unchecked") @Path("/API.html") @GET public Response handleAPICall() { try { PebbleHelper pebbleHelper = PebbleHelper .getPebbleHelper("web/apianswer.html"); // EXAMPLE POST/GET/DELETE String type = request.getParameter("type"); // EXAMPLE /names/key/MyName String url = request.getParameter("apiurl"); String okmsg = request.getParameter("okmsg"); String errormsg = request.getParameter("errormsg"); if (StringUtils.isBlank(type) || (!type.equalsIgnoreCase("get") && !type.equalsIgnoreCase("post") && !type .equalsIgnoreCase("delete"))) { pebbleHelper.getContextMap().put("title", "An Api error occured"); pebbleHelper .getContextMap() .put("apicall", "You need a type parameter with value GET/POST or DELETE "); return Response.ok(pebbleHelper.evaluate(), "text/html; charset=utf-8").build(); } if (StringUtils.isBlank(url)) { pebbleHelper.getContextMap().put("title", "An Api error occured"); pebbleHelper.getContextMap().put("apicall", "You need to provide an apiurl parameter"); return Response.ok(pebbleHelper.evaluate(), "text/html; charset=utf-8").build(); } url = url.startsWith("/") ? url.substring(1) : url; Map<String, String[]> parameterMap = new HashMap<String, String[]>( request.getParameterMap()); parameterMap.remove("type"); parameterMap.remove("apiurl"); parameterMap.remove("okmsg"); parameterMap.remove("errormsg"); Set<String> keySet = parameterMap.keySet(); JSONObject json = new JSONObject(); for (String key : keySet) { String[] value = parameterMap.get(key); json.put(key, value[0]); } try { // CREATE CONNECTION URL urlToCall = new URL("http://127.0.0.1:" + Settings.getInstance().getRpcPort() + "/" + url); HttpURLConnection connection = (HttpURLConnection) urlToCall .openConnection(); // EXECUTE connection.setRequestMethod(type.toUpperCase()); if (type.equalsIgnoreCase("POST")) { connection.setDoOutput(true); connection.getOutputStream().write( json.toJSONString().getBytes("UTF-8")); connection.getOutputStream().flush(); connection.getOutputStream().close(); } // READ RESULT InputStream stream; if (connection.getResponseCode() == 400) { stream = connection.getErrorStream(); } else { stream = connection.getInputStream(); } InputStreamReader isReader = new InputStreamReader(stream, "UTF-8"); BufferedReader br = new BufferedReader(isReader); String result = br.readLine(); if (result.contains("message") && result.contains("error")) { if (StringUtils.isNotBlank(errormsg)) { pebbleHelper.getContextMap().put("customtext", "<font color=red>" + errormsg + "</font>"); } pebbleHelper.getContextMap().put("title", "An Api error occured"); pebbleHelper.getContextMap().put( "apicall", "apicall: " + type.toUpperCase() + " " + url + (json.size() > 0 ? json.toJSONString() : "")); pebbleHelper.getContextMap().put("errormessage", "Result:" + result); return Response.ok(pebbleHelper.evaluate(), "text/html; charset=utf-8").build(); } else { if (StringUtils.isNotBlank(okmsg)) { pebbleHelper.getContextMap().put("customtext", "<font color=green>" + okmsg + "</font>"); } pebbleHelper.getContextMap().put("title", "The API Call was successful"); pebbleHelper.getContextMap().put( "apicall", "Submitted Api call: " + type.toUpperCase() + " " + url + (json.size() > 0 ? json.toJSONString() : "")); pebbleHelper.getContextMap().put("errormessage", "Result:" + result); return Response.ok(pebbleHelper.evaluate(), "text/html; charset=utf-8").build(); } } catch (IOException e) { e.printStackTrace(); String additionalHelp = ""; if (e instanceof FileNotFoundException) { additionalHelp = "The apicall with the following apiurl is not existing: "; } pebbleHelper.getContextMap().put("title", "An Api error occured"); pebbleHelper.getContextMap().put( "apicall", "You tried to submit the following apicall: " + type.toUpperCase() + " " + url + (json.size() > 0 ? json.toJSONString() : "")); pebbleHelper.getContextMap().put("errormessage", additionalHelp + e.getMessage()); return Response.ok(pebbleHelper.evaluate(), "text/html; charset=utf-8").build(); } } catch (Throwable e) { e.printStackTrace(); } return error404(request); } @Path("img/qora.png") @GET public Response qorapng() { File file = new File("web/img/qora.png"); if (file.exists()) { return Response.ok(file, "image/png").build(); } else { return error404(request); } } @Path("img/logo_header.png") @GET public Response logo_header() { File file = new File("web/img/logo_header.png"); if (file.exists()) { return Response.ok(file, "image/png").build(); } else { return error404(request); } } @Path("img/qora-user.png") @GET public Response qorauserpng() { File file = new File("web/img/qora-user.png"); if (file.exists()) { return Response.ok(file, "image/png").build(); } else { return error404(request); } } @Path("libs/css/style.css") @GET public Response style() { File file = new File("web/libs/css/style.css"); if (file.exists()) { return Response.ok(file, "text/css").build(); } else { return error404(request); } } @Path("libs/css/sidebar.css") @GET public Response sidebarcss() { File file = new File("web/libs/css/sidebar.css"); if (file.exists()) { return Response.ok(file, "text/css").build(); } else { return error404(request); } } @Path("libs/css/timeline.css") @GET public Response timelinecss() { File file = new File("web/libs/css/timeline.css"); if (file.exists()) { return Response.ok(file, "text/css").build(); } else { return error404(request); } } @Path("libs/js/sidebar.js") @GET public Response sidebarjs() { File file = new File("web/libs/js/sidebar.js"); if (file.exists()) { return Response.ok(file, "text/javascript").build(); } else { return error404(request); } } @SuppressWarnings("unchecked") @Path("postblog.html") @GET public Response postBlog() { try { PebbleHelper pebbleHelper = PebbleHelper .getPebbleHelper("web/postblog.html"); pebbleHelper.getContextMap().put("errormessage", ""); pebbleHelper.getContextMap().put("font", ""); pebbleHelper.getContextMap().put("content", ""); pebbleHelper.getContextMap().put("option", ""); pebbleHelper.getContextMap().put("oldtitle", ""); pebbleHelper.getContextMap().put("oldcreator", ""); pebbleHelper.getContextMap().put("oldcontent", ""); pebbleHelper.getContextMap().put("oldfee", ""); pebbleHelper.getContextMap().put("preview", ""); String title = request.getParameter(BlogPostResource.TITLE_KEY); String creator = request.getParameter("creator"); String contentparam = request.getParameter("content"); String fee = request.getParameter("fee"); String preview = request.getParameter("preview"); String blogname = request .getParameter(BlogPostResource.BLOGNAME_KEY); BlogBlackWhiteList blogBlackWhiteList = BlogBlackWhiteList .getBlogBlackWhiteList(blogname); Pair<List<Account>, List<Name>> ownAllowedElements = blogBlackWhiteList .getOwnAllowedElements(true); List<Account> resultingAccounts = new ArrayList<Account>( ownAllowedElements.getA()); List<Name> resultingNames = ownAllowedElements.getB(); Collections.sort(resultingAccounts, new AccountBalanceComparator()); Collections.reverse(resultingAccounts); String accountStrings = ""; for (Name name : resultingNames) { accountStrings += "<option value=" + name.getName() + ">" + name.getNameBalanceString() + "</option>"; } for (Account account : resultingAccounts) { accountStrings += "<option value=" + account.getAddress() + ">" + account + "</option>"; } // are we allowed to post if (resultingNames.size() == 0 && resultingAccounts.size() == 0) { pebbleHelper .getContextMap() .put("errormessage", "<font color=red>You can't post to this blog! None of your accounts has balance or the blogowner did not allow your accounts to post!</font><br>"); } pebbleHelper.getContextMap().put("option", accountStrings); if (StringUtil.isNotBlank(creator) && StringUtil.isNotBlank(contentparam) && StringUtil.isNotBlank(fee)) { JSONObject json = new JSONObject(); title = URLDecoder.decode(title, "UTF-8"); contentparam = URLDecoder.decode(contentparam, "UTF-8"); Pair<Account, NameResult> nameToAdress = NameUtils .nameToAdress(creator); String authorOpt = null; if (nameToAdress.getB() == NameResult.OK) { authorOpt = creator; json.put(BlogPostResource.AUTHOR, authorOpt); json.put("creator", nameToAdress.getA().getAddress()); } else { json.put("creator", creator); } json.put("fee", fee); json.put("title", title); json.put("body", contentparam); if (StringUtils.isNotBlank(preview)) { pebbleHelper.getContextMap().put("oldtitle", title); pebbleHelper.getContextMap().put("oldfee", fee); pebbleHelper.getContextMap().put("oldcontent", contentparam.replaceAll("\\n", "\\\\n")); pebbleHelper.getContextMap().put("oldcreator", creator); BlogEntry entry = new BlogEntry(title, contentparam, authorOpt, new Date().getTime(), creator); pebbleHelper.getContextMap().put("blogposts", Arrays.asList(entry)); return Response.ok(pebbleHelper.evaluate(), "text/html; charset=utf-8").build(); } try { String result = new BlogPostResource().addBlogEntry( json.toJSONString(), blogname); pebbleHelper .getContextMap() .put("font", "<div class=\"alert alert-success\" role=\"alert\">Your post was successful<br>" + result + "</div>"); } catch (WebApplicationException e) { pebbleHelper.getContextMap().put("oldtitle", title); pebbleHelper.getContextMap().put("oldfee", fee); pebbleHelper.getContextMap().put("oldcontent", contentparam.replaceAll("\\n", "\\\\n")); pebbleHelper.getContextMap().put("oldcreator", creator); pebbleHelper .getContextMap() .put("font", "<div class=\"alert alert-danger\" role=\"alert\">Your post was NOT successful<br>" + e.getResponse().getEntity() + "</div>"); } } return Response.ok(pebbleHelper.evaluate(), "text/html; charset=utf-8").build(); } catch (Throwable e) { e.printStackTrace(); return error404(request); } } @Path("blog.html") @GET public Response getBlog() { try { String blogname = request .getParameter(BlogPostResource.BLOGNAME_KEY); PebbleHelper pebbleHelper = PebbleHelper .getPebbleHelper("web/blog.html"); pebbleHelper.getContextMap().put("postblogurl", "postblog.html"); NameMap nameMap = DBSet.getInstance().getNameMap(); if (blogname != null) { if (!nameMap.contains(blogname)) { return Response.ok( PebbleHelper.getPebbleHelper( "web/blogdisabled.html").evaluate(), "text/html; charset=utf-8").build(); } Name name = nameMap.get(blogname); Profile profile = Profile.getProfile(name); if (!profile.isProfileEnabled() || !profile.isBlogEnabled()) { pebbleHelper = PebbleHelper .getPebbleHelper("web/blogdisabled.html"); if (Controller.getInstance().getAccountByAddress( name.getOwner().getAddress()) != null) { String resultcall = "/settings.html?profilename=" + blogname; String template = readFile("web/blogenabletemplate", StandardCharsets.UTF_8); template = template.replace("!TEXT!", "here"); template = template.replace("!LINK!", resultcall); pebbleHelper.getContextMap().put( "enableblog", "You can activate the blog by clicking " + template); } return Response.ok(pebbleHelper.evaluate(), "text/html; charset=utf-8").build(); } pebbleHelper.getContextMap().put("postblogurl", "postblog.html?blogname=" + blogname); } List<BlogEntry> blogPosts = BlogUtils.getBlogPosts(blogname); pebbleHelper.getContextMap().put("blogposts", blogPosts); return Response.ok(pebbleHelper.evaluate(), "text/html; charset=utf-8").build(); } catch (Throwable e) { e.printStackTrace(); return error404(request); } } // public String getHTMLForBlogPosts(List<BlogEntry> blogPosts) { // String results = "<br>"; // String entryTemplate = "<li><div class=\"timeline-badge primary\"><a>" // "<i class=\"glyphicon glyphicon-record\" rel=\"tooltip\" title=\"POST TIME\" id=\"\">" // + "</i></a></div>" // + "<div class=\"timeline-panel\"><div class=\"timeline-heading\">" // + "<div class=\"media\"><div class=\"media-left media-middle\">" // "<a href=\"#\"><img class=\"media-object\" src=\"img/qora-user.png\" alt=\"\"></a></div>" // + "<div class=\"media-body\">" // + "<h6 class=\"media-heading\"><b>Name</b></h6>Time</div></div>" // + "</div>" // "<div class=\"timeline-body\"><p class=\"post-header\"><b>TITLE</b></p><p class=\"post-content\">CONTENT</p></div></div></li>"; // for (BlogEntry blogentry : blogPosts) { // String converted = entryTemplate; // String body = blogentry.getDescription(); // String nameOpt = blogentry.getNameOpt(); // converted = converted // .replaceAll("Name", blogentry.getNameOrCreator()); // converted = converted.replaceAll("TITLE", blogentry.getTitleOpt()); // converted = converted.replaceAll("CONTENT", body); // converted = converted.replaceAll("Time", // blogentry.getCreationTime()); // results += converted; // return results; @Path("libs/jquery/jquery.{version}.js") @GET public Response jquery(@PathParam("version") String version) { File file; if (version.equals("1")) { file = new File("web/libs/jquery/jquery-1.11.3.min.js"); } else if (version.equals("2")) { file = new File("web/libs/jquery/jquery-2.1.4.min.js"); } else { file = new File("web/libs/jquery/jquery-2.1.4.min.js"); } if (file.exists()) { return Response.ok(file, "text/javascript; charset=utf-8").build(); } else { return error404(request); } } @Path("libs/angular/angular.min.{version}.js") @GET public Response angular(@PathParam("version") String version) { File file; if (version.equals("1.3")) { file = new File("web/libs/angular/angular.min.1.3.15.js"); } else if (version.equals("1.4")) { file = new File("web/libs/angular/angular.min.1.4.0.js"); } else { file = new File("web/libs/angular/angular.min.1.3.15.js"); } if (file.exists()) { return Response.ok(file, "text/javascript; charset=utf-8").build(); } else { return error404(request); } } @Path("libs/bootstrap/{version}/{folder}/{filename}") @GET public Response bootstrap(@PathParam("version") String version, @PathParam("folder") String folder, @PathParam("filename") String filename) { String fullname = "web/libs/bootstrap-3.3.4-dist/"; String type = "text/html; charset=utf-8"; switch (folder) { case "css": { fullname += "css/"; type = "text/css"; switch (filename) { case "bootstrap.css": fullname += "bootstrap.css"; break; case "theme.css": fullname += "theme.css"; break; case "bootstrap.css.map": fullname += "bootstrap.css.map"; break; case "bootstrap.min.css": fullname += "bootstrap.min.css"; break; case "bootstrap-theme.css": fullname += "bootstrap-theme.css"; break; case "bootstrap-theme.css.map": fullname += "bootstrap-theme.css.mapp"; break; case "bootstrap-theme.min.css": fullname += "bootstrap-theme.min.css"; break; } break; } case "fonts": { fullname += "fonts/"; switch (filename) { case "glyphicons-halflings-regular.eot": fullname += "glyphicons-halflings-regular.eot"; type = "application/vnd.ms-fontobject"; break; case "glyphicons-halflings-regular.svg": fullname += "glyphicons-halflings-regular.svg"; type = "image/svg+xml"; break; case "glyphicons-halflings-regular.ttf": fullname += "glyphicons-halflings-regular.ttf"; type = "application/x-font-ttf"; break; case "glyphicons-halflings-regular.woff": fullname += "glyphicons-halflings-regular.woff"; type = "application/font-woff"; break; case "glyphicons-halflings-regular.woff2": fullname += "glyphicons-halflings-regular.woff2"; type = "application/font-woff"; break; } break; } case "js": { fullname += "js/"; type = "text/javascript"; switch (filename) { case "bootstrap.js": fullname += "bootstrap.js"; break; case "bootstrap.min.js": fullname += "bootstrap.js"; break; case "npm.js": fullname += "npm.js"; break; } break; } } File file = new File(fullname); if (file.exists()) { return Response.ok(file, type).build(); } else { return error404(request); } } public Response error404(HttpServletRequest request) { try { PebbleHelper pebbleHelper = PebbleHelper.getPebbleHelper("web/404.html"); return Response .status(404) .header("Content-Type", "text/html; charset=utf-8") .entity(pebbleHelper .evaluate()).build(); } catch (PebbleException e) { e.printStackTrace(); return Response.status(404).build(); } } static String readFile(String path, Charset encoding) throws IOException { byte[] encoded = Files.readAllBytes(Paths.get(path)); return new String(encoded, encoding); } @SuppressWarnings("unchecked") @Path("namepairs:{name}") @GET public Response showNamepairs(@PathParam("name") String name) { try { PebbleHelper pebbleHelper = PebbleHelper .getPebbleHelper("web/index.mini.html"); NameMap nameMap = DBSet.getInstance().getNameMap(); if (nameMap.contains(name)) { Name nameObj = nameMap.get(name); String value = nameObj.getValue(); JSONObject resultJson = NameUtils.getJsonForNameOpt(nameObj); // BAD FORMAT --> NO KEYVALUE if (resultJson == null) { resultJson = new JSONObject(); resultJson.put(Qorakeys.DEFAULT.toString(), value); value = jsonToFineSting(resultJson.toJSONString()); } pebbleHelper.getContextMap().put("keyvaluepairs", resultJson); pebbleHelper.getContextMap().put("dataname", name); return Response.status(200) .header("Content-Type", "text/html; charset=utf-8") .entity(pebbleHelper.evaluate()).build(); } else { return error404(request); } } catch (Throwable e) { e.printStackTrace(); return error404(request); } } @Path("block:{block}") @GET public Response getBlock(@PathParam("block") String strBlock) { String str; try { if (strBlock.matches("\\d+")) { str = BlocksResource.getbyHeight(Integer.valueOf(strBlock)); } else if (strBlock.equals("last")) { str = BlocksResource.getLastBlock(); } else { str = BlocksResource.getBlock(strBlock); } str = jsonToFineSting(str); } catch (Exception e1) { str = "<h2>Block does not exist!</h2"; } return Response .status(200) .header("Content-Type", "text/html; charset=utf-8") .entity(miniIndex() .replace( "<jsonresults></jsonresults>", "<br><div ng-app=\"myApp\" ng-controller=\"AppController\"><div class=\"panel panel-default\">" + "<div class=\"panel-heading\">Block : " + strBlock + "</div><table class=\"table\">" + "<tr ng-repeat=\"(key,value) in steps\"><td>{{ key }}</td><td>{{ value }}</td></tr></table></div></div>") .replace("$scope.steps = {}", "$scope.steps = " + str)) .build(); } @SuppressWarnings("unchecked") @Path("tx:{tx}") @GET public Response getTx(@PathParam("tx") String strTx) { String str = null; try { if (Crypto.getInstance().isValidAddress(strTx)) { Account account = new Account(strTx); Pair<Block, List<Transaction>> result = Controller .getInstance().scanTransactions(null, -1, -1, -1, -1, account); JSONObject json = new JSONObject(); JSONArray transactions = new JSONArray(); for (Transaction transaction : result.getB()) { transactions.add(transaction.toJson()); } json.put(strTx, transactions); str = json.toJSONString(); } else { str = TransactionsResource.getTransactionsBySignature(strTx); } str = jsonToFineSting(str); } catch (Exception e1) { str = "<h2>Transaction does not exist!</h2>"; } return Response .status(200) .header("Content-Type", "text/html; charset=utf-8") .entity(miniIndex() .replace( "<jsonresults></jsonresults>", "<br><div ng-app=\"myApp\" ng-controller=\"AppController\"><div class=\"panel panel-default\">" + "<div class=\"panel-heading\">Transaction : " + strTx + "</div><table class=\"table\">" + "<tr ng-repeat=\"(key,value) in steps\"><td>{{ key }}</td><td>{{ value }}</td></tr></table></div></div>") .replace("$scope.steps = {}", "$scope.steps = " + str)) .build(); } @Path("balance:{address}") @GET public Response getBalance(@PathParam("address") String address) { String str = null; try { String addressreal = ""; if (!Crypto.getInstance().isValidAddress(address)) { Pair<Account, NameResult> nameToAdress = NameUtils .nameToAdress(address); if (nameToAdress.getB() == NameResult.OK) { addressreal = nameToAdress.getA().getAddress(); } else { throw ApiErrorFactory.getInstance().createError( nameToAdress.getB().getErrorCode()); } } else { addressreal = address; } str = AddressesResource.getGeneratingBalance(addressreal); } catch (Exception e1) { str = "<h2>Address does not exist!</h2>"; } return Response .status(200) .header("Content-Type", "text/html; charset=utf-8") .entity(miniIndex() .replace( "<jsonresults></jsonresults>", "<br><div ng-app=\"myApp\" ng-controller=\"AppController\"><div class=\"panel panel-default\">" + "<div class=\"panel-heading\">Balance of " + address + "</div><table class=\"table\">" + "<tr ng-repeat=\"(key,value) in steps\"><td>{{ key }}</td><td>{{ value }}</td></tr></table></div></div>") .replace("$scope.steps = {}", "$scope.steps = {\"amount\":" + str + "}")) .build(); } @Path("balance:{address}:{confirmations}") @GET public Response getBalance(@PathParam("address") String address, @PathParam("confirmations") int confirmations) { String str = null; try { str = AddressesResource .getGeneratingBalance(address, confirmations); } catch (Exception e1) { str = "<h2>Address does not exist!</h2>"; } return Response .status(200) .header("Content-Type", "text/html; charset=utf-8") .entity(miniIndex() .replace( "<jsonresults></jsonresults>", "<br><div ng-app=\"myApp\" ng-controller=\"AppController\"><div class=\"panel panel-default\">" + "<div class=\"panel-heading\">Balance of " + address + ":" + confirmations + "</div><table class=\"table\">" + "<tr ng-repeat=\"(key,value) in steps\"><td>{{ key }}</td><td>{{ value }}</td></tr></table></div></div>") .replace("$scope.steps = {}", "$scope.steps = {\"amount\":" + str + "}")) .build(); } @Path("name:{name}") @GET public Response getName(@PathParam("name") String strName) { String str = null; String strNameSale = null; try { str = NamesResource.getName(strName); if (DBSet.getInstance().getNameExchangeMap().contains(strName)) { strNameSale = NameSalesResource.getNameSale(strName); } str = jsonToFineSting(str); if (strNameSale != null) { str += "\n\n" + jsonToFineSting(strNameSale); } } catch (Exception e1) { str = "<h2>Name does not exist!</h2>"; } return Response .status(200) .header("Content-Type", "text/html; charset=utf-8") .entity(miniIndex() .replace( "<jsonresults></jsonresults>", "<br><div ng-app=\"myApp\" ng-controller=\"AppController\"><div class=\"panel panel-default\">" + "<div class=\"panel-heading\">Name : " + strName + "</div><table class=\"table\">" + "<tr ng-repeat=\"(key,value) in steps\"><td>{{ key }}</td><td>{{ value }}</td></tr></table></div></div>") .replace("$scope.steps = {}", "$scope.steps = " + str)) .build(); } @Path("at:{at}") @GET public Response getAt(@PathParam("at") String strAt) { String str = null; try { str = ATResource.getAT(strAt); str = jsonToFineSting(str); } catch (Exception e1) { str = "<h2>AT does not exist!</h2>"; } return Response .status(200) .header("Content-Type", "text/html; charset=utf-8") .entity(miniIndex() .replace( "<jsonresults></jsonresults>", "<br><div ng-app=\"myApp\" ng-controller=\"AppController\"><div class=\"panel panel-default\">" + "<div class=\"panel-heading\">AT : " + strAt + "</div><table class=\"table\">" + "<tr ng-repeat=\"(key,value) in steps\"><td>{{ key }}</td><td>{{ value }}</td></tr></table></div></div>") .replace("$scope.steps = {}", "$scope.steps = " + str)) .build(); } @Path("atbysender:{atbysender}") @GET public Response getAtTx(@PathParam("atbysender") String strAtbySender) { String str = null; try { str = ATResource.getATTransactionsBySender(strAtbySender); str = jsonToFineSting(str); } catch (Exception e1) { str = "<h2>AT does not exist!</h2>"; } return Response .status(200) .header("Content-Type", "text/html; charset=utf-8") .entity(miniIndex() .replace( "<jsonresults></jsonresults>", "<br><div ng-app=\"myApp\" ng-controller=\"AppController\"><div class=\"panel panel-default\">" + "<div class=\"panel-heading\">AT Sender : " + strAtbySender + "</div><table class=\"table\">" + "<tr ng-repeat=\"(key,value) in steps\"><td>{{ key }}</td><td>{{ value }}</td></tr></table></div></div>") .replace("$scope.steps = {}", "$scope.steps = " + str)) .build(); } @Path("atbycreator:{atbycreator}") @GET public Response getAtbyCreator( @PathParam("atbycreator") String strAtbyCreator) { String str = null; try { str = ATResource.getATsByCreator(strAtbyCreator); str = jsonToFineSting(str); } catch (Exception e1) { str = "<h2>AT does not exist!</h2>"; } return Response .status(200) .header("Content-Type", "text/html; charset=utf-8") .entity(miniIndex() .replace( "<jsonresults></jsonresults>", "<br><div ng-app=\"myApp\" ng-controller=\"AppController\"><div class=\"panel panel-default\">" + "<div class=\"panel-heading\">AT Creator : " + strAtbyCreator + "</div><table class=\"table\">" + "<tr ng-repeat=\"(key,value) in steps\"><td>{{ key }}</td><td>{{ value }}</td></tr></table></div></div>") .replace("$scope.steps = {}", "$scope.steps = " + str)) .build(); } @Path("attxbyrecipient:{attxbyrecipient}") @GET public Response getATTransactionsByRecipient( @PathParam("attxbyrecipient") String StrAtTxbyRecipient) { String str = null; try { str = ATResource.getATTransactionsByRecipient(StrAtTxbyRecipient); str = jsonToFineSting(str); } catch (Exception e1) { str = "<h2>AT does not exist!</h2>"; } return Response .status(200) .header("Content-Type", "text/html; charset=utf-8") .entity(miniIndex() .replace( "<jsonresults></jsonresults>", "<br><div ng-app=\"myApp\" ng-controller=\"AppController\"><div class=\"panel panel-default\">" + "<div class=\"panel-heading\">AT TX by Recipient : " + StrAtTxbyRecipient + "</div><table class=\"table\">" + "<tr ng-repeat=\"(key,value) in steps\"><td>{{ key }}</td><td>{{ value }}</td></tr></table></div></div>") .replace("$scope.steps = {}", "$scope.steps = " + str)) .build(); } public String miniIndex() { try { return readFile("web/index.mini.html", StandardCharsets.UTF_8); } catch (IOException e) { e.printStackTrace(); return "ERROR"; } } public String jsonToFineSting(String str) { Writer writer = new JSonWriter(); Object jsonResult = JSONValue.parse(str); try { if (jsonResult instanceof JSONArray) { ((JSONArray) jsonResult).writeJSONString(writer); return writer.toString(); } if (jsonResult instanceof JSONObject) { ((JSONObject) jsonResult).writeJSONString(writer); return writer.toString(); } writer.close(); return ""; } catch (IOException e) { e.printStackTrace(); return ""; } } @Path("{name}") @GET public Response getNames(@PathParam("name") String nameName) { Name name = Controller.getInstance().getName(nameName); // CHECK IF NAME EXISTS if (name == null) { return error404(request); } String value = name.getValue(); // REDIRECT if (value.toLowerCase().startsWith("http: || value.toLowerCase().startsWith("https: return Response.status(302).header("Location", value).build(); } JSONObject jsonObject = NameUtils.getJsonForNameOpt(name); String website = null; if (jsonObject != null && jsonObject.containsKey(Qorakeys.WEBSITE.getKeyname())) { website = (String) jsonObject.get(Qorakeys.WEBSITE.getKeyname()); } if (website == null) { try { PebbleHelper pebbleHelper = PebbleHelper .getPebbleHelper("web/websitenotfound.html"); pebbleHelper.getContextMap().put("name", nameName.replaceAll(" ", "%20")); return Response.ok(pebbleHelper.evaluate(), "text/html; charset=utf-8").build(); } catch (Throwable e) { e.printStackTrace(); return error404(request); } } website = injectValues(website); // SHOW WEB-PAGE return Response.status(200) .header("Content-Type", "text/html; charset=utf-8") .entity(website).build(); } public static String injectValues(String value) { // PROCESSING TAG INJ Pattern pattern = Pattern.compile("(?i)(<inj.*>(.*?)</inj>)"); Matcher matcher = pattern.matcher(value); while (matcher.find()) { Document doc = Jsoup.parse(matcher.group(1)); Elements inj = doc.select("inj"); Element element = inj.get(0); NameMap nameMap = DBSet.getInstance().getNameMap(); String name = matcher.group(2); if (nameMap.contains(name)) { Name nameinj = nameMap.get(name); String result = GZIP.webDecompress(nameinj.getValue() .toString()); if (element.hasAttr("key")) { String key = element.attr("key"); try { JSONObject jsonObject = (JSONObject) JSONValue .parse(result); if (jsonObject != null) { // Looks like valid jSon if (jsonObject.containsKey(key)) { result = (String) jsonObject.get(key); } } } catch (Exception e) { // no json probably } } value = value.replace(matcher.group(), result); } } return value; } }
package namewebserver; import java.io.File; import java.io.IOException; import java.io.Writer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.WebApplicationException; import javax.ws.rs.core.Context; import javax.ws.rs.core.Response; import org.apache.commons.lang3.StringEscapeUtils; import org.eclipse.jetty.util.StringUtil; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.json.simple.JSONValue; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import qora.account.Account; import qora.block.Block; import qora.crypto.Base58; import qora.crypto.Crypto; import qora.naming.Name; import qora.transaction.Transaction; import utils.AccountBalanceComparator; import utils.BlogUtils; import utils.GZIP; import utils.JSonWriter; import utils.NameUtils; import utils.NameUtils.NameResult; import utils.Pair; import utils.Qorakeys; import api.ATResource; import api.AddressesResource; import api.ApiErrorFactory; import api.ArbitraryTransactionsResource; import api.BlocksResource; import api.NameSalesResource; import api.NamesResource; import api.TransactionsResource; import controller.Controller; import database.DBSet; import database.NameMap; @Path("/") public class NamesWebResource { @Context HttpServletRequest request; @GET public Response Default() { return handleDefault(); } public Response handleDefault() { try { String searchValue = request.getParameter("search"); String webDirectory = request.getParameter("webdirectory"); String content = readFile("web/index.html", StandardCharsets.UTF_8); if (StringUtil.isBlank(searchValue) && StringUtil.isBlank(webDirectory)) { content = replaceWarning(content); return Response.ok(content, "text/html; charset=utf-8").build(); } else if (searchValue != null || webDirectory != null) { List<Pair<String, String>> searchResults; if (webDirectory != null) { searchResults = NameUtils.getWebsitesByValue(null); } else { searchResults = NameUtils.getWebsitesByValue(searchValue); } content = readFile("web/index.mini.html", StandardCharsets.UTF_8); String searchResultTemplate = readFile("web/searchresult", StandardCharsets.UTF_8); String results = ""; for (Pair<String, String> result : searchResults) { String name = result.getA(); String websitecontent = result.getB(); Document htmlDoc = Jsoup.parse(websitecontent); String title = selectTitleOpt(htmlDoc); title = title == null ? "" : title; String description = selectDescriptionOpt(htmlDoc); description = description == null ? "" : description; results += searchResultTemplate.replace("!Name!", name) .replace("!Title!", title) .replace("!Description!", description) .replace("!Titlelink!", "/" + name) .replace("!Namelink!", "/" + name) .replace("!keyslink!", "/namepairs:" + name); } content = content.replace("<resultlist></resultlist>", results); } return Response.ok(content, "text/html; charset=utf-8").build(); } catch (IOException e) { e.printStackTrace(); return error404(request); } } public String selectTitleOpt(Document htmlDoc) { String title = selectFirstElementOpt(htmlDoc, "title"); return title; } public String selectFirstElementOpt(Document htmlDoc, String tag) { Elements titleElements = htmlDoc.select(tag); String title = null; if (titleElements.size() > 0) { title = titleElements.get(0).text(); } return title; } public String selectDescriptionOpt(Document htmlDoc) { String result = ""; Elements descriptions = htmlDoc.select("meta[name=\"description\"]"); if (descriptions.size() > 0) { Element descr = descriptions.get(0); if (descr.hasAttr("content")) { result = descr.attr("content"); } } return result; } private String replaceWarning(String content) { content = content.replace("<warning></warning>", getWarning(request)); return content; } @Path("index.html") @GET public Response handleIndex() { return handleDefault(); } @Path("favicon.ico") @GET public Response favicon() { File file = new File("web/favicon.ico"); if (file.exists()) { return Response.ok(file, "image/vnd.microsoft.icon").build(); } else { return error404(request); } } @Path("index/qora.png") @GET public Response qorapng() { File file = new File("web/qora.png"); if (file.exists()) { return Response.ok(file, "image/png").build(); } else { return error404(request); } } @Path("index/logo_header.png") @GET public Response logo_header() { File file = new File("web/logo_header.png"); if (file.exists()) { return Response.ok(file, "image/png").build(); } else { return error404(request); } } @Path("index/style.css") @GET public Response style() { File file = new File("web/style.css"); if (file.exists()) { return Response.ok(file, "text/css").build(); } else { return error404(request); } } @Path("index/theme.css") @GET public Response theme() { File file = new File("web/theme.css"); if (file.exists()) { return Response.ok(file, "text/css").build(); } else { return error404(request); } } @Path("index/qora-user.png") @GET public Response qorauserpng() { File file = new File("web/qora-user.png"); if (file.exists()) { return Response.ok(file, "image/png").build(); } else { return error404(request); } } @Path("webdirectory.html") @GET public Response websites() { try { String content = readFile("web/webdirectory.html", StandardCharsets.UTF_8); content = replaceWarning(content); List<Pair<String, String>> namesContainingWebsites = NameUtils .getNamesContainingWebsites(); String linksAsHtml = ""; for (Pair<String, String> websitepair : namesContainingWebsites) { String name = websitepair.getA(); linksAsHtml += "<a href=/" + name.replaceAll(" ", "%20") + ">" + name + "</a><br>"; } content = content.replace("!linkstoreplace!", linksAsHtml); return Response.ok(content, "text/html; charset=utf-8").build(); } catch (IOException e) { e.printStackTrace(); return error404(request); } } @SuppressWarnings("unchecked") @Path("postblog.html") @GET public Response postBlog() { try { String content = readFile("web/postblog.html", StandardCharsets.UTF_8); String title = request.getParameter("title"); String creator = request.getParameter("creator"); String contentparam = request.getParameter("content"); String fee = request.getParameter("fee"); List<Account> accounts = new ArrayList<Account>(Controller .getInstance().getAccounts()); Collections.sort(accounts, new AccountBalanceComparator()); Collections.reverse(accounts); String accountStrings = ""; for (Account account : accounts) { accountStrings += "<option value=" + account.getAddress() + ">" + account + "</option>"; } content = content.replaceAll("<option></option>", accountStrings); if (StringUtil.isNotBlank(creator) && StringUtil.isNotBlank(contentparam) && StringUtil.isNotBlank(fee)) { JSONObject json = new JSONObject(); json.put("creator", creator); json.put("service", 777); json.put("fee", fee); String params = "{\"title\":\"" + title + "\"" + ",\"post\":\"" + contentparam + "\"}"; String data = Base58.encode(params.getBytes()); json.put("data", data); // TODO maybe this is not the best way try { String result = new ArbitraryTransactionsResource() .createArbitraryTransaction(json.toJSONString()); content = content .replaceAll( "<font></font>", "<div class=\"alert alert-success\" role=\"alert\">Your post was successful<br>" + result + "</div>"); } catch (WebApplicationException e) { content = content .replaceAll( "<font></font>", "<div class=\"alert alert-danger\" role=\"alert\">Your post was NOT successful<br>" + e.getResponse().getEntity() + "</div>"); } } return Response.ok(content, "text/html; charset=utf-8").build(); } catch (IOException e) { e.printStackTrace(); return error404(request); } } public String transformURLIntoLinks(String text) { String urlValidationRegex = "(https?|ftp)://(www\\d?|[a-zA-Z0-9]+)?.[a-zA-Z0-9-]+(\\:|.)([a-zA-Z0-9.]+|(\\d+)?)([/?:].*)?"; Pattern p = Pattern.compile(urlValidationRegex); Matcher m = p.matcher(text); StringBuffer sb = new StringBuffer(); while (m.find()) { String found = m.group(0); m.appendReplacement(sb, "<a href='" + found + "'>" + found + "</a>"); } m.appendTail(sb); return sb.toString(); } private ArrayList<String> getAllLinks(String text) { ArrayList<String> links = new ArrayList<>(); String regex = "\\(?\\b(http(s?)://|www[.])[-A-Za-z0-9+&amp;@#/%?=~_()|!:,.;]*[-A-Za-z0-9+&amp;@#/%=~_()|]"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(text); while (m.find()) { String urlStr = m.group(); if (urlStr.startsWith("(") && urlStr.endsWith(")")) { urlStr = urlStr.substring(1, urlStr.length() - 1); } links.add(urlStr); } return links; } @Path("blog.html") @GET public Response getBlog() { try { String content = readFile("web/blog.html", StandardCharsets.UTF_8); content = replaceWarning(content); List<Pair<String, String>> blogPosts = BlogUtils.getBlogPosts(); String results = "<br>"; String entryTemplate = "<li class=\"media\"><a class=\"pull-left\" href=\"#\"><img class=\"media-object\" src=\"index/qora-user.png\" alt=\"Generic placeholder image\"></a><div class=\"media-body\"><h4 class=\"media-heading\">TITLE</h4><p>CONTENT</p></div></li>"; for (Pair<String, String> pair : blogPosts) { String converted = entryTemplate; String body = pair.getB(); List<Pair<String, String>> linkList = createHtmlLinks(getAllLinks(body)); for (Pair<String, String> link : linkList) { String originalLink = link.getA(); String newLink = link.getB(); body = body.replace(originalLink, newLink); } converted = converted.replaceAll("TITLE", pair.getA()); converted = converted.replaceAll("CONTENT", body); results += converted; } content = content.replace("!blogposts!", results); return Response.ok(content, "text/html; charset=utf-8").build(); } catch (IOException e) { e.printStackTrace(); return error404(request); } } private List<Pair<String, String>> createHtmlLinks(List<String> links) { List<Pair<String, String>> result = new ArrayList<>(); for (String link : links) { String refurbishedlink = StringEscapeUtils.unescapeHtml4(link); if (refurbishedlink.toLowerCase().matches( Pattern.quote("https: String vid = refurbishedlink.replaceAll( Pattern.quote("https: + "([a-zA-Z0-9]+).*", "$1"); result.add(new Pair<String, String>( link, "<iframe width=\"560\" height=\"315\" src=\"https: + vid + "\" frameborder=\"0\" allowfullscreen></iframe>")); } else { refurbishedlink = transformURLIntoLinks(refurbishedlink); result.add(new Pair<String, String>(link, refurbishedlink)); } } return result; } @Path("libs/jquery.{version}.js") @GET public Response jquery(@PathParam("version") String version) { File file; if (version.equals("1")) { file = new File("web/jquery-1.11.3.min.js"); } else if (version.equals("2")) { file = new File("web/jquery-2.1.4.min.js"); } else { file = new File("web/jquery-2.1.4.min.js"); } if (file.exists()) { return Response.ok(file, "text/javascript; charset=utf-8").build(); } else { return error404(request); } } @Path("libs/angular.min.{version}.js") @GET public Response angular(@PathParam("version") String version) { File file; if (version.equals("1.3")) { file = new File("web/angular.min.1.3.15.js"); } else if (version.equals("1.4")) { file = new File("web/angular.min.1.4.0.js"); } else { file = new File("web/angular.min.1.3.15.js"); } if (file.exists()) { return Response.ok(file, "text/javascript; charset=utf-8").build(); } else { return error404(request); } } @Path("libs/bootstrap/{version}/{folder}/{filename}") @GET public Response bootstrap(@PathParam("version") String version, @PathParam("folder") String folder, @PathParam("filename") String filename) { String fullname = "web/bootstrap-3.3.4-dist/"; String type = "text/html; charset=utf-8"; switch (folder) { case "css": { fullname += "css/"; type = "text/css"; switch (filename) { case "bootstrap.css": fullname += "bootstrap.css"; break; case "theme.css": fullname += "theme.css"; break; case "bootstrap.css.map": fullname += "bootstrap.css.map"; break; case "bootstrap.min.css": fullname += "bootstrap.min.css"; break; case "bootstrap-theme.css": fullname += "bootstrap-theme.css"; break; case "bootstrap-theme.css.map": fullname += "bootstrap-theme.css.mapp"; break; case "bootstrap-theme.min.css": fullname += "bootstrap-theme.min.css"; break; } break; } case "fonts": { fullname += "fonts/"; switch (filename) { case "glyphicons-halflings-regular.eot": fullname += "glyphicons-halflings-regular.eot"; type = "application/vnd.ms-fontobject"; break; case "glyphicons-halflings-regular.svg": fullname += "glyphicons-halflings-regular.svg"; type = "image/svg+xml"; break; case "glyphicons-halflings-regular.ttf": fullname += "glyphicons-halflings-regular.ttf"; type = "application/x-font-ttf"; break; case "glyphicons-halflings-regular.woff": fullname += "glyphicons-halflings-regular.woff"; type = "application/font-woff"; break; case "glyphicons-halflings-regular.woff2": fullname += "glyphicons-halflings-regular.woff2"; type = "application/font-woff"; break; } break; } case "js": { fullname += "js/"; type = "text/javascript"; switch (filename) { case "bootstrap.js": fullname += "bootstrap.js"; break; case "bootstrap.min.js": fullname += "bootstrap.js"; break; case "npm.js": fullname += "npm.js"; break; } break; } } File file = new File(fullname); if (file.exists()) { return Response.ok(file, type).build(); } else { return error404(request); } } public Response error404(HttpServletRequest request) { String pathInfo = request.getPathInfo(); pathInfo = pathInfo.substring(1, pathInfo.length()); return Response .status(404) .header("Content-Type", "text/html; charset=utf-8") .entity(miniIndex().replace("<data></data>", pathInfo) + "<h1>name \"" + pathInfo + "\" does not exist</h1><hr> <a href=http: .build(); } private String getWarning(HttpServletRequest request) { if (Controller.getInstance().isWalletUnlocked()) { String ipAddress = request.getHeader("X-FORWARDED-FOR"); if (ipAddress == null) { ipAddress = request.getRemoteAddr(); } if (ipAddress.equals("127.0.0.1")) { return "<style type=\"text/css\">" + "#message_box {" // + "position:absolute;" + "left:0; right:0; top:0;" + "z-index: 10;" + "background:#ffc;" // + "padding:5px;" + "border:1px solid #CCCCCC;" // + "text-align:center;" + "font-weight:bold;" + "width:auto;" + "}" + "</STYLE>" + "<div id=message_box>Wallet is unlocked!</div>" + "<div style='margin-top:50px'>"; } } return ""; } static String readFile(String path, Charset encoding) throws IOException { byte[] encoded = Files.readAllBytes(Paths.get(path)); return new String(encoded, encoding); } @SuppressWarnings("unchecked") @Path("namepairs:{name}") @GET public Response showNamepairs(@PathParam("name") String name) { NameMap nameMap = DBSet.getInstance().getNameMap(); if (nameMap.contains(name)) { String value = nameMap.get(name).getValue(); JSONObject resultJson = null; try { // WEBPAGE GZIP DECOMPRESSOR value = GZIP.webDecompress(value); JSONObject jsonObject = (JSONObject) JSONValue.parse(value); if (jsonObject != null) { // Looks like valid jSon resultJson = jsonObject; } } catch (Exception e) { // no json probably } // BAD FORMAT --> NO KEYVALUE if (resultJson == null) { resultJson = new JSONObject(); resultJson.put(Qorakeys.DEFAULT.toString(), value); value = jsonToFineSting(resultJson.toJSONString()); } return Response .status(200) .header("Content-Type", "text/html; charset=utf-8") .entity(miniIndex() .replace("<data></data>", "namepairs:" + name) .replace( "<jsonresults></jsonresults>", "<br><div ng-app=\"myApp\" ng-controller=\"AppController\"><div class=\"panel panel-default\">" + "<div class=\"panel-heading\">Results on :" + name + "</div><table class=\"table\">" + "<tr ng-repeat=\"(key,value) in steps\"><td>{{ key }}</td><td>{{ value }}</td></tr></table></div></div>") .replace("$scope.steps = {}", "$scope.steps = " + value)).build(); } else { return error404(request); } } @Path("block:{block}") @GET public Response getBlock(@PathParam("block") String strBlock) { String str; try { if (strBlock.matches("\\d+")) { str = BlocksResource.getbyHeight(Integer.valueOf(strBlock)); } else if (strBlock.equals("last")) { str = BlocksResource.getLastBlock(); } else { str = BlocksResource.getBlock(strBlock); } str = jsonToFineSting(str); } catch (Exception e1) { str = "<h2>Block does not exist!</h2"; } return Response .status(200) .header("Content-Type", "text/html; charset=utf-8") .entity(miniIndex() .replace( "<jsonresults></jsonresults>", "<br><div ng-app=\"myApp\" ng-controller=\"AppController\"><div class=\"panel panel-default\">" + "<div class=\"panel-heading\">Block : " + strBlock + "</div><table class=\"table\">" + "<tr ng-repeat=\"(key,value) in steps\"><td>{{ key }}</td><td>{{ value }}</td></tr></table></div></div>") .replace("$scope.steps = {}", "$scope.steps = " + str)) .build(); } @SuppressWarnings("unchecked") @Path("tx:{tx}") @GET public Response getTx(@PathParam("tx") String strTx) { String str = null; try { if (Crypto.getInstance().isValidAddress(strTx)) { Account account = new Account(strTx); Pair<Block, List<Transaction>> result = Controller .getInstance().scanTransactions(null, -1, -1, -1, -1, account); JSONObject json = new JSONObject(); JSONArray transactions = new JSONArray(); for (Transaction transaction : result.getB()) { transactions.add(transaction.toJson()); } json.put(strTx, transactions); str = json.toJSONString(); } else { str = TransactionsResource.getTransactionsBySignature(strTx); } str = jsonToFineSting(str); } catch (Exception e1) { str = "<h2>Transaction does not exist!</h2>"; } return Response .status(200) .header("Content-Type", "text/html; charset=utf-8") .entity(miniIndex() .replace( "<jsonresults></jsonresults>", "<br><div ng-app=\"myApp\" ng-controller=\"AppController\"><div class=\"panel panel-default\">" + "<div class=\"panel-heading\">Transaction : " + strTx + "</div><table class=\"table\">" + "<tr ng-repeat=\"(key,value) in steps\"><td>{{ key }}</td><td>{{ value }}</td></tr></table></div></div>") .replace("$scope.steps = {}", "$scope.steps = " + str)) .build(); } @Path("balance:{address}") @GET public Response getBalance(@PathParam("address") String address) { String str = null; try { String addressreal = ""; if (!Crypto.getInstance().isValidAddress(address)) { Pair<Account, NameResult> nameToAdress = NameUtils .nameToAdress(address); if (nameToAdress.getB() == NameResult.OK) { addressreal = nameToAdress.getA().getAddress(); } else { throw ApiErrorFactory.getInstance().createError( nameToAdress.getB().getErrorCode()); } } else { addressreal = address; } str = AddressesResource.getGeneratingBalance(addressreal); } catch (Exception e1) { str = "<h2>Address does not exist!</h2>"; } return Response .status(200) .header("Content-Type", "text/html; charset=utf-8") .entity(miniIndex() .replace( "<jsonresults></jsonresults>", "<br><div ng-app=\"myApp\" ng-controller=\"AppController\"><div class=\"panel panel-default\">" + "<div class=\"panel-heading\">Balance of " + address + "</div><table class=\"table\">" + "<tr ng-repeat=\"(key,value) in steps\"><td>{{ key }}</td><td>{{ value }}</td></tr></table></div></div>") .replace("$scope.steps = {}", "$scope.steps = {\"amount\":" + str + "}")) .build(); } @Path("balance:{address}:{confirmations}") @GET public Response getBalance(@PathParam("address") String address, @PathParam("confirmations") int confirmations) { String str = null; try { str = AddressesResource .getGeneratingBalance(address, confirmations); } catch (Exception e1) { str = "<h2>Address does not exist!</h2>"; } return Response .status(200) .header("Content-Type", "text/html; charset=utf-8") .entity(miniIndex() .replace( "<jsonresults></jsonresults>", "<br><div ng-app=\"myApp\" ng-controller=\"AppController\"><div class=\"panel panel-default\">" + "<div class=\"panel-heading\">Balance of " + address + ":" + confirmations + "</div><table class=\"table\">" + "<tr ng-repeat=\"(key,value) in steps\"><td>{{ key }}</td><td>{{ value }}</td></tr></table></div></div>") .replace("$scope.steps = {}", "$scope.steps = {\"amount\":" + str + "}")) .build(); } @Path("name:{name}") @GET public Response getName(@PathParam("name") String strName) { String str = null; String strNameSale = null; try { str = NamesResource.getName(strName); if (DBSet.getInstance().getNameExchangeMap().contains(strName)) { strNameSale = NameSalesResource.getNameSale(strName); } str = jsonToFineSting(str); if (strNameSale != null) { str += "\n\n" + jsonToFineSting(strNameSale); } } catch (Exception e1) { str = "<h2>Name does not exist!</h2>"; } return Response .status(200) .header("Content-Type", "text/html; charset=utf-8") .entity(miniIndex() .replace( "<jsonresults></jsonresults>", "<br><div ng-app=\"myApp\" ng-controller=\"AppController\"><div class=\"panel panel-default\">" + "<div class=\"panel-heading\">Name : " + strName + "</div><table class=\"table\">" + "<tr ng-repeat=\"(key,value) in steps\"><td>{{ key }}</td><td>{{ value }}</td></tr></table></div></div>") .replace("$scope.steps = {}", "$scope.steps = " + str)) .build(); } @Path("at:{at}") @GET public Response getAt(@PathParam("at") String strAt) { String str = null; try { str = ATResource.getAT(strAt); str = jsonToFineSting(str); } catch (Exception e1) { str = "<h2>AT does not exist!</h2>"; } return Response .status(200) .header("Content-Type", "text/html; charset=utf-8") .entity(miniIndex() .replace( "<jsonresults></jsonresults>", "<br><div ng-app=\"myApp\" ng-controller=\"AppController\"><div class=\"panel panel-default\">" + "<div class=\"panel-heading\">AT : " + strAt + "</div><table class=\"table\">" + "<tr ng-repeat=\"(key,value) in steps\"><td>{{ key }}</td><td>{{ value }}</td></tr></table></div></div>") .replace("$scope.steps = {}", "$scope.steps = " + str)) .build(); } @Path("atbysender:{atbysender}") @GET public Response getAtTx(@PathParam("atbysender") String strAtbySender) { String str = null; try { str = ATResource.getATTransactionsBySender(strAtbySender); str = jsonToFineSting(str); } catch (Exception e1) { str = "<h2>AT does not exist!</h2>"; } return Response .status(200) .header("Content-Type", "text/html; charset=utf-8") .entity(miniIndex() .replace( "<jsonresults></jsonresults>", "<br><div ng-app=\"myApp\" ng-controller=\"AppController\"><div class=\"panel panel-default\">" + "<div class=\"panel-heading\">AT Sender : " + strAtbySender + "</div><table class=\"table\">" + "<tr ng-repeat=\"(key,value) in steps\"><td>{{ key }}</td><td>{{ value }}</td></tr></table></div></div>") .replace("$scope.steps = {}", "$scope.steps = " + str)) .build(); } @Path("atbycreator:{atbycreator}") @GET public Response getAtbyCreator( @PathParam("atbycreator") String strAtbyCreator) { String str = null; try { str = ATResource.getATsByCreator(strAtbyCreator); str = jsonToFineSting(str); } catch (Exception e1) { str = "<h2>AT does not exist!</h2>"; } return Response .status(200) .header("Content-Type", "text/html; charset=utf-8") .entity(miniIndex() .replace( "<jsonresults></jsonresults>", "<br><div ng-app=\"myApp\" ng-controller=\"AppController\"><div class=\"panel panel-default\">" + "<div class=\"panel-heading\">AT Creator : " + strAtbyCreator + "</div><table class=\"table\">" + "<tr ng-repeat=\"(key,value) in steps\"><td>{{ key }}</td><td>{{ value }}</td></tr></table></div></div>") .replace("$scope.steps = {}", "$scope.steps = " + str)) .build(); } @Path("attxbyrecipient:{attxbyrecipient}") @GET public Response getATTransactionsByRecipient( @PathParam("attxbyrecipient") String StrAtTxbyRecipient) { String str = null; try { str = ATResource.getATTransactionsByRecipient(StrAtTxbyRecipient); str = jsonToFineSting(str); } catch (Exception e1) { str = "<h2>AT does not exist!</h2>"; } return Response .status(200) .header("Content-Type", "text/html; charset=utf-8") .entity(miniIndex() .replace( "<jsonresults></jsonresults>", "<br><div ng-app=\"myApp\" ng-controller=\"AppController\"><div class=\"panel panel-default\">" + "<div class=\"panel-heading\">AT TX by Recipient : " + StrAtTxbyRecipient + "</div><table class=\"table\">" + "<tr ng-repeat=\"(key,value) in steps\"><td>{{ key }}</td><td>{{ value }}</td></tr></table></div></div>") .replace("$scope.steps = {}", "$scope.steps = " + str)) .build(); } public String miniIndex() { try { return readFile("web/index.mini.html", StandardCharsets.UTF_8); } catch (IOException e) { e.printStackTrace(); return "ERROR"; } } public String jsonToFineSting(String str) { Writer writer = new JSonWriter(); Object jsonResult = JSONValue.parse(str); try { if (jsonResult instanceof JSONArray) { ((JSONArray) jsonResult).writeJSONString(writer); return writer.toString(); } if (jsonResult instanceof JSONObject) { ((JSONObject) jsonResult).writeJSONString(writer); return writer.toString(); } writer.close(); return ""; } catch (IOException e) { e.printStackTrace(); return ""; } } @Path("{name}") @GET public Response getNames(@PathParam("name") String nameName) { Name name = Controller.getInstance().getName(nameName); // CHECK IF NAME EXISTS if (name == null) { return error404(request); } String Value = name.getValue().toString(); // REDIRECT if (Value.startsWith("http: return Response.status(302).header("Location", Value).build(); } // WEBPAGE GZIP DECOMPRESSOR Value = GZIP.webDecompress(Value); String website = null; try { JSONObject jsonObject = (JSONObject) JSONValue.parse(Value); if (jsonObject != null && jsonObject.containsKey(Qorakeys.WEBSITE.getKeyname())) { website = (String) jsonObject .get(Qorakeys.WEBSITE.getKeyname()); } } catch (Exception e) { // no json probably } if (website == null) { try { String content = readFile("web/websitenotfound.html", StandardCharsets.UTF_8); content = content .replaceAll( "!websitenotfoundcontent!", "<br><font color=\"red\">If this is your name, please do a name update for the name <a href=/name:" + nameName.replaceAll(" ", "%20") + ">" + nameName + "</a> and add the key \"website\" with webcontent as value to make this work.</font><br>You can see the current value <a href=/name:" + nameName.replaceAll(" ", "%20") + ">here</a>"); Value = injectValues(Value); return Response.ok(content, "text/html; charset=utf-8").build(); } catch (IOException e) { return error404(request); } } website = injectValues(website); // SHOW WEB-PAGE return Response.status(200) .header("Content-Type", "text/html; charset=utf-8") .entity(getWarning(request) + website).build(); } public String injectValues(String value) { // PROCESSING TAG INJ Pattern pattern = Pattern.compile("(?i)(<inj.*>(.*?)</inj>)"); Matcher matcher = pattern.matcher(value); while (matcher.find()) { Document doc = Jsoup.parse(matcher.group(1)); Elements inj = doc.select("inj"); Element element = inj.get(0); NameMap nameMap = DBSet.getInstance().getNameMap(); String name = matcher.group(2); if (nameMap.contains(name)) { Name nameinj = nameMap.get(name); String result = GZIP.webDecompress(nameinj.getValue() .toString()); if (element.hasAttr("key")) { String key = element.attr("key"); try { JSONObject jsonObject = (JSONObject) JSONValue .parse(result); if (jsonObject != null) { // Looks like valid jSon if (jsonObject.containsKey(key)) { result = (String) jsonObject.get(key); } } } catch (Exception e) { // no json probably } } value = value.replace(matcher.group(), result); } } return value; } }
package org.reldb.relui.dbui; import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.FileDialog; import org.eclipse.swt.custom.SashForm; import org.eclipse.swt.custom.StyleRange; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.SWT; import org.eclipse.swt.layout.FillLayout; import org.eclipse.swt.custom.StackLayout; import org.eclipse.swt.graphics.Color; import org.reldb.rel.client.parser.ResponseToHTML; import org.reldb.rel.client.parser.core.ParseException; import org.reldb.relui.dbui.html.BrowserManager; import org.reldb.relui.dbui.preferences.PreferenceChangeAdapter; import org.reldb.relui.dbui.preferences.PreferenceChangeEvent; import org.reldb.relui.dbui.preferences.PreferenceChangeListener; import org.reldb.relui.dbui.preferences.PreferencePageCmd; import org.reldb.relui.dbui.preferences.Preferences; public class CmdPanel extends Composite { private BrowserManager browser; private StyledText styledText; private CmdPanelInput cmdPanelInput; private Composite outputStack; private StackLayout outputStackLayout; private boolean showOk = true; private boolean isEnhancedOutput = true; private boolean isShowHeadings = true; private boolean isShowHeadingTypes = true; private boolean isAutoclear = true; private Color red = new Color(getDisplay(), 200, 0, 0); private Color green = new Color(getDisplay(), 0, 128, 0); private Color blue = new Color(getDisplay(), 0, 0, 128); private Color black = new Color(getDisplay(), 0, 0, 0); private Color grey = new Color(getDisplay(), 128, 128, 128); private Color yellow = new Color(getDisplay(), 255, 215, 0); private FileDialog saveHtmlDialog; private FileDialog saveTextDialog; private boolean copyInputToOutput = true; private boolean responseFormatted = false; private ConcurrentStringReceiverClient connection; private StringBuffer reply = new StringBuffer(); private PreferenceChangeListener browserPreferenceChangeListener; private PreferenceChangeListener fontPreferenceChangeListener; /** * Create the composite. * @param parent * @param style * @throws IOException * @throws ClassNotFoundException * @throws NumberFormatException */ public CmdPanel(DbTab dbTab, Composite parent, int style) throws NumberFormatException, ClassNotFoundException, IOException { super(parent, style); setLayout(new FillLayout(SWT.HORIZONTAL)); SashForm sashForm = new SashForm(this, SWT.VERTICAL); outputStack = new Composite(sashForm, SWT.NONE); outputStackLayout = new StackLayout(); outputStack.setLayout(outputStackLayout); styledText = new StyledText(outputStack, SWT.BORDER | SWT.V_SCROLL | SWT.MULTI | SWT.H_SCROLL); styledText.setEditable(false); browser = new BrowserManager(); browser.createWidget(outputStack); browserPreferenceChangeListener = new PreferenceChangeAdapter("CmdPanel_browser") { @Override public void preferenceChange(PreferenceChangeEvent preferenceChangeEvent) { browser.changeWidget(outputStack); setEnhancedOutput(getEnhancedOutput()); } }; Preferences.addPreferenceChangeListener(PreferencePageCmd.CMD_BROWSER_SWING, browserPreferenceChangeListener); styledText.setFont(Preferences.getPreferenceFont(getDisplay(), PreferencePageCmd.CMD_FONT)); fontPreferenceChangeListener = new PreferenceChangeAdapter("CmdPanel_font") { @Override public void preferenceChange(PreferenceChangeEvent preferenceChangeEvent) { styledText.setFont(Preferences.getPreferenceFont(getDisplay(), PreferencePageCmd.CMD_FONT)); browser.setContent(browser.getContent()); } }; Preferences.addPreferenceChangeListener(PreferencePageCmd.CMD_FONT, fontPreferenceChangeListener); outputStackLayout.topControl = browser.getWidget(); connection = new ConcurrentStringReceiverClient(this, dbTab.getURL(), false) { StringBuffer errorBuffer = null; @Override public void received(String r) { if (r.equals("\n")) { return; } else if (r.equals("Ok.")) { if (showOk) goodResponse(r); reply = new StringBuffer(); } else if (r.equals("Cancel.")) { warningResponse(r); reply = new StringBuffer(); } else if (r.startsWith("ERROR:")) { badResponse(r); outputPlain("\n", black); reply = new StringBuffer(); errorBuffer = new StringBuffer(); if (r.contains(", column")) { errorBuffer.append(r); errorBuffer.append('\n'); } } else if (r.startsWith("NOTICE")) { noticeResponse(r); reply = new StringBuffer(); } else { if (responseFormatted) { reply.append(r); reply.append("\n"); } else outputHTML(getResponseFormatted(r, responseFormatted)); responseText(r, black); if (errorBuffer != null) { errorBuffer.append(r); errorBuffer.append('\n'); } } } @Override public void received(Exception e) { badResponse(e.toString()); } @Override public void update() { outputUpdated(); } @Override public void finished() { if (responseFormatted && reply.length() > 0) { String content = reply.toString(); outputHTML(getResponseFormatted(content, responseFormatted)); outputUpdated(); } StyledText inputTextWidget = cmdPanelInput.getInputTextWidget(); if (errorBuffer != null) { ErrorInformation eInfo = parseErrorInformationFrom(errorBuffer.toString()); if (eInfo != null) { int startOffset = 0; try { if (eInfo.getLine() > 0) { startOffset = inputTextWidget.getOffsetAtLine(eInfo.getLine() - 1); if (eInfo.getColumn() > 0) startOffset += eInfo.getColumn() - 1; } inputTextWidget.setCaretOffset(startOffset); if (eInfo.getBadToken() != null) inputTextWidget.setSelection(startOffset, startOffset + eInfo.getBadToken().length()); } catch (Exception e) { System.out.println("CmdPanel: Unable to position to line " + eInfo.getLine() + ", column " + eInfo.getColumn()); } } else System.out.println("CmdPanel: Unable to locate error in " + errorBuffer.toString()); errorBuffer = null; } else { inputTextWidget.selectAll(); } inputTextWidget.setFocus(); cmdPanelInput.done(); } }; cmdPanelInput = new CmdPanelInput(sashForm, SWT.NONE) { @Override protected void setCopyInputToOutput(boolean selection) { copyInputToOutput = selection; } @Override protected void announcement(String msg) { systemResponse(msg); } @Override protected void announceError(String msg, Throwable t) { badResponse(msg); } @Override public void notifyGo(String text) { reply = new StringBuffer(); if (isAutoclear) clearOutput(); if (copyInputToOutput) userResponse(text); try { if (isLastNonWhitespaceCharacter(text.trim(), ';')) { responseFormatted = false; connection.sendExecute(text); } else { responseFormatted = true; connection.sendEvaluate(text); } } catch (Throwable ioe) { badResponse(ioe.getMessage()); } } @Override public void notifyStop() { connection.reset(); } }; sashForm.setWeights(new int[] {2, 1}); outputPlain(connection.getInitialServerResponse(), black); outputHTML(ResponseToHTML.textToHTML(connection.getInitialServerResponse())); goodResponse("Ok."); } public void clearOutput() { browser.clear(); styledText.setText(""); } public void copyOutputToInput() { String selection = styledText.getSelectionText(); if (selection.length() == 0) cmdPanelInput.insertInputText(cmdPanelInput.getInputText() + styledText.getText()); else cmdPanelInput.insertInputText(cmdPanelInput.getInputText() + selection); } public void setEnhancedOutput(boolean selection) { outputStackLayout.topControl = (selection) ? browser.getWidget() : styledText; outputStack.layout(); isEnhancedOutput = selection; } public boolean getEnhancedOutput() { return isEnhancedOutput; } public void setShowOk(boolean selection) { showOk = selection; } public boolean getShowOk() { return showOk; } public void setHeadingVisible(boolean selection) { isShowHeadings = selection; } public boolean getHeadingVisible() { return isShowHeadings; } public void setHeadingTypesVisible(boolean selection) { isShowHeadingTypes = selection; } public boolean getHeadingTypesVisible() { return isShowHeadingTypes; } public void setAutoclear(boolean selection) { isAutoclear = selection; } public boolean getAutoclear() { return isAutoclear; } public void saveOutputAsHtml() { ensureSaveHtmlDialogExists(); String fname = saveHtmlDialog.open(); if (fname == null) return; try { BufferedWriter f = new BufferedWriter(new FileWriter(fname)); f.write(browser.getText()); f.close(); systemResponse("Saved " + fname); } catch (IOException ioe) { badResponse(ioe.toString()); } } public void saveOutputAsText() { ensureSaveTextDialogExists(); String fname = saveTextDialog.open(); if (fname == null) return; try { BufferedWriter f = new BufferedWriter(new FileWriter(fname)); f.write(styledText.getText()); f.close(); systemResponse("Saved " + fname); } catch (IOException ioe) { badResponse(ioe.toString()); } } public void dispose() { Preferences.removePreferenceChangeListener(PreferencePageCmd.CMD_BROWSER_SWING, browserPreferenceChangeListener); Preferences.removePreferenceChangeListener(PreferencePageCmd.CMD_FONT, fontPreferenceChangeListener); connection.close(); clearOutput(); cmdPanelInput.dispose(); red.dispose(); green.dispose(); blue.dispose(); black.dispose(); grey.dispose(); yellow.dispose(); super.dispose(); } private void ensureSaveHtmlDialogExists() { if (saveHtmlDialog == null) { saveHtmlDialog = new FileDialog(getShell(), SWT.SAVE); saveHtmlDialog.setFilterPath(System.getProperty("user.home")); saveHtmlDialog.setFilterExtensions(new String[] {"*.html", "*.*"}); saveHtmlDialog.setFilterNames(new String[] {"HTML", "All Files"}); saveHtmlDialog.setText("Save Output"); saveHtmlDialog.setOverwrite(true); } } private void ensureSaveTextDialogExists() { if (saveTextDialog == null) { saveTextDialog = new FileDialog(getShell(), SWT.SAVE); saveTextDialog.setFilterPath(System.getProperty("user.home")); saveTextDialog.setFilterExtensions(new String[] {"*.txt", "*.*"}); saveTextDialog.setFilterNames(new String[] {"Text", "All Files"}); saveTextDialog.setText("Save Output"); saveTextDialog.setOverwrite(true); } } private void outputPlain(String s, Color color) { StyleRange styleRange = new StyleRange(); styleRange.start = styledText.getCharCount(); styleRange.length = s.length(); styleRange.fontStyle = SWT.NORMAL; styleRange.foreground = color; styledText.append(s); styledText.setStyleRange(styleRange); } private void outputHTML(String s) { browser.appendHtml(s); } /** Get formatted response. */ private String getResponseFormatted(String s, boolean parseResponse) { if (parseResponse) { try { StringBuffer sb = new StringBuffer(); ResponseToHTML response = new ResponseToHTML(s) { public void emitHTML(String generatedHTML) { sb.append(generatedHTML); } public boolean isEmitHeading() { return isShowHeadings; } public boolean isEmitHeadingTypes() { return isShowHeadingTypes; } }; response.parse(); return sb.toString(); } catch (ParseException pe) { return "<br>" + ResponseToHTML.textToHTML(s); } } else { return "<br>" + ResponseToHTML.textToHTML(s).replace(" ", "&nbsp;"); } } private void outputTextUpdated() { styledText.setCaretOffset(styledText.getCharCount()); styledText.setSelection(styledText.getCaretOffset(), styledText.getCaretOffset()); } private void outputHtmlUpdated() { browser.scrollToBottom(); } private void outputUpdated() { outputTextUpdated(); outputHtmlUpdated(); } /** Record text responses. */ private void responseText(String s, Color color) { outputPlain(s + '\n', color); } private void response(String msg, String htmlClass, Color colour, boolean bold) { String msgPrefixTag; String msgSuffixTag; if (bold) { msgPrefixTag = "<b>"; msgSuffixTag = "</b>"; } else { msgPrefixTag = ""; msgSuffixTag = ""; } outputHTML("<div class=\"" + htmlClass + "\">" + msgPrefixTag + getResponseFormatted(msg, false) + msgSuffixTag + "</div>"); responseText("\n" + msg, colour); outputUpdated(); } /** Handle a received line of 'good' content. */ private void goodResponse(String s) { response(s, "ok", green, false); } /** Handle a received line of 'warning' content. */ private void warningResponse(String s) { response(s, "warn", yellow, true); } /** Handle user entry. */ private void userResponse(String s) { response(s, "user", grey, true); } /** Handle a received line of system notice. */ private void systemResponse(String s) { response(s, "note", blue, false); } /** Handle a received line of 'bad' content. */ void badResponse(String s) { response(s, "bad", red, true); } /** Handle a notice. */ private void noticeResponse(String s) { response(s, "notice", black, true); } private static class ErrorInformation { private int line; private int column; private String badToken; ErrorInformation(int line, int column, String badToken) { this.line = line; this.column = column; this.badToken = badToken; } int getLine() { return line; } int getColumn() { return column; } String getBadToken() { return badToken; } public String toString() { String output = "Error in line " + line; if (column >= 0) output += ", column " + column; if (badToken != null) output += " near " + badToken; return output; } } private ErrorInformation parseErrorInformationFrom(String eInfo) { try { String badToken = null; String errorEncountered = "ERROR: Encountered "; if (eInfo.startsWith(errorEncountered)) { String atLineText = "at line "; int atLineTextPosition = eInfo.indexOf(atLineText); int lastBadTokenCharPosition = eInfo.lastIndexOf('"', atLineTextPosition); if (lastBadTokenCharPosition >= 0) badToken = eInfo.substring(errorEncountered.length() + 1, lastBadTokenCharPosition); } String lineText = "line "; int locatorStart = eInfo.toLowerCase().indexOf(lineText); if (locatorStart >= 0) { int line = 0; int column = 0; eInfo = eInfo.substring(locatorStart + lineText.length()); int nonNumberPosition = 0; while (nonNumberPosition < eInfo.length() && Character.isDigit(eInfo.charAt(nonNumberPosition))) nonNumberPosition++; String lineString = eInfo.substring(0, nonNumberPosition); try { line = Integer.parseInt(lineString); } catch (NumberFormatException nfe) { return null; } int commaPosition = eInfo.indexOf(','); if (commaPosition > 0) { eInfo = eInfo.substring(commaPosition + 2); String columnText = "column "; if (eInfo.startsWith(columnText)) { eInfo = eInfo.substring(columnText.length()); int endOfNumber = 0; while (endOfNumber < eInfo.length() && Character.isDigit(eInfo.charAt(endOfNumber))) endOfNumber++; String columnString = ""; if (endOfNumber > 0 && endOfNumber < eInfo.length()) columnString = eInfo.substring(0, endOfNumber); else columnString = eInfo; try { column = Integer.parseInt(columnString); } catch (NumberFormatException nfe) { return null; } String nearText = "near "; int nearTextPosition = eInfo.indexOf(nearText, endOfNumber); if (nearTextPosition > 0) { int lastQuotePosition = eInfo.lastIndexOf('\''); badToken = eInfo.substring(nearTextPosition + nearText.length() + 1, lastQuotePosition); } return new ErrorInformation(line, column, badToken); } else return new ErrorInformation(line, -1, badToken); } else return new ErrorInformation(line, -1, badToken); } } catch (Throwable t) { System.out.println("PanelCommandline: unable to parse " + eInfo + " due to " + t); t.printStackTrace(); } return null; } }
package com.battleejb.entities; import java.io.Serializable; import javax.persistence.*; /** * The persistent class for the Text database table. * @author rtkachuk * @author Lukashchuk Ivan * */ @Entity @NamedNativeQueries({ @NamedNativeQuery(name = "User.findEnTextByKey", query="SELECT `valueEn` FROM `Text` WHERE `keyval`=:keyval", resultSetMapping="valueEn"), @NamedNativeQuery(name = "User.findNlTextByKey", query="SELECT `valueNl` FROM `Text` WHERE `keyval`=:keyval", resultSetMapping="valueNl") }) @SqlResultSetMappings({ @SqlResultSetMapping(name = "valueEn", columns ={@ColumnResult(name = "valueEn") }), @SqlResultSetMapping(name = "valueNl", columns ={@ColumnResult(name = "valueNl") }) }) @NamedQueries({ @NamedQuery(name = "Text.findByKey", query = "SELECT t FROM Text t WHERE t.keyval = :keyval") }) public class Text implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; private Integer keyval; private String valueEn; private String valueNl; @Transient private Long num; @Transient private Boolean viewOnEdit; public Text() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getKeyval() { return keyval; } public void setKey(Integer keyval) { this.keyval = keyval; } public String getValueEn() { return valueEn; } public void setValueEn(String valueEn) { this.valueEn = valueEn; } public String getValueNl() { return valueNl; } public void setValueNl(String valueNl) { this.valueNl = valueNl; } public Long getNum() { return num; } public void setNum(Long num) { this.num = num; } public Boolean getViewOnEdit() { return viewOnEdit; } public void setViewOnEdit(Boolean viewOnEdit) { this.viewOnEdit = viewOnEdit; } public void setKeyval(Integer keyval) { this.keyval = keyval; } }
package armstrong; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Random; import java.util.Set; import org.hibernate.search.analyzer.Discriminator; //import com.sun.xml.internal.bind.v2.runtime.Location; import battlecode.common.*; public class RobotPlayer{ static Random rnd; static RobotController rc; static int[] tryDirections = {0,-1,1,-2,2}; static RobotType[] buildList = new RobotType[]{RobotType.GUARD,RobotType.TURRET}; static RobotType lastBuilt = RobotType.ARCHON; static Set<Integer> marriedScouts = new HashSet<>(); static Set<Integer> marriedTurrets = new HashSet<>(); static int husbandTurretID = -1; static boolean broadcastNextTurn = false; static int[] toBroadcastNextTurn = new int[3]; static int MESSAGE_MARRIAGE = 0; static int MESSAGE_ENEMY = 1; public static void run(RobotController rcIn){ rc = rcIn; rnd = new Random(rc.getID()); while(true){ try{ if(rc.getType()==RobotType.ARCHON){ archonCode(); }else if(rc.getType()==RobotType.TURRET){ turretCode(); }else if(rc.getType()==RobotType.TTM){ ttmCode(); }else if(rc.getType()==RobotType.GUARD){ guardCode(); }else if(rc.getType()==RobotType.SOLDIER){ guardCode(); }else if(rc.getType()==RobotType.SCOUT){ scoutCode(); } }catch(Exception e){ e.printStackTrace(); } Clock.yield(); } } private static MapLocation getTurretEnemy(Signal s){ int[] message = s.getMessage(); if(s.getTeam().equals(rc.getTeam()) && message != null && s.getLocation().distanceSquaredTo(rc.getLocation()) <= 2){ if(message[0] == MESSAGE_ENEMY){ return decodeLocation(message[1]); } } return null; } private static void turretCode() throws GameActionException { RobotInfo[] visibleEnemyArray = rc.senseHostileRobots(rc.getLocation(), 1000000); Signal[] incomingSignals = rc.emptySignalQueue(); MapLocation[] enemyArray = combineThings(visibleEnemyArray,incomingSignals); for(Signal s: incomingSignals){ MapLocation enemyLocation = getTurretEnemy(s); if(enemyLocation != null && rc.canAttackLocation(enemyLocation)){ rc.attackLocation(enemyLocation); } } if(enemyArray.length>0){ if(rc.isWeaponReady()){ //look for adjacent enemies to attack for(MapLocation oneEnemy:enemyArray){ if(rc.canAttackLocation(oneEnemy)){ rc.setIndicatorString(0,"trying to attack"); rc.attackLocation(oneEnemy); break; } } } //could not find any enemies adjacent to attack //try to move toward them if(rc.isCoreReady()){ rc.pack(); } }else{//there are no enemies nearby //check to see if we are in the way of friends //we are obstructing them if(rc.isCoreReady()){ //TODO Fix logic here choose the condition for packing //rc.pack(); RobotInfo[] nearbyFriends = rc.senseNearbyRobots(2, rc.getTeam()); if(nearbyFriends.length>3){ rc.pack(); } } } } private static int encodeLocation(MapLocation lc){ final int maxOffset = 16000; final int range = 2 * maxOffset; int x = lc.x; int y = lc.y; x += maxOffset; y += maxOffset; return (range + 1) * x + y; } private static MapLocation decodeLocation(int code){ final int maxOffset = 16000; final int range = 2 * maxOffset; int x = code/(range + 1); int y = code%(range + 1); return new MapLocation(x, y); } private static void ttmCode() throws GameActionException { RobotInfo[] visibleEnemyArray = rc.senseHostileRobots(rc.getLocation(), 1000000); Signal[] incomingSignals = rc.emptySignalQueue(); MapLocation[] enemyArray = combineThings(visibleEnemyArray,incomingSignals); if(enemyArray.length>0){ rc.unpack(); //could not find any enemies adjacent to attack //try to move toward them if(rc.isCoreReady()){ MapLocation goal = enemyArray[0]; Direction toEnemy = rc.getLocation().directionTo(goal); tryToMove(toEnemy); } }else{//there are no enemies nearby //check to see if we are in the way of friends //we are obstructing them if(rc.isCoreReady()){ RobotInfo[] nearbyFriends = rc.senseNearbyRobots(2, rc.getTeam()); if(nearbyFriends.length>3){ Direction away = randomDirection(); tryToMove(away); }else{//maybe a friend is in need! RobotInfo[] alliesToHelp = rc.senseNearbyRobots(1000000,rc.getTeam()); MapLocation weakestOne = findWeakest(alliesToHelp); if(weakestOne!=null){//found a friend most in need Direction towardFriend = rc.getLocation().directionTo(weakestOne); tryToMove(towardFriend); } } } } } private static void guardCode() throws GameActionException { RobotInfo[] enemyArray = rc.senseHostileRobots(rc.getLocation(), 1000000); if(enemyArray.length>0){ if(rc.isWeaponReady()){ //look for adjacent enemies to attack for(RobotInfo oneEnemy:enemyArray){ if(rc.canAttackLocation(oneEnemy.location)){ rc.setIndicatorString(0,"trying to attack"); rc.attackLocation(oneEnemy.location); break; } } } //could not find any enemies adjacent to attack //try to move toward them if(rc.isCoreReady()){ MapLocation goal = enemyArray[0].location; Direction toEnemy = rc.getLocation().directionTo(goal); tryToMove(toEnemy); } }else{//there are no enemies nearby //check to see if we are in the way of friends //we are obstructing them if(rc.isCoreReady()){ RobotInfo[] nearbyFriends = rc.senseNearbyRobots(2, rc.getTeam()); if(nearbyFriends.length>3){ Direction away = randomDirection(); tryToMove(away); }else{//maybe a friend is in need! RobotInfo[] alliesToHelp = rc.senseNearbyRobots(1000000,rc.getTeam()); MapLocation weakestOne = findWeakest(alliesToHelp); if(weakestOne!=null){//found a friend most in need Direction towardFriend = rc.getLocation().directionTo(weakestOne); tryToMove(towardFriend); } } } } } private static MapLocation[] combineThings(RobotInfo[] visibleEnemyArray, Signal[] incomingSignals) { ArrayList<MapLocation> attackableEnemyArray = new ArrayList<MapLocation>(); for(RobotInfo r:visibleEnemyArray){ attackableEnemyArray.add(r.location); } for(Signal s:incomingSignals){ if(s.getTeam()==rc.getTeam().opponent()){ MapLocation enemySignalLocation = s.getLocation(); int distanceToSignalingEnemy = rc.getLocation().distanceSquaredTo(enemySignalLocation); if(distanceToSignalingEnemy<=rc.getType().attackRadiusSquared){ attackableEnemyArray.add(enemySignalLocation); } } } MapLocation[] finishedArray = new MapLocation[attackableEnemyArray.size()]; for(int i=0;i<attackableEnemyArray.size();i++){ finishedArray[i]=attackableEnemyArray.get(i); } return finishedArray; } public static void tryToMove(Direction forward) throws GameActionException{ if(rc.isCoreReady()){ for(int deltaD:tryDirections){ Direction maybeForward = Direction.values()[(forward.ordinal()+deltaD+8)%8]; if(rc.canMove(maybeForward)){ rc.move(maybeForward); return; } } if(rc.getType().canClearRubble()){ //failed to move, look to clear rubble MapLocation ahead = rc.getLocation().add(forward); if(rc.senseRubble(ahead)>=GameConstants.RUBBLE_OBSTRUCTION_THRESH){ rc.clearRubble(forward); } } } } private static RobotInfo findWeakestRobot(RobotInfo[] listOfRobots){ double weakestSoFar = 0; RobotInfo weakest = null; for(RobotInfo r:listOfRobots){ double weakness = r.maxHealth-r.health; //double weakness = (r.maxHealth-r.health)*1.0/r.maxHealth; if(weakness>weakestSoFar){ weakest = r; weakestSoFar=weakness; } } return weakest; } private static MapLocation findWeakest(RobotInfo[] listOfRobots){ double weakestSoFar = 0; MapLocation weakestLocation = null; for(RobotInfo r:listOfRobots){ double weakness = r.maxHealth-r.health; //double weakness = (r.maxHealth-r.health)*1.0/r.maxHealth; if(weakness>weakestSoFar){ weakestLocation = r.location; weakestSoFar=weakness; } } return weakestLocation; } //Gets an unmarried turret or scout private static RobotInfo getLonelyRobot(RobotInfo[] robots,RobotType targetType,Set<Integer> married){ for(RobotInfo robot: robots){ if(robot.type == targetType && !married.contains(robot.ID)){ return robot; } } return null; } //Checks private static int getHusbandTurretID(Signal s){ if(s.getTeam().equals(rc.getTeam()) && s.getMessage() != null){ if(s.getMessage()[0] == rc.getID()){ return s.getMessage()[1]; } } return -1; } private static void scoutCode() throws GameActionException{ RobotInfo[] visibleEnemyArray = rc.senseHostileRobots(rc.getLocation(), 1000000); Signal[] incomingSignals = rc.emptySignalQueue(); //MapLocation[] enemyArray = combineThings(visibleEnemyArray,incomingSignals); for(Signal s: incomingSignals){ husbandTurretID = getHusbandTurretID(s); if(husbandTurretID != -1){ break; } } if(husbandTurretID != -1){ rc.setIndicatorString(0, "My husband ID is" + husbandTurretID); } else{ rc.setIndicatorString(1, "I am a scout with no husband"); } //TODO can be improved by using previous information of the location of the husband RobotInfo[] visibleAlliesArray = rc.senseNearbyRobots(); RobotInfo husband = null; for(int i = 0; i < visibleAlliesArray.length; i++){ if(visibleAlliesArray[i].ID == husbandTurretID){ husband = visibleAlliesArray[i]; } } RobotInfo targetRobot = findWeakestRobot(visibleEnemyArray); MapLocation target = null; if(targetRobot != null){ target = targetRobot.location; rc.setIndicatorString(2, "Target is at location (" + target.x + "," + target.y + ")"); rc.setIndicatorString(3, "Target is of type:" + targetRobot.type); } if(husband != null){ Direction toHusband = rc.getLocation().directionTo(husband.location); if(rc.getLocation().distanceSquaredTo(husband.location)<= 2){ if(target != null){ rc.broadcastMessageSignal(MESSAGE_ENEMY, encodeLocation(target),rc.getLocation().distanceSquaredTo(husband.location)); } }else{ if(rc.isCoreReady()){ tryToMove(toHusband); } } } } private static RobotInfo[] getArray(ArrayList<RobotInfo> selectedList){ RobotInfo[] selectedArray = new RobotInfo[selectedList.size()]; for(int i = 0;i < selectedList.size();i ++){ selectedArray[i] = selectedList.get(i); } return selectedArray; } private static void archonCode() throws GameActionException { if(broadcastNextTurn){ rc.broadcastMessageSignal(toBroadcastNextTurn[0], toBroadcastNextTurn[1], toBroadcastNextTurn[2]); broadcastNextTurn = false; } if(rc.isCoreReady()){ Direction randomDir = randomDirection(); boolean backupTurret = false; RobotInfo choosenTurret = null; RobotType toBuild; if(lastBuilt == RobotType.TURRET){ //We can improve on this //for instance we can combine the two sense statements we have. RobotInfo[] alliesNearBy = rc.senseNearbyRobots(rc.getType().sensorRadiusSquared,rc.getTeam()); //turretsNearBy = filterRobotsbyType(alliesNearBy, targetType) choosenTurret = getLonelyRobot(alliesNearBy,RobotType.TURRET,marriedTurrets); if(choosenTurret != null){ toBuild = RobotType.SCOUT; backupTurret = true; }else{ toBuild = buildList[rnd.nextInt(buildList.length)]; } }else{ toBuild = buildList[rnd.nextInt(buildList.length)]; } if(rc.getTeamParts()>100){ if(rc.canBuild(randomDir, toBuild)){ rc.build(randomDir,toBuild); lastBuilt = toBuild; if(backupTurret){ RobotInfo[] alliesVeryNear = rc.senseNearbyRobots(2,rc.getTeam()); RobotInfo choosenScout = getLonelyRobot(alliesVeryNear, RobotType.SCOUT, marriedScouts); if(choosenTurret == null){ rc.disintegrate(); } //rc.broadcastMessageSignal(choosenScout.ID,choosenTurret.ID, choosenTurret.location.distanceSquaredTo(rc.getLocation())); toBroadcastNextTurn[0] = choosenScout.ID; toBroadcastNextTurn[1] = choosenTurret.ID; toBroadcastNextTurn[2] = 8; broadcastNextTurn = true; marriedTurrets.add(choosenTurret.ID); marriedScouts.add(choosenScout.ID); } return; } } RobotInfo[] alliesToHelp = rc.senseNearbyRobots(RobotType.ARCHON.attackRadiusSquared,rc.getTeam()); MapLocation weakestOne = findWeakest(alliesToHelp); if(weakestOne!=null){ rc.repair(weakestOne); return; } } } private static Direction randomDirection() { return Direction.values()[(int)(rnd.nextDouble()*8)]; } //filters robots by type private static RobotInfo[] filterRobotsbyType(RobotInfo[] robots, RobotType targetType){ ArrayList<RobotInfo> selectedList = new ArrayList<>(); for(RobotInfo r:robots){ if(r.type.equals(targetType)){ selectedList.add(r); } } return getArray(selectedList); } }
package proj.me.bitframe.helper; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.LayerDrawable; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.Uri; import android.os.Build; import android.text.TextUtils; import android.util.Log; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.webkit.MimeTypeMap; import android.widget.ImageView; import android.widget.Toast; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import proj.me.bitframe.R; import proj.me.bitframe.exceptions.FrameException; public class Utils { /** * Convert Dp to Pixel * dp-pixel */ public static int dpToPx(float dp, Resources resources){ float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, resources.getDisplayMetrics()); return (int) px; } public static int spToPx(float sp, Resources resources){ float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, resources.getDisplayMetrics()); return (int) px; } private static final String TAG = "Bit_Frame"; public static void logMessage(String message){ Log.i(TAG, message); } public static void logVerbose(String message){ Log.v(TAG, message); } public static void showToast(Context context,String message){ Toast.makeText(context, message, Toast.LENGTH_SHORT).show(); } public static String formatMessage(String message, Object ... values){ return String.format(message, values); } public static ColorPallet getColorPallet(){ return ColorPallet.VIBRANT; } /** * for max 6 colors it'll do mixing at a time * it's simply taking average of the colors * */ private static int getMixedColor(int ... colors){ //for 1 //return same color //for 2 //add colors then right shift them with two to find average //for 3 //add all then right shift by 1 then multiply by 2/3 by shift/add 101010... //for 4 add them then right shift 2 //for 5 add them then divide by 10 then multiply by 2 //for 6 add them all then divide by 3 then divide by 2 int finalColor = 0; switch(colors.length){ case 1: return colors[0]; case 2: return (colors[0] + colors[1]) >> 1; case 3: int number = colors[0] + colors[1] + colors[2]; int resultInt = number >> 1; int v = number;int n = 1; //calculating leading zeros if(v >>> 16 == 0){ n+=16; v <<= 16;} if(v >>> 24 == 0){ n+=8; v <<= 8; } if(v >>> 28 == 0){ n+=4; v <<= 4; } if(v >>> 30 == 0){ n+=2; v <<= 2; } n-=v >>> 31; int bitLength = 32 - n; finalColor = 0; int i = 1; while(bitLength > 0){ //shifting to left as 1, 3, 5..... finalColor += resultInt << i; bitLength i+=2; } bitLength = 32 - n; int bits = bitLength * 2; int val = 1 << (bits - 1); if((val & finalColor) != 0){ finalColor = finalColor >> bits; return finalColor + 1;} else return finalColor >> bits; case 4: return (colors[0] + colors[1] + colors[2] + colors[3]) >> 2; case 5: finalColor = colors[0] + colors[1] + colors[2] + colors[3] + colors[4]; int q = (finalColor >> 1) + (finalColor >> 2); q = q + (q >> 4); q = q + (q >> 8); q = q + (q >> 16); q = q >> 3; int r = finalColor - (((q << 2) + q) << 1); return (q + ((r > 9) ? 1 : 0)) << 1; case 6: finalColor = getMixedColor(colors[0]+colors[1]+colors[2]+colors[3], colors[4], colors[5]); return finalColor >> 1; } return finalColor; } public static int getMixedArgbColor(int ... colors) throws FrameException{ if(colors == null) throw new IllegalArgumentException("can not mix empty colors"); if(colors.length > 6) throw new IllegalArgumentException("only support maximum six color mixing, found : "+colors.length); int mixedAlpha = 0; int mixedRed = 0; int mixedGreen = 0; int mixedBlue = 0; switch(colors.length){ case 1: mixedAlpha = getMixedColor(colors[0] >>> 24); mixedRed = getMixedColor(colors[0] >> 16 & 0xFF); mixedGreen = getMixedColor(colors[0] >> 8 & 0xFF); mixedBlue = getMixedColor(colors[0] & 0xFF); break; case 2: mixedAlpha = getMixedColor(colors[0] >>> 24, colors[1] >>> 24); mixedRed = getMixedColor(colors[0] >> 16 & 0xFF, colors[1] >> 16 & 0xFF); mixedGreen = getMixedColor(colors[0] >> 8 & 0xFF, colors[1] >> 8 & 0xFF); mixedBlue = getMixedColor(colors[0] & 0xFF, colors[1] & 0xFF); break; case 3: mixedAlpha = getMixedColor(colors[0] >>> 24, colors[1] >>> 24, colors[2] >>> 24); mixedRed = getMixedColor(colors[0] >> 16 & 0xFF, colors[1] >> 16 & 0xFF, colors[2] >> 16 & 0xFF); mixedGreen = getMixedColor(colors[0] >> 8 & 0xFF, colors[1] >> 8 & 0xFF, colors[2] >> 8 & 0xFF); mixedBlue = getMixedColor(colors[0] & 0xFF, colors[1] & 0xFF, colors[2] & 0xFF); break; case 4: mixedAlpha = getMixedColor(colors[0] >>> 24, colors[1] >>> 24, colors[2] >>> 24, colors[3] >>> 24); mixedRed = getMixedColor(colors[0] >> 16 & 0xFF, colors[1] >> 16 & 0xFF, colors[2] >> 16 & 0xFF, colors[3] >> 16 & 0xFF); mixedGreen = getMixedColor(colors[0] >> 8 & 0xFF, colors[1] >> 8 & 0xFF, colors[2] >> 8 & 0xFF, colors[3] >> 8 & 0xFF); mixedBlue = getMixedColor(colors[0] & 0xFF, colors[1] & 0xFF, colors[2] & 0xFF, colors[3] & 0xFF); break; case 5: mixedAlpha = getMixedColor(colors[0] >>> 24, colors[1] >>> 24, colors[2] >>> 24, colors[3] >>> 24, colors[4] >>> 24); mixedRed = getMixedColor(colors[0] >> 16 & 0xFF, colors[1] >> 16 & 0xFF, colors[2] >> 16 & 0xFF, colors[3] >> 16 & 0xFF, colors[4] >> 16 & 0xFF); mixedGreen = getMixedColor(colors[0] >> 8 & 0xFF, colors[1] >> 8 & 0xFF, colors[2] >> 8 & 0xFF, colors[3] >> 8 & 0xFF, colors[4] >> 8 & 0xFF); mixedBlue = getMixedColor(colors[0] & 0xFF, colors[1] & 0xFF, colors[2] & 0xFF, colors[3] & 0xFF, colors[4] & 0xFF); break; case 6: mixedAlpha = getMixedColor(colors[0] >>> 24, colors[1] >>> 24, colors[2] >>> 24, colors[3] >>> 24, colors[4] >>> 24, colors[5] >>> 24); mixedRed = getMixedColor(colors[0] >> 16 & 0xFF, colors[1] >> 16 & 0xFF, colors[2] >> 16 & 0xFF, colors[3] >> 16 & 0xFF, colors[4] >> 16 & 0xFF, colors[5] >> 16 & 0xFF); mixedGreen = getMixedColor(colors[0] >> 8 & 0xFF, colors[1] >> 8 & 0xFF, colors[2] >> 8 & 0xFF, colors[3] >> 8 & 0xFF, colors[4] >> 8 & 0xFF, colors[5] >> 8 & 0xFF); mixedBlue = getMixedColor(colors[0] & 0xFF, colors[1] & 0xFF, colors[2] & 0xFF, colors[3] & 0xFF, colors[4] & 0xFF, colors[5] & 0xFF); break; } return Color.argb(mixedAlpha, mixedRed, mixedGreen, mixedBlue); } public static int getInverseColor(int color){ float hsv[] = new float[3]; Color.colorToHSV(color, hsv); //inverting color float hue = hsv[2]; hue = (hue + 180) % 360; hsv[2] = hue; return Color.HSVToColor(hsv); } public static int getColorWithTransparency(int color, int transparencyPercent){ int alpha = 235 * transparencyPercent / 100; return Color.argb(alpha, color >> 16 & 0xFF, color >> 8 & 0xFF, color & 0xFF); } *//*public static final float MIN_RATIO = 0.3f; public static final float MAX_RATIO = 0.7f;*//* /* public static final int COMMENT_TRANSPARENCY_PERCENT = 70; public static float MIN_WIDTH = 300; public static float MIN_HIGHT = 300; public static float MAX_WIDTH = 700; public static float MAX_HEIGHT = 900; //show be less than or equal to 4 for now public static int MAX_IMAGES_TO_SHOW = 4; public static final float MIN_ADD_RATIO = 0.25f; //for add in layout public static boolean shouldShowAddInLayout(){ return false; } //for comments public static boolean shouldShowComments(){ return false; } public static boolean showShowDivider(){ return true; } public static ColorCombination getColorCombo(){ return ColorCombination.VIBRANT_TO_MUTED; } //for image public static int getErrorDrawableId(){ return 0; } public static ImageView.ScaleType getImageScaleType(){ return ImageView.ScaleType.CENTER_CROP; }*/ public static BeanBitmapResult getScaledResult(Bitmap bitmap, int reqWidth, int reqHeight) throws FrameException{ if(bitmap == null || reqWidth == 0 || reqHeight == 0) throw new IllegalArgumentException("scaling can not perform on invalid arguments"); BeanBitmapResult beanBitmapResult = new BeanBitmapResult(); beanBitmapResult.setHeight(bitmap.getHeight()); beanBitmapResult.setWidth(bitmap.getWidth()); int inSampleSize = 1; if(beanBitmapResult.getHeight() > reqHeight || beanBitmapResult.getWidth() > reqWidth){ final int heightRatio = Math.round((float) beanBitmapResult.getHeight() / (float) reqHeight); final int widthRatio = Math.round((float) beanBitmapResult.getWidth() / (float) reqWidth); inSampleSize = (heightRatio <= widthRatio && beanBitmapResult.getHeight() > reqHeight) ? heightRatio : (widthRatio <= heightRatio && beanBitmapResult.getWidth() > reqWidth) ? widthRatio : 1; } if(inSampleSize == 0) inSampleSize = 1; Bitmap btmp = Bitmap.createScaledBitmap(bitmap, beanBitmapResult.getWidth()/inSampleSize, beanBitmapResult.getHeight()/inSampleSize, false); beanBitmapResult.setBitmap(btmp); Utils.logMessage("width : " + reqWidth+" height : "+reqHeight); Utils.logMessage("width : " + beanBitmapResult.getWidth()+" height : "+beanBitmapResult.getHeight()); Utils.logMessage("width : " + beanBitmapResult.getWidth()/inSampleSize+" height : "+beanBitmapResult.getHeight()/inSampleSize); return beanBitmapResult; } public static Bitmap getScaledBitmap(Bitmap bitmap, int reqWidth, int reqHeight) throws FrameException{ if(bitmap == null || reqWidth == 0 || reqHeight == 0) throw new IllegalArgumentException("scaling can not perform on invalid arguments"); int inSampleSize = 1; final int height = bitmap.getHeight(); final int width = bitmap.getWidth(); if(height > reqHeight || width > reqWidth){ final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); inSampleSize = (heightRatio <= widthRatio && height > reqHeight) ? heightRatio : (widthRatio <= heightRatio && width > reqWidth) ? widthRatio : 1; } if(inSampleSize == 0) inSampleSize = 1; Bitmap btmp = Bitmap.createScaledBitmap(bitmap, width/inSampleSize, height/inSampleSize, false); if(btmp != bitmap) bitmap.recycle(); Utils.logMessage("width : " + reqWidth+" height : "+reqHeight); Utils.logMessage("width : " + width+" height : "+height); Utils.logMessage("width : " + width/inSampleSize+" height : "+height/inSampleSize); return btmp; } public static BeanResult decodeBitmapFromPath(int reqWidth, int reqHeight, String imagePath, Context context) throws FrameException{ if(reqWidth == 0 || reqHeight == 0 || TextUtils.isEmpty(imagePath) || context == null) throw new IllegalArgumentException("Failed to decode bitmap from path, invalid arguments"); boolean hasExtension = !TextUtils.isEmpty(MimeTypeMap.getFileExtensionFromUrl(imagePath)); if(hasExtension && imagePath.contains(".")) imagePath=imagePath.substring(0,imagePath.lastIndexOf('.')); Uri fileUri = Uri.parse(imagePath); BitmapFactory.Options options=new BitmapFactory.Options(); options.inJustDecodeBounds=true; InputStream inputStream = null; try { inputStream = context.getContentResolver().openInputStream(fileUri); BitmapFactory.decodeStream(inputStream, null, options); inputStream.close(); BeanResult beanResult = calculateInSmapleSize(options, reqWidth, reqHeight); options.inSampleSize = beanResult.getInSampleSize(); options.inJustDecodeBounds = false; inputStream = context.getContentResolver().openInputStream(fileUri); beanResult.setBitmap(BitmapFactory.decodeStream(inputStream, null, options)); inputStream.close(); Utils.logMessage("width : " + reqWidth+" height : "+reqHeight); Utils.logMessage("width : " + beanResult.getWidth()+" height : "+beanResult.getHeight()); Utils.logMessage("width : " + options.outWidth+" height : "+options.outHeight); return beanResult; } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); if(inputStream != null) { try { inputStream.close(); throw new FrameException("Could not found file on path : "+imagePath, e); } catch (IOException e1) { e1.printStackTrace(); throw new FrameException("Could not close stream", e1); } } return null; } catch (IOException e) { e.printStackTrace(); if(inputStream != null) { try { inputStream.close(); throw new FrameException("could not decode file : "+imagePath, e); } catch (IOException e1) { e1.printStackTrace(); throw new FrameException("could not close stream", e1); } } return null; } } private static BeanResult calculateInSmapleSize(BitmapFactory.Options options, int reqWidth, int reqHeight){ BeanResult beanResult = new BeanResult(); final int width = options.outWidth; final int height = options.outHeight; int inSampleSize = 1; beanResult.setHeight(height); beanResult.setWidth(width); if(height > reqHeight || width > reqWidth){ /*final int halfHeight = height / 2; final int halfWidth = width / 2; while((halfHeight / inSampleSize > reqHeight) && (halfWidth / inSampleSize) > reqWidth){ inSampleSize *= 2; }*/ final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; beanResult.setInSampleSize(inSampleSize); } return beanResult; } public static void unbindDrawables(View view, boolean unbindItself, boolean shouldRecycleBitmaps){ if(view == null) return; if(unbindItself && view.getBackground() != null) view.getBackground().setCallback(null); if(view instanceof ImageView && shouldRecycleBitmaps) { ImageView imageView = ((ImageView)view); if(imageView.getBackground() != null) imageView.getBackground().setCallback(null); Drawable drawable = imageView.getDrawable(); if(drawable instanceof BitmapDrawable) { Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap(); if(bitmap != null && !bitmap.isRecycled()) bitmap.recycle(); bitmap = null; }else if(drawable instanceof LayerDrawable){ Bitmap bitmap = ((BitmapDrawable)((LayerDrawable)drawable).getDrawable(0)).getBitmap(); if(bitmap != null && !bitmap.isRecycled()) bitmap.recycle(); bitmap = null; } imageView.setImageBitmap(null); imageView.setImageDrawable(null); imageView.setImageResource(0); } if(view instanceof ViewGroup){ for(int i = 0;i<((ViewGroup)view).getChildCount();i++) unbindDrawables(((ViewGroup)view).getChildAt(i), true, shouldRecycleBitmaps); try{ ((ViewGroup)view).removeAllViews(); }catch(UnsupportedOperationException e){} if(unbindItself) view.setBackgroundResource(0); } } public static boolean hasNetwork(Context context){ ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo(); return activeNetwork != null && activeNetwork.isConnectedOrConnecting(); } public static boolean isLocalPath(String imagePath){ if(TextUtils.isEmpty(imagePath)) return false; Uri uri = Uri.parse(imagePath); return (uri != null && uri.getScheme() != null) && (uri.getScheme().equals("content") || uri.getScheme().equals("file")); } public static int getVersionColor(Context context, int colorId){ if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) return context.getResources().getColor(colorId, context.getTheme()); else return context.getResources().getColor(colorId); } public static Drawable getVersionDrawable(Context context, int drawableId){ if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) return context.getResources().getDrawable(drawableId, context.getTheme()); else return context.getResources().getDrawable(drawableId); } }
package edu.umd.cs.findbugs.bluej.test; import java.awt.event.ActionEvent; import java.util.HashMap; import java.util.Map; import javax.swing.AbstractAction; import javax.swing.JMenuItem; import javax.swing.JCheckBoxMenuItem; import javax.swing.JOptionPane; import bluej.extensions.BClass; import bluej.extensions.BPackage; import bluej.extensions.BProject; import bluej.extensions.BlueJ; import bluej.extensions.ExtensionException; import bluej.extensions.MenuGenerator; import bluej.extensions.ProjectNotOpenException; public class MenuBuilder extends MenuGenerator { private BlueJ bluej; private Map<BProject, Boolean> isRunning = new HashMap<BProject, Boolean>(); public MenuBuilder(BlueJ bluej) { this.bluej = bluej; } /** * @see bluej.extensions.MenuGenerator#getToolsMenuItem(bluej.extensions.BPackage) */ @Override public JMenuItem getToolsMenuItem(BPackage pckg) { //JCheckBoxMenuItem result = new JCheckBoxMenuItem("CheckBox Something"); try { JCheckBoxMenuItem result = new JCheckBoxMenuItem(new CheckBoxMenuAction(pckg.getProject())); result.setText("CheckBox Something"); return result; } catch (ProjectNotOpenException e) { Log.recordBug(e); return null; } } /** * Called when the menu is about to be displayed. If and only if we're enabled on * this project, make sure the menu item is checked. (If we've never seen this project * before, start it off checked.) */ @Override public void notifyPostToolsMenu(BPackage pckg, JMenuItem menu) { try { BProject project = pckg.getProject(); if (!isRunning.containsKey(project)) isRunning.put(project, true); menu.setSelected(isRunning.get(project)); } catch (ProjectNotOpenException notGonnaHappen) { JOptionPane.showMessageDialog(null, "Oh crap!"); return; } } @SuppressWarnings("serial") class CheckBoxMenuAction extends AbstractAction { private BProject project; public CheckBoxMenuAction(BProject project) { this.project = project; } public void actionPerformed(ActionEvent evt) { isRunning.put(project, ((JCheckBoxMenuItem)evt.getSource()).isSelected()); } } @SuppressWarnings("serial") class MenuAction extends AbstractAction { /** * Called when our menu entry is clicked. Pop a dialog with a cheery * message, followed by a list of all classes in all packages in all * open projects. (Mostly to see how BlueJ handles weird class * structures. */ public void actionPerformed(ActionEvent evt) { try { StringBuilder result = new StringBuilder(); for (BProject i : bluej.getOpenProjects()) for (BPackage j : i.getPackages()) for (BClass k : j.getClasses()) { result.append(k.getName() + "\n"); for (Class l : k.getJavaClass() .getDeclaredClasses()) result.append(l.getName() + "\n"); } /* Old method: return everything that ends in .class */ // FilenameFilter filter = new FilenameFilter() // public boolean accept(File dir, String name) // return name.toLowerCase().endsWith(".class"); // for (BProject i : bluej.getOpenProjects()) // for (BPackage j : i.getPackages()) // for (File k : j.getDir().listFiles(filter)) // String className = k.getName().substring(0, k.getName().length() - ".class".length()); // result.append(className + "\n"); JOptionPane.showMessageDialog(null, "Hello, World!\n\nClasses:\n" + result.toString()); } /* ProjectNotOpenException, PackageNotFoundException, and * ClassNotFoundException are checked exceptions and must be caught, * although none of these should ever be thrown from this code, * since all objects returned by getOpenProjects(), getPackages(), * and getClasses() should be fine. */ catch (ExtensionException e) { StringBuilder msg = new StringBuilder(); msg.append(e.getClass().getName() + ": " + e.getMessage() + "\n"); for (StackTraceElement i : e.getStackTrace()) msg.append(i + "\n"); JOptionPane.showMessageDialog(null, msg); } } } }
package modules; import java.util.ArrayList; import java.util.Calendar; import java.util.Comparator; import java.util.Formatter; import java.util.GregorianCalendar; import java.util.List; import modules.admin.domain.Contact; import modules.admin.domain.DocumentNumber; import org.skyve.CORE; import org.skyve.EXT; import org.skyve.bizport.BizPortException; import org.skyve.bizport.BizPortWorkbook; import org.skyve.domain.Bean; import org.skyve.domain.ChildBean; import org.skyve.domain.PersistentBean; import org.skyve.domain.messages.DomainException; import org.skyve.domain.messages.Message; import org.skyve.domain.messages.ValidationException; import org.skyve.domain.types.DateOnly; import org.skyve.domain.types.Decimal2; import org.skyve.domain.types.Decimal5; import org.skyve.domain.types.converters.date.DD_MMM_YYYY; import org.skyve.metadata.MetaDataException; import org.skyve.metadata.customer.Customer; import org.skyve.metadata.model.Attribute; import org.skyve.metadata.model.document.Bizlet.DomainValue; import org.skyve.metadata.model.document.Document; import org.skyve.metadata.module.Module; import org.skyve.metadata.user.User; import org.skyve.persistence.DocumentQuery; import org.skyve.persistence.DocumentQuery.AggregateFunction; import org.skyve.persistence.Persistence; import org.skyve.util.Binder; import org.skyve.util.Time; import org.skyve.wildcat.bizport.StandardGenerator; import org.skyve.wildcat.bizport.StandardLoader; /** * Utility methods applicable across application modules. * <p> * This class is provided as part of WILDCAT * * @author robert.brown * */ public class ModulesUtil { /** comparator to allow sorting of domain values by code */ public static class DomainValueSortByCode implements Comparator<DomainValue> { @Override public int compare(DomainValue d1, DomainValue d2) { return d1.getCode().compareTo(d2.getCode()); } } /** comparator to allow sorting of domain values by description */ public static class DomainValueSortByDescription implements Comparator<DomainValue> { @Override public int compare(DomainValue d1, DomainValue d2) { return d1.getDescription().compareTo(d2.getDescription()); } } /** general types of time-based frequencies */ public static enum OccurenceFrequency { OneOff, EverySecond, EveryMinute, Hourly, Daily, Weekly, Fortnightly, Monthly, Quarterly, HalfYearly, Yearly, Irregularly, DuringHolidays, NotDuringHolidays, WeekDays, Weekends; } public static final List<DomainValue> OCCURRENCE_FREQUENCIES = new ArrayList<>(); static { OCCURRENCE_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Irregularly.toString())); OCCURRENCE_FREQUENCIES.add(new DomainValue(OccurenceFrequency.OneOff.toString())); OCCURRENCE_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Hourly.toString())); OCCURRENCE_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Daily.toString())); OCCURRENCE_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Weekly.toString())); OCCURRENCE_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Fortnightly.toString())); OCCURRENCE_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Monthly.toString())); OCCURRENCE_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Quarterly.toString())); OCCURRENCE_FREQUENCIES.add(new DomainValue(OccurenceFrequency.HalfYearly.toString())); OCCURRENCE_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Yearly.toString())); } /** subset of frequencies relevant for use as terms */ public static final List<DomainValue> TERM_FREQUENCIES = new ArrayList<>(); static { TERM_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Irregularly.toString())); TERM_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Weekly.toString())); TERM_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Fortnightly.toString())); TERM_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Monthly.toString())); TERM_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Quarterly.toString())); TERM_FREQUENCIES.add(new DomainValue(OccurenceFrequency.HalfYearly.toString())); TERM_FREQUENCIES.add(new DomainValue(OccurenceFrequency.Yearly.toString())); } /** normal days of the week */ public static enum DayOfWeek { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } public static final List<DomainValue> WEEK_DAYS = new ArrayList<>(); static { WEEK_DAYS.add(new DomainValue(DayOfWeek.Sunday.toString())); WEEK_DAYS.add(new DomainValue(DayOfWeek.Monday.toString())); WEEK_DAYS.add(new DomainValue(DayOfWeek.Tuesday.toString())); WEEK_DAYS.add(new DomainValue(DayOfWeek.Wednesday.toString())); WEEK_DAYS.add(new DomainValue(DayOfWeek.Thursday.toString())); WEEK_DAYS.add(new DomainValue(DayOfWeek.Friday.toString())); WEEK_DAYS.add(new DomainValue(DayOfWeek.Saturday.toString())); } /** * Returns a calendar day of the week * * @param weekDay * - the day of the week (DayOfWeek) * @return - the day of the week as a Calendar.day (int) */ public static final int dayOfWeekToCalendar(DayOfWeek weekDay) { int calendarDay = Calendar.MONDAY; if (weekDay.equals(DayOfWeek.Monday)) { calendarDay = Calendar.MONDAY; } if (weekDay.equals(DayOfWeek.Tuesday)) { calendarDay = Calendar.TUESDAY; } if (weekDay.equals(DayOfWeek.Wednesday)) { calendarDay = Calendar.WEDNESDAY; } if (weekDay.equals(DayOfWeek.Thursday)) { calendarDay = Calendar.THURSDAY; } if (weekDay.equals(DayOfWeek.Friday)) { calendarDay = Calendar.FRIDAY; } if (weekDay.equals(DayOfWeek.Saturday)) { calendarDay = Calendar.SATURDAY; } if (weekDay.equals(DayOfWeek.Sunday)) { calendarDay = Calendar.SUNDAY; } return calendarDay; } /** * Returns a day of the week from a Calendar day * * @param calendarDay * - the number of the day (int) * @return - the DayOfWeek (DayOfWeek) */ public static final DayOfWeek calendarToDayOfWeek(int calendarDay) { DayOfWeek weekDay = DayOfWeek.Monday; if (calendarDay == Calendar.MONDAY) { weekDay = DayOfWeek.Monday; } if (calendarDay == Calendar.TUESDAY) { weekDay = DayOfWeek.Tuesday; } if (calendarDay == Calendar.WEDNESDAY) { weekDay = DayOfWeek.Wednesday; } if (calendarDay == Calendar.THURSDAY) { weekDay = DayOfWeek.Thursday; } if (calendarDay == Calendar.FRIDAY) { weekDay = DayOfWeek.Friday; } if (calendarDay == Calendar.SATURDAY) { weekDay = DayOfWeek.Saturday; } if (calendarDay == Calendar.SUNDAY) { weekDay = DayOfWeek.Sunday; } return weekDay; } /** returns the number of days between day1 and day2 */ public static enum OccurrencePeriod { Seconds, Minutes, Hours, Days, Weeks, Months, Years } public static final List<DomainValue> OCCURRENCE_PERIODS = new ArrayList<>(); static { OCCURRENCE_PERIODS.add(new DomainValue(OccurrencePeriod.Seconds.toString())); OCCURRENCE_PERIODS.add(new DomainValue(OccurrencePeriod.Minutes.toString())); OCCURRENCE_PERIODS.add(new DomainValue(OccurrencePeriod.Hours.toString())); OCCURRENCE_PERIODS.add(new DomainValue(OccurrencePeriod.Days.toString())); OCCURRENCE_PERIODS.add(new DomainValue(OccurrencePeriod.Weeks.toString())); OCCURRENCE_PERIODS.add(new DomainValue(OccurrencePeriod.Months.toString())); OCCURRENCE_PERIODS.add(new DomainValue(OccurrencePeriod.Years.toString())); } /** * Returns the number of periods of specified frequency which occur in the * calendar year. * * @param frequency * - the specified frequency (OccurrenceFrequency) * @return - the number of times the specified frequency occurs in a * calendar year */ public static int annualFrequencyCount(OccurenceFrequency frequency) { int periodCount = 1; // default period Count if (frequency.equals(OccurenceFrequency.Daily)) { // estimated periodCount = 365; } else if (frequency.equals(OccurenceFrequency.Weekly)) { periodCount = 52; } else if (frequency.equals(OccurenceFrequency.Fortnightly)) { periodCount = 26; } else if (frequency.equals(OccurenceFrequency.Monthly)) { periodCount = 12; } else if (frequency.equals(OccurenceFrequency.Quarterly)) { periodCount = 4; } else if (frequency.equals(OccurenceFrequency.HalfYearly)) { periodCount = 2; } return periodCount; } /** * Returns the number of periods which occur in a calendar year. * * @param period * - the time period (OccurrencePeriod) * @return - the number of times the period occurs within a calendar year * (int) */ public static int annualPeriodCount(OccurrencePeriod period) { int periodCount = 1; // default period Count if (period.equals(OccurrencePeriod.Days)) { // estimated periodCount = 365; } else if (period.equals(OccurrencePeriod.Weeks)) { periodCount = 52; } else if (period.equals(OccurrencePeriod.Months)) { periodCount = 12; } else if (period.equals(OccurrencePeriod.Years)) { periodCount = 1; } return periodCount; } /** * Adds a time frequency to a given date. * * @param frequency * - the frequency to add * @param date * - the date to add to * @param numberOfFrequencies * - the number of frequencies to add * @return - the resulting date */ public static final DateOnly addFrequency(OccurenceFrequency frequency, DateOnly date, int numberOfFrequencies) { if (date != null) { if (frequency.equals(OccurenceFrequency.OneOff)) { return new DateOnly(date.getTime()); } DateOnly newDate = new DateOnly(date.getTime()); Calendar calendar = new GregorianCalendar(); calendar.setTime(newDate); calendar.setLenient(false); // NB clear() does not work in JDK 1.3.1 calendar.set(Calendar.MILLISECOND, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.HOUR_OF_DAY, 0); if (frequency.equals(OccurenceFrequency.Daily)) { calendar.add(Calendar.DATE, numberOfFrequencies); } else if (frequency.equals(OccurenceFrequency.Weekly)) { calendar.add(Calendar.DATE, (numberOfFrequencies * 7)); } else if (frequency.equals(OccurenceFrequency.Fortnightly)) { calendar.add(Calendar.DATE, (numberOfFrequencies * 14)); } else if (frequency.equals(OccurenceFrequency.Monthly)) { calendar.add(Calendar.MONTH, numberOfFrequencies); } else if (frequency.equals(OccurenceFrequency.Quarterly)) { calendar.add(Calendar.MONTH, (numberOfFrequencies * 3)); } else if (frequency.equals(OccurenceFrequency.HalfYearly)) { calendar.add(Calendar.MONTH, (numberOfFrequencies * 6)); } else if (frequency.equals(OccurenceFrequency.Yearly)) { calendar.add(Calendar.YEAR, numberOfFrequencies); } newDate.setTime(calendar.getTime().getTime()); return newDate; } return null; } /** * Returns the last day of the month in which the specified date occurs. * * @param date * - the specified date * @return - the date of the last day of the month in which the specified * date occurs */ public static DateOnly lastDayOfMonth(DateOnly date) { if (date != null) { DateOnly newDate = new DateOnly(date.getTime()); Calendar calendar = new GregorianCalendar(); calendar.setTime(newDate); calendar.setLenient(false); // NB clear() does not work in JDK 1.3.1 calendar.set(Calendar.MILLISECOND, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.HOUR_OF_DAY, 0); // last day of month is one day before 1st day of next month calendar.add(Calendar.MONTH, 1); calendar.set(Calendar.DATE, 1); newDate.setTime(calendar.getTime().getTime()); Time.addDays(newDate, -1); return newDate; } return null; } /** * Returns the last day of the year in which the specified date occurs. * * @param date * - the specified date * @return - the date of the last day of the year in which the specified * date occurs */ public static DateOnly lastDayOfYear(DateOnly date) { if (date != null) { DateOnly newDate = new DateOnly(date.getTime()); Calendar calendar = new GregorianCalendar(); calendar.setTime(newDate); calendar.setLenient(false); // NB clear() does not work in JDK 1.3.1 calendar.set(Calendar.MILLISECOND, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.HOUR_OF_DAY, 0); // last day of year is one day before 1st day of next year calendar.add(Calendar.YEAR, 1); calendar.set(Calendar.MONTH, 0); calendar.set(Calendar.DATE, 1); newDate.setTime(calendar.getTime().getTime()); Time.addDays(newDate, -1); return newDate; } return null; } /** * Returns the date of the first day of the month in which the specified * date occurs. * * @param date * - the specified date * @return - the date of the first day of that month */ @SuppressWarnings("deprecation") public static DateOnly firstDayOfMonth(DateOnly date) { Calendar calendar = new GregorianCalendar(); calendar.setTime(date); calendar.setLenient(false); // NB clear() does not work in JDK 1.3.1 calendar.set(Calendar.MILLISECOND, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MONTH, date.getMonth()); calendar.set(Calendar.DATE, 1); date.setTime(calendar.getTime().getTime()); return date; } /** * Returns the date of the first day of the year in which the specified date * occurs. * * @param date * - the specified date * @return - the date of the first day of that year */ public static DateOnly firstDayOfYear(DateOnly date) { Calendar calendar = new GregorianCalendar(); calendar.setTime(date); calendar.setLenient(false); // NB clear() does not work in JDK 1.3.1 calendar.set(Calendar.MILLISECOND, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MONTH, 0); calendar.set(Calendar.DATE, 1); date.setTime(calendar.getTime().getTime()); return date; } /** * Returns the date which occurs after the specified date, given the number * of days to add. * * @param date * - the specified date * @param daysToAdd * - the number of days to add to that date * @return - the resulting date */ public static DateOnly addDaysDateOnly(DateOnly date, int daysToAdd) { Calendar calendar = new GregorianCalendar(); calendar.setTime(date); calendar.setLenient(false); // NB clear() does not work in JDK 1.3.1 calendar.set(Calendar.MILLISECOND, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.add(Calendar.DAY_OF_WEEK, daysToAdd); date.setTime(calendar.getTime().getTime()); return date; } @SuppressWarnings("deprecation") public static String sqlFormatDateOnly(DateOnly theDate) { String result = ""; if (theDate != null) { String month = "0" + (theDate.getMonth() + 1); month = month.substring(month.length() - 2); String day = "0" + theDate.getDate(); day = day.substring(day.length() - 2); result = "convert('" + (theDate.getYear() + 1900) + "-" + month + "-" + day + "', date) "; } return result; } /** Returns a TitleCase version of the String supplied */ public static String titleCase(String raw) { String s = raw; if (s != null) { if (s.length() > 1) { s = s.substring(0, 1).toUpperCase() + s.substring(1); } else if (s.length() == 1) { s = s.toUpperCase(); } } return s; } /** abbreviated forms of calendar months */ public static enum CalendarMonth { JAN, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC } public static final List<DomainValue> CALENDAR_MONTHS = new ArrayList<>(); static { CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.JAN.toString())); CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.FEB.toString())); CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.MAR.toString())); CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.APR.toString())); CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.MAY.toString())); CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.JUN.toString())); CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.JUL.toString())); CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.AUG.toString())); CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.SEP.toString())); CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.OCT.toString())); CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.NOV.toString())); CALENDAR_MONTHS.add(new DomainValue(CalendarMonth.DEC.toString())); } /** conversion from month Name to calendar month (int) */ public static int calendarMonthNameToNumber(String monthName) { if (CalendarMonth.JAN.toString().equals(monthName)) { return 0; } else if (CalendarMonth.FEB.toString().equals(monthName)) { return 1; } else if (CalendarMonth.MAR.toString().equals(monthName)) { return 2; } else if (CalendarMonth.APR.toString().equals(monthName)) { return 3; } else if (CalendarMonth.MAY.toString().equals(monthName)) { return 4; } else if (CalendarMonth.JUN.toString().equals(monthName)) { return 5; } else if (CalendarMonth.JUL.toString().equals(monthName)) { return 6; } else if (CalendarMonth.AUG.toString().equals(monthName)) { return 7; } else if (CalendarMonth.SEP.toString().equals(monthName)) { return 8; } else if (CalendarMonth.OCT.toString().equals(monthName)) { return 9; } else if (CalendarMonth.NOV.toString().equals(monthName)) { return 10; } else if (CalendarMonth.DEC.toString().equals(monthName)) { return 11; } else { return 0; } } /** Returns the current session/conversation user as a Amin module User */ public static modules.admin.domain.User currentAdminUser() { modules.admin.domain.User user = null; try { Persistence persistence = CORE.getPersistence(); Customer customer = persistence.getUser().getCustomer(); Module module = customer.getModule(modules.admin.domain.User.MODULE_NAME); Document userDoc = module.getDocument(customer, modules.admin.domain.User.DOCUMENT_NAME); user = persistence.retrieve(userDoc, persistence.getUser().getId(), false); } catch (Exception e) { // do nothing } return user; } public static Contact getCurrentUserContact() throws MetaDataException, DomainException { Persistence persistence = CORE.getPersistence(); User user = persistence.getUser(); Customer customer = user.getCustomer(); Module module = customer.getModule(Contact.MODULE_NAME); Document document = module.getDocument(customer, Contact.DOCUMENT_NAME); Contact contact = persistence.retrieve(document, user.getContactId(), false); return contact; } public static void addValidationError(ValidationException e, String fieldName, String messageString) { Message vM = new Message(messageString); vM.addBinding(fieldName); e.getMessages().add(vM); } /** * Returns a new document/sequence number for the given * module.document.fieldName in a thread-safe way. * <p> * If no previous record is found in the DocumentNumber table, the method * attempts to find the Maximum existing value currently extant in the field * and increments that. Otherwise, the value returned is incremented and * updated DocumentNumber value for the specified combination. * * @param prefix * - if the sequence value has a known prefix before the number, * eg INV0001 has a prefix of "INV" * @param moduleName * - the application module * @param documentName * - the application document * @param fieldName * - the fieldName/columnName in which the value is held * @param numberLength * - the minimum length of the number when specified as a string * @return - the next sequence number * @throws Exception * general Exception for persistence failure */ public static String getNextDocumentNumber(String prefix, String moduleName, String documentName, String fieldName, int numberLength) throws Exception { Persistence pers = CORE.getPersistence(); User user = pers.getUser(); Customer customer = user.getCustomer(); Module module = customer.getModule(DocumentNumber.MODULE_NAME); Document document = module.getDocument(customer, DocumentNumber.DOCUMENT_NAME); String nextNumber = "0"; String lastNumber = "0"; DocumentNumber dN = null; try { DocumentQuery qN = pers.newDocumentQuery(DocumentNumber.MODULE_NAME, DocumentNumber.DOCUMENT_NAME); qN.getFilter().addEquals(DocumentNumber.moduleNamePropertyName, moduleName); qN.getFilter().addEquals(DocumentNumber.documentNamePropertyName, documentName); qN.getFilter().addEquals(DocumentNumber.sequenceNamePropertyName, fieldName); List<DocumentNumber> num = pers.retrieve(qN); if (num.isEmpty()) { // System.out.println("DOCUMENT NUMBER: No previous found - source from table"); // Check if sequence name is a field in that table boolean isField = false; for (Attribute attribute : document.getAttributes()) { if (attribute.getName().equals(fieldName)) { isField = true; break; } } if (isField) { // first hit - go lookup max number from table DocumentQuery query = pers.newDocumentQuery(moduleName, documentName); query.addAggregateProjection(AggregateFunction.Max, fieldName, "MaxNumber"); List<Bean> beans = pers.retrieve(query); if (!beans.isEmpty()) { Object o = Binder.get(beans.get(0), "MaxNumber"); if (o instanceof Integer) { lastNumber = ((Integer) Binder.get(beans.get(0), "MaxNumber")).toString(); } else { lastNumber = (String) Binder.get(beans.get(0), "MaxNumber"); } } } // create a new document number record dN = document.newInstance(user); dN.setModuleName(moduleName); dN.setDocumentName(documentName); dN.setSequenceName(fieldName); } else { // System.out.println("DOCUMENT NUMBER: Previous found"); dN = num.get(0); dN = pers.retrieve(document, dN.getBizId(), true); // issue a // row-level // lock lastNumber = dN.getNumber(); } // just update from the document Number nextNumber = incrementAlpha(prefix, lastNumber, numberLength); dN.setNumber(nextNumber); pers.preFlush(document, dN); pers.upsertBeanTuple(dN); pers.postFlush(document, dN); } finally { if (dN != null) { pers.evictCached(dN); } } // System.out.println("Next document number for " + moduleName + "." + // documentName + "." + fieldName + " is " + nextNumber); return nextNumber; } /** * Wrapper for getNextDocumentNumber, specifically for numeric only * sequences */ public static Integer getNextDocumentNumber(String moduleName, String documentName, String fieldName) throws Exception { return new Integer(Integer.parseInt(getNextDocumentNumber(null, moduleName, documentName, fieldName, 0))); } /** * Returns the next alpha value - ie A00A1 becomes A00A2 etc * * @param prefix * - if the sequence value has a known prefix before the number, * eg INV0001 has a prefix of "INV" * @param numberLength * - the minimum length of the number when specified as a string * @param lastNumber * - the number to increment * @return - the next number * @throws Exception * general Exception */ public static String incrementAlpha(String prefix, String lastNumber, int numberLength) throws Exception { String newNumber = ""; String nonNumeric = lastNumber; Integer value = new Integer(1); if (lastNumber != null) { String[] parts = (new StringBuilder(" ").append(lastNumber)).toString().split("\\D\\d+$"); //cater for alpha prefix if (parts.length > 0 && parts[0].length() < lastNumber.length()) { String numberPart = lastNumber.substring(parts[0].length(),lastNumber.length()); nonNumeric = lastNumber.substring(0, parts[0].length()); value = new Integer(Integer.parseInt(numberPart) + 1); //cater for purely numeric prefix } else if (prefix.matches("^\\d+$") && lastNumber.matches("^\\d+$") && !"0".equals(lastNumber)) { int len = prefix.length(); value = new Integer(Integer.parseInt(lastNumber.substring(len)) + 1); nonNumeric = (prefix == null ? "" : prefix); //cater for numeric only } else if (lastNumber.matches("^\\d+$")) { nonNumeric = (prefix == null ? "" : prefix); value = new Integer(Integer.parseInt(lastNumber) + 1); } } else { nonNumeric = (prefix == null ? "" : prefix); } // now put prefix and value together int newLength = (nonNumeric.length() + value.toString().length() > numberLength ? nonNumeric.length() + value.toString().length() : numberLength); StringBuilder sb = new StringBuilder(newLength + 1); try (Formatter f = new Formatter(sb)) { newNumber = nonNumeric + f.format(new StringBuilder("%1$").append(newLength - nonNumeric.length()).append("s").toString(), value.toString()).toString().replace(" ", "0"); } return newNumber; } /** short-hand generic way to create a bean instance */ public static Bean newBeanInstance(String moduleName, String documentName) throws Exception { User user = CORE.getPersistence().getUser(); Customer customer = user.getCustomer(); Module module = customer.getModule(moduleName); Document document = module.getDocument(customer, documentName); Bean bean = document.newInstance(user); return bean; } /** returns a fomatted string representing the condition */ public static String getConditionName(String conditionCode) { String result = "is"; result += conditionCode.substring(0, 1).toUpperCase() + conditionCode.substring(1, conditionCode.length()); // System.out.println("GetConditionName " + result); return result; } /** allows comparison where both terms being null evaluates as equality */ public static boolean bothNullOrEqual(Object object1, Object object2) { boolean result = false; if ((object1 == null && object2 == null) || (object1 != null && object2 != null && object1.equals(object2))) { result = true; } return result; } /** returns null if zero - for reports or data import/export */ public static Decimal5 coalesce(Decimal5 val, Decimal5 ifNullValue) { return (val == null ? ifNullValue : val); } /** type-specific coalesce */ public static String coalesce(String val, String ifNullValue) { return (val == null ? ifNullValue : val); } /** type-specific coalesce */ public static Decimal2 coalesce(Decimal2 val, Decimal2 ifNullValue) { return (val == null ? ifNullValue : val); } /** type-specific coalesce */ public static String coalesce(Object val, String ifNullValue) { return (val == null ? ifNullValue : val.toString()); } /** type-specific coalesce */ public static Boolean coalesce(Boolean val, Boolean ifNullValue) { return (val == null ? ifNullValue : val); } /** type-specific coalesce */ public static Integer coalesce(Integer val, Integer ifNullValue) { return (val == null ? ifNullValue : val); } /** * Replaces the value found in the bean for the binding string provided, * e.g. if the bean has a binding of contact.name, for which the * displayNames of those bindings are Contact.FullName , then get the value * of that binding from the bean provided. * * @param bean * - the bean relevant for the binding * @param replacementString * - the string representing the displayName form of the binding * @return - the value from the bean * @throws Exception * general Exception for metadata exception or string * manipulation failure etc */ public static String replaceBindingsInString(Bean bean, String replacementString) throws Exception { StringBuilder result = new StringBuilder(replacementString); int openCurlyBraceIndex = result.indexOf("{"); // now replace contents of each curlyBraced expression if we can while (openCurlyBraceIndex >= 0) { int closedCurlyBraceIndex = result.indexOf("}"); String displayNameOfAttribute = result.substring(openCurlyBraceIndex + 1, closedCurlyBraceIndex); Bean b = bean; StringBuilder binding = new StringBuilder(); String[] attributes = displayNameOfAttribute.toString().split("\\."); boolean found = false; for (String a : attributes) { // if the format string includes a sub-bean attribute, get the // sub-bean if (binding.toString().length() > 0) { b = (Bean) Binder.get(bean, binding.toString()); } // parent special case if (a.equals("parent")) { b = ((ChildBean<?>) bean).getParent(); } // if the sub-bean isn't null, try to match the attribute // because attributes in the format string might be optional found = false; if (b != null) { User user = CORE.getPersistence().getUser(); Customer customer = user.getCustomer(); Module module = customer.getModule(b.getBizModule()); Document document = module.getDocument(customer, b.getBizDocument()); for (Attribute attribute : document.getAttributes()) { if (attribute.getDisplayName().equals(a)) { found = true; if (binding.toString().length() > 0) { binding.append('.').append(attribute.getName()); } else { binding.append(attribute.getName()); } } } // check for non-attribute bindings if (!found) { try { if (Binder.get(bean, a) != null) { binding.append(a); } } catch (Exception e) { // do nothing } } } } String term = ""; if (found) { Object value = Binder.get(bean, binding.toString()); if (value instanceof DateOnly) { DateOnly dValue = (DateOnly) value; DD_MMM_YYYY convDate = new DD_MMM_YYYY(); term = convDate.toDisplayValue(dValue); } else if (value instanceof Decimal2) { term = value.toString(); } else if (value instanceof Decimal5) { term = value.toString(); } else { term = coalesce(value, "").toString(); } } // move along String displayValue = ModulesUtil.coalesce(term, ""); result.replace(openCurlyBraceIndex, closedCurlyBraceIndex + 1, displayValue); openCurlyBraceIndex = result.indexOf("{"); } return result.toString(); } /** simple concatenation with a delimiter */ public static String concatWithDelim(String delimiter, String... strings) { StringBuilder sb = new StringBuilder(); String delim = coalesce(delimiter, " "); for (String s : strings) { if (coalesce(s, "").length() > 0) { if (sb.toString().length() > 0) { sb.append(delim); } sb.append(s); } } return sb.toString(); } /** short-hand enquoting of a string */ public static String enquote(String quoteSet, String s) { String l = null; String r = null; if (quoteSet != null) { l = quoteSet.substring(0, 1); if (coalesce(quoteSet, "").length() > 1) { r = quoteSet.substring(1); } } return concatWithDelim("", l, concatWithDelim("", s, r)); } /** * Returns whether the user has access to the specified module * * @param moduleName * @return */ public static boolean hasModule(String moduleName) throws MetaDataException { boolean result = false; User user = CORE.getPersistence().getUser(); Customer customer = user.getCustomer(); for (Module module : customer.getModules()) { if (module.getName().equals(moduleName)) { result = true; break; } } return result; } /** * Generic bizport export method. * * @param moduleName * - the module to be exported * @param documentName * - the document to be exported * @param b * - the top-level bean to export * @return - the reference to the Bizportable * @throws Exception * general Exception */ public static BizPortWorkbook standardBeanBizExport(String modName, String docName, Bean b) throws Exception { String documentName = docName; String moduleName = modName; BizPortWorkbook result = EXT.newBizPortWorkbook(false); if (b != null) { moduleName = b.getBizModule(); documentName = b.getBizDocument(); } Persistence persistence = CORE.getPersistence(); Customer customer = persistence.getUser().getCustomer(); Module module = customer.getModule(moduleName); // Project Document document = module.getDocument(customer, documentName); StandardGenerator bgBean = EXT.newBizPortStandardGenerator(customer, document); bgBean.generateStructure(result); result.materialise(); // System.out.println("BIZPORTING PROJECT " ); DocumentQuery query = persistence.newDocumentQuery(moduleName, documentName); if (b != null) { // filter for this project if provided query.getFilter().addEquals(Bean.DOCUMENT_ID, b.getBizId()); } bgBean.generateData(result, persistence.retrieve(query)); return result; } public static void standardBeanBizImport(BizPortWorkbook workbook, BizPortException problems, String moduleName) throws Exception { final Persistence persistence = CORE.getPersistence(); final Customer customer = persistence.getUser().getCustomer(); StandardLoader loader = new StandardLoader(workbook, problems); List<Bean> bs = loader.populate(persistence); Module module = customer.getModule(moduleName); Document document = null; Bean bean = null; String documentName = null; // System.out.println("Validate everything " + new Date()); for (String key : loader.getBeanKeys()) { bean = loader.getBean(key); document = module.getDocument(customer, bean.getBizDocument()); if (documentName == null) { documentName = document.getName(); } try { persistence.preFlush(document, bean); } catch (DomainException e) { loader.addError(customer, module, document, bean, e); } } // throw if we have errors found if (problems.hasErrors()) { throw problems; } // do the insert as 1 operation, bugging out if we encounter any errors try { document = module.getDocument(customer, documentName); for (Bean b : bs) { PersistentBean pb = (PersistentBean) b; pb = persistence.save(document, pb); } } catch (DomainException e) { loader.addError(customer, module, document, bean, e); throw problems; } } /** short-hand way of finding a bean using a legacy key */ public static Bean lookupBean(String moduleName, String documentName, String propertyName, Object objValue) throws Exception { Persistence persistence = CORE.getPersistence(); DocumentQuery qBean = persistence.newDocumentQuery(moduleName, documentName); qBean.getFilter().addEquals(propertyName, objValue); List<Bean> beans = persistence.retrieve(qBean); Bean bean = null; if (!beans.isEmpty()) { bean = beans.get(0); } else { System.out.println("Cannot find reference to " + objValue + " in document " + documentName); } return bean; } }
package org.intermine.api.template; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import org.intermine.api.profile.InterMineBag; import org.intermine.api.util.PathUtil; import org.intermine.model.InterMineObject; import org.intermine.objectstore.query.ConstraintOp; import org.intermine.pathquery.Path; import org.intermine.pathquery.PathConstraint; import org.intermine.pathquery.PathConstraintAttribute; import org.intermine.pathquery.PathConstraintBag; import org.intermine.pathquery.PathConstraintLookup; import org.intermine.pathquery.PathConstraintMultiValue; import org.intermine.pathquery.PathConstraintNull; import org.intermine.pathquery.PathException; import org.intermine.util.DynamicUtil; /** * Configures original template. Old constraints are replaced with the similar * new constraints, that have different values. * @author Richard Smith **/ public final class TemplatePopulator { private TemplatePopulator() { } /** * Given a template and a map of values for editable constraints on each editable node create * a copy of the template query with the values filled in. This may alter the query when e.g. * bag constraints are applied to a class rather than an attribute. * * @param origTemplate the template to populate with values * @param newConstraints a map from editable node to a list of values for each editable * constraint * @return a copy of the template with values filled in * @throws TemplatePopulatorException if something goes wrong */ public static TemplateQuery getPopulatedTemplate(TemplateQuery origTemplate, Map<String, List<TemplateValue>> newConstraints) { TemplateQuery template = origTemplate.clone(); template.setEdited(true); for (String editablePath : template.getEditablePaths()) { List<PathConstraint> constraints = template.getEditableConstraints(editablePath); List<TemplateValue> values = newConstraints.get(editablePath); // TODO this is a temporary fix, this section of code should be re-written without // editablePaths. Each TemplateValue has a reference to a PathConstraint. if (values == null) { values = new ArrayList<TemplateValue>(); } if (constraints.size() < values.size()) { throw new TemplatePopulatorException("There were more values provided than " + " there are editable constraints on the path " + editablePath); } // if (values.size() == 0) { // for (PathConstraint con : constraints) { // template.removeConstraint(con); // continue; for (PathConstraint con : constraints) { boolean found = false; for (TemplateValue templateValue : values) { if (con.equals(templateValue.getConstraint())) { try { setConstraint(template, templateValue); } catch (PathException e) { throw new TemplatePopulatorException("Invalid path found when " + "populating template.", e); } found = true; break; } } if (!found) { template.removeConstraint(con); } } } return template; } /** * Constrain a template query with a single editable constraint to be the given object. This * returns a copy of the template with the value filled in, if the existing constraint will be * replaced by a constraint on the id field of the editable node. * * @param template the template to constrain * @param obj the object to constrain to * @return a copy of the template with values filled in * @throws PathException if the template is invalid */ public static TemplateQuery populateTemplateWithObject(TemplateQuery template, InterMineObject obj) throws PathException { Map<String, List<TemplateValue>> templateValues = new HashMap<String, List<TemplateValue>>(); if (template.getEditableConstraints().size() != 1) { throw new TemplatePopulatorException("Template must have exactly one editable " + "constraint to be configured with an object."); } PathConstraint constraint = template.getEditableConstraints().get(0); Path path = getPathOfClass(template, constraint.getPath()); if (!PathUtil.canAssignObjectToType(path.getEndType(), obj)) { throw new TemplatePopulatorException("The constraint of type " + path.getEndType() + " can't be set to object of type " + DynamicUtil.getFriendlyName(obj.getClass()) + " in template query " + template.getName() + "."); } TemplateValue templateValue = new TemplateValue(constraint, ConstraintOp.EQUALS, obj.getId().toString(), TemplateValue.ValueType.OBJECT_VALUE, SwitchOffAbility.ON); templateValues.put(constraint.getPath(), new ArrayList<TemplateValue>(Collections.singleton(templateValue))); return TemplatePopulator.getPopulatedTemplate(template, templateValues); } /** * Constrain a template query with a single editable constraint to be in the given bag. This * returns a copy of the template with the value filled in, if the constraint is on an * attribute it will be replaced by a constrain on the parent class. * * @param template the template to constrain * @param bag the bag to constrain to * @return a copy of the template with values filled in * @throws PathException if the template is invalid */ public static TemplateQuery populateTemplateWithBag(TemplateQuery template, InterMineBag bag) throws PathException { Map<String, List<TemplateValue>> templateValues = new HashMap<String, List<TemplateValue>>(); if (template.getEditableConstraints().size() != 1) { throw new TemplatePopulatorException("Template must have exactly one editable " + "constraint to be configured with a bag."); } PathConstraint constraint = template.getEditableConstraints().get(0); Path path = getPathOfClass(template, constraint.getPath()); if (!bag.isOfType(path.getNoConstraintsString())) { throw new TemplatePopulatorException("The constraint of type " + path.getNoConstraintsString() + " can't be set to a bag (list) of type " + bag.getType() + " in template query " + template.getName() + "."); } TemplateValue templateValue = new TemplateValue(constraint, ConstraintOp.IN, bag.getName(), TemplateValue.ValueType.BAG_VALUE, SwitchOffAbility.ON); templateValues.put(constraint.getPath(), new ArrayList<TemplateValue>(Collections.singleton(templateValue))); return TemplatePopulator.getPopulatedTemplate(template, templateValues); } private static Path getPathOfClass(TemplateQuery template, String pathStr) throws PathException { Path path = template.makePath(pathStr); if (path.endIsAttribute()) { path = path.getPrefix(); } return path; } /** * Populate a TemplateQuery that has a single editable constraint with the given value. This * returns a copy of the template with the value filled in. * @param template the template query to populate * @param op operation of the constraint * @param value value to be constrained to * @return a copy of the template with the value filled in * @throws PathException if the template is invalid */ public static TemplateQuery populateTemplateOneConstraint( TemplateQuery template, ConstraintOp op, String value) throws PathException { Map<String, List<TemplateValue>> templateValues = new HashMap<String, List<TemplateValue>>(); if (template.getEditableConstraints().size() != 1) { throw new RuntimeException("Template must have exactly one editable constraint to be " + " configured with a single value."); } String editablePath = template.getEditablePaths().get(0); Path path = template.makePath(editablePath); if (path.endIsAttribute()) { path = path.getPrefix(); } PathConstraint constraint = template.getEditableConstraints(editablePath).get(0); TemplateValue templateValue = new TemplateValue(constraint, op, value, TemplateValue.ValueType.SIMPLE_VALUE, SwitchOffAbility.ON); templateValues.put(constraint.getPath(), new ArrayList<TemplateValue>(Collections.singleton(templateValue))); return TemplatePopulator.getPopulatedTemplate(template, templateValues); } /** * Set the value for a constraint in the template query with the given TemplateValue. This may * move a constraint from an attribute to the parent class if the constraint is object or bag. * @param template the template to constrain * @param templateValue container for the value to set constraint to * @throws PathException if a TemplateValue contains an invalid path */ protected static void setConstraint(TemplateQuery template, TemplateValue templateValue) throws PathException { PathConstraint originalConstraint = templateValue.getConstraint(); Path constraintPath = template.makePath(templateValue.getConstraint().getPath()); if (templateValue.isBagConstraint()) { if (constraintPath.endIsAttribute()) { constraintPath = constraintPath.getPrefix(); } PathConstraint newConstraint = new PathConstraintBag(constraintPath.getNoConstraintsString(), templateValue.getOperation(), templateValue.getValue()); template.replaceConstraint(originalConstraint, newConstraint); template.setSwitchOffAbility(newConstraint, templateValue.getSwitchOffAbility()); } else if (templateValue.isObjectConstraint()) { if (constraintPath.endIsAttribute()) { constraintPath = constraintPath.getPrefix(); } String idPath = constraintPath.getNoConstraintsString() + ".id"; PathConstraint newConstraint = new PathConstraintAttribute(idPath, templateValue.getOperation(), templateValue.getValue()); template.replaceConstraint(originalConstraint, newConstraint); template.setSwitchOffAbility(newConstraint, templateValue.getSwitchOffAbility()); } else { // this is one of the valid constraint types for templates PathConstraint newConstraint = null; if (originalConstraint instanceof PathConstraintAttribute) { // if the op has been changed to IN or NOT_IN this becomes a multi value constraint if (PathConstraintMultiValue.VALID_OPS.contains(templateValue.getOperation())) { newConstraint = new PathConstraintMultiValue(constraintPath.getNoConstraintsString(), templateValue.getOperation(), Arrays.asList(templateValue.getValue().split(","))); } else { newConstraint = new PathConstraintAttribute(constraintPath.getNoConstraintsString(), templateValue.getOperation(), templateValue.getValue()); } } else if (originalConstraint instanceof PathConstraintLookup) { newConstraint = new PathConstraintLookup(constraintPath.getNoConstraintsString(), templateValue.getValue(), templateValue.getExtraValue()); } else if (originalConstraint instanceof PathConstraintNull) { newConstraint = new PathConstraintNull(constraintPath.getNoConstraintsString(), templateValue.getOperation()); } else if (originalConstraint instanceof PathConstraintMultiValue) { // if op has been changed to something other than IN or NOT_IN make this becomes // a regular attribute constraint if (!PathConstraintMultiValue.VALID_OPS.contains(templateValue.getOperation())) { newConstraint = new PathConstraintAttribute(constraintPath.getNoConstraintsString(), templateValue.getOperation(), templateValue.getValue()); } else { newConstraint = new PathConstraintMultiValue(constraintPath.getNoConstraintsString(), templateValue.getOperation(), Arrays.asList(templateValue.getValue().split(","))); } } template.replaceConstraint(originalConstraint, newConstraint); template.setSwitchOffAbility(newConstraint, templateValue.getSwitchOffAbility()); } } }
package org.intermine.web.logic.results; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; import org.intermine.api.InterMineAPI; import org.intermine.api.util.PathUtil; import org.intermine.metadata.ClassDescriptor; import org.intermine.metadata.CollectionDescriptor; import org.intermine.metadata.FieldDescriptor; import org.intermine.metadata.ReferenceDescriptor; import org.intermine.model.InterMineObject; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.proxy.ProxyReference; import org.intermine.objectstore.query.ClobAccess; import org.intermine.pathquery.Path; import org.intermine.pathquery.PathException; import org.intermine.util.DynamicUtil; import org.intermine.util.StringUtil; import org.intermine.web.displayer.CustomDisplayer; import org.intermine.web.displayer.DisplayerManager; import org.intermine.web.logic.config.FieldConfig; import org.intermine.web.logic.config.HeaderConfigLink; import org.intermine.web.logic.config.HeaderConfigTitle; import org.intermine.web.logic.config.InlineList; import org.intermine.web.logic.config.Type; import org.intermine.web.logic.config.WebConfig; import org.intermine.web.logic.pathqueryresult.PathQueryResultHelper; /** * Object to be displayed on report.do * * @author Radek Stepan * @author Richard Smith */ public class ReportObject { private InterMineObject object; private final WebConfig webConfig; /** unqualified (!!) object type string */ private final String objectType; private Map<String, Object> fieldValues; private InterMineAPI im; /** * @List<ReportObjectField> setup list of summary fields this object has */ private List<ReportObjectField> objectSummaryFields; /** @var List header inline lists set by the WebConfig */ private List<InlineList> inlineListsHeader = null; /** @var List of 'unplaced' normal InlineLists */ private List<InlineList> inlineListsNormal = null; private Map<String, Object> attributes = null; private Map<String, String> longAttributes = null; private Map<String, Object> longAttributesTruncated = null; private Map<String, FieldDescriptor> attributeDescriptors = null; private Map<String, DisplayReference> references = null; private Map<String, DisplayCollection> collections = null; private Map<String, DisplayField> refsAndCollections = null; /** @var ObjectStore so we can use PathQueryResultHelper.queryForTypesInCollection */ private ObjectStore os = null; private HeaderConfigLink headerLink; /** * Setup internal ReportObject * @param object InterMineObject * @param webConfig WebConfig * @param im InterMineAPI * @throws Exception Exception */ public ReportObject(InterMineObject object, WebConfig webConfig, InterMineAPI im) throws Exception { this.object = object; this.webConfig = webConfig; this.im = im; this.os = im.getObjectStore(); // infer dynamic type of IM object this.objectType = DynamicUtil.getSimpleClass(object).getSimpleName(); } /** * * @return Map */ public Map<String, List<CustomDisplayer>> getReportDisplayers() { DisplayerManager displayerManager = DisplayerManager.getInstance(webConfig, im); return displayerManager.getReportDisplayersForType(objectType); } /** * Get the id of this object * @return the id */ public int getId() { return object.getId().intValue(); } /** * Get the attribute fields and values for this object * @return the attributes */ public Map<String, Object> getAttributes() { if (attributes == null) { initialise(); } return attributes; } /** * Get the class descriptor for this object * @return one class descriptor */ public ClassDescriptor getClassDescriptor() { return im.getModel().getClassDescriptorByName(objectType); } /** * Get the collection fields and values for this object * @return the collections */ public Map<String, DisplayCollection> getCollections() { if (collections == null) { initialise(); } return collections; } private String stripTail(String input) { Integer dot = input.indexOf("."); if (dot > 0) { return input.substring(0, dot); } return input; } /** * A listing of object fields as pieced together from the various ReportObject methods * @return <ReportObjectField>s List */ public List<ReportObjectField> getObjectSummaryFields() { // are we setup yet? if (objectSummaryFields == null) { objectSummaryFields = new ArrayList<ReportObjectField>(); List<ReportObjectField> objectOtherSummaryFields = new ArrayList<ReportObjectField>(); // to make sure we do not show fields that are replaced elsewhere Set<String> replacedFields = getReplacedFieldExprs(); // traverse all path expressions for the fields that should be used when // summarising the object for (FieldConfig fc : getFieldConfigs()) { // get fieldName String fieldName = fc.getFieldExpr(); // only non-replaced fields if (!replacedFields.contains(stripTail(fieldName))) { // get fieldValue Object fieldValue = getFieldValue(fieldName); // get displayer //FieldConfig fieldConfig = fieldConfigMap.get(fieldName); String fieldDisplayer = fc.getDisplayer(); // new ReportObjectField ReportObjectField rof = new ReportObjectField( objectType, fieldName, fieldValue, fieldDisplayer, fc.getDoNotTruncate() ); // show in summary... if (fc.getShowInSummary()) { objectSummaryFields.add(rof); } else { // show in summary also, but not right now... objectOtherSummaryFields.add(rof); } } } // append the other fields objectSummaryFields.addAll(objectOtherSummaryFields); } return objectSummaryFields; } /** * Get InterMine object * @return InterMineObject */ public InterMineObject getObject() { return object; } /** * Return a list of field configs * @return Collection<FieldConfig> */ public Collection<FieldConfig> getFieldConfigs() { Map<String, Type> types = webConfig.getTypes(); String qualifiedType = DynamicUtil.getSimpleClass(object).getName(); if (types.containsKey(qualifiedType)) { return types.get(qualifiedType).getFieldConfigs(); } return Collections.emptyList(); } /** * Get field value for a field name (expression) * @param fieldExpression String * @return Object */ protected Object getFieldValue(String fieldExpression) { // if field values as a whole are not set yet... if (fieldValues == null) { setupFieldValues(); } // return a field value for a field expression (name) return fieldValues.get(fieldExpression); } /** * Setup fieldValues HashMap */ protected void setupFieldValues() { // create a new map fieldValues = new HashMap<String, Object>(); // fetch field configs for (FieldConfig fc : getFieldConfigs()) { // crete a path string String pathString = objectType + "." + fc.getFieldExpr(); try { // resolve path Path path = new Path(im.getModel(), pathString); fieldValues.put(fc.getFieldExpr(), PathUtil.resolvePath(path, object)); } catch (PathException e) { throw new Error("There must be a bug", e); } } } public String getType() { return objectType; } /** * Used by JSP * @return the main title of this object, i.e.: "eve FBgn0000606" */ public String getTitleMain() { return getTitles("main"); } /** * Used by JSP * @return the subtitle of this object, i.e.: "D. melanogaster" */ public String getTitleSub() { return getTitles("sub"); } /** * Get a title based on the type key we pass it * @param key: main|subre * @return the titles string as resolved based on the path(s) under key */ private String getTitles(String key) { // fetch the Type Type type = webConfig.getTypes().get(getClassDescriptor().getName()); // retrieve the titles map, HeaderConfig serves as a useless wrapper HeaderConfigTitle hc = type.getHeaderConfigTitle(); if (hc != null) { Map<String, LinkedHashMap<String, Object>> titles = hc.getTitles(); // if we have something saved if (titles != null && titles.containsKey(key)) { String result = ""; // concatenate a space delineated title together as resolved from FieldValues for (String path : titles.get(key).keySet()) { // do we have some special formatting chars? char first = path.charAt(0); char last = path.charAt(path.length() - 1); // strip all "non allowed" characters path = path.replaceAll("[^a-zA-Z.]", ""); // resolve the field value Object stuff = getFieldValue(path); if (stuff != null) { String stringyStuff = stuff.toString(); // String.isEmpty() was introduced in Java release 1.6 if (StringUtils.isNotBlank(stringyStuff)) { // apply special formatting if (first == '[' && last == ']') { stringyStuff = first + stringyStuff + last; } else if (first == '*' && first == last) { stringyStuff = "<i>" + stringyStuff + "</i>"; } result += stringyStuff + " "; } } } // trailing space & return if (!result.isEmpty()) { return result.substring(0, result.length() - 1); } } } return null; } /** * * @return a resolved link */ public HeaderConfigLink getHeaderLink() { if (this.headerLink == null) { // fetch the Type Type type = webConfig.getTypes().get(getClassDescriptor().getName()); // retrieve the titles map, HeaderConfig serves as a useless wrapper HeaderConfigLink link = type.getHeaderConfigLink(); if (link != null) { // link URL String linkUrl = link.getLinkUrl(); if (linkUrl != null) { // patternz Pattern linkPattern = Pattern.compile("\\{(.*?)\\}"); Matcher m = linkPattern.matcher(linkUrl); while (m.find()) { // get the field name and do some filtering just in case String path = m.group(1).replaceAll("[^a-zA-Z.]", ""); // resolve the field value Object stuff = getFieldValue(path); if (stuff != null) { String stringyStuff = stuff.toString(); // String.isEmpty() was introduced in Java release 1.6 if (StringUtils.isNotBlank(stringyStuff)) { // replace the field with the value & update link.setLinkUrl(linkUrl.replace("{" + path + "}", stringyStuff)); this.headerLink = link; } } } } } } return this.headerLink; } /** * Resolve an InlineList by filling it up with a list of list objects, part of initialise() * @param list retrieved from Type * @param bagOfInlineListNames is a bag of names of lists we have resolved so far so these * fields are not resolved elsewhere and skipped instead * @see setDescriptorOnInlineList() is still needed when traversing FieldDescriptors */ private void initialiseInlineList( InlineList list, HashMap<String, Boolean> bagOfInlineListNames ) { // bags inlineListsHeader = (inlineListsHeader != null) ? inlineListsHeader : new ArrayList<InlineList>(); inlineListsNormal = (inlineListsNormal != null) ? inlineListsNormal : new ArrayList<InlineList>(); // soon to be list of values Set<Object> listOfListObjects = null; String columnToDisplayBy = null; try { // create a new path to the collection of objects Path path = new Path(im.getModel(), DynamicUtil.getSimpleClass(object.getClass()).getSimpleName() + '.' + list.getPath()); try { // save the suffix, the value we will show the list by columnToDisplayBy = path.getLastElement(); // create only a prefix of the path so we have // Objects and not just Strings path = path.getPrefix(); } catch (Error e) { throw new RuntimeException("You need to specify a key to display" + "the list by, not just the root element."); } // resolve path to a collection and save into a list listOfListObjects = PathUtil.resolveCollectionPath(path, object); list.setListOfObjects(listOfListObjects, columnToDisplayBy); } catch (PathException e) { throw new RuntimeException("Your collections of inline lists" + "are failing you", e); } // place the list if (list.getShowInHeader()) { inlineListsHeader.add(list); } else { inlineListsNormal.add(list); } // save name of the collection String path = list.getPath(); bagOfInlineListNames.put(path.substring(0, path.indexOf('.')), true); } /** * Resolve an attribute, part of initialise() * @param fd FieldDescriptor */ private void initialiseAttribute(FieldDescriptor fd) { // bags attributes = (attributes != null) ? attributes : new TreeMap<String, Object>(String.CASE_INSENSITIVE_ORDER); longAttributes = (longAttributes != null) ? longAttributes : new HashMap<String, String>(); longAttributesTruncated = (longAttributesTruncated != null) ? longAttributesTruncated : new HashMap<String, Object>(); attributeDescriptors = (attributeDescriptors != null) ? attributeDescriptors : new HashMap<String, FieldDescriptor>(); Object fieldValue = null; try { fieldValue = object.getFieldValue(fd.getName()); } catch (IllegalAccessException e) { e.printStackTrace(); } if (fieldValue != null) { if (fieldValue instanceof ClobAccess) { ClobAccess fieldClob = (ClobAccess) fieldValue; if (fieldClob.length() > 200) { fieldValue = fieldClob.subSequence(0, 200).toString(); } else { fieldValue = fieldClob.toString(); } } attributes.put(fd.getName(), fieldValue); attributeDescriptors.put(fd.getName(), fd); if (fieldValue instanceof String) { String fieldString = (String) fieldValue; if (fieldString.length() > 30) { StringUtil.LineWrappedString lws = StringUtil.wrapLines( fieldString, 50, 3, 11); longAttributes.put(fd.getName(), lws.getString() .replace("\n", "<BR>")); if (lws.isTruncated()) { longAttributesTruncated.put(fd.getName(), Boolean.TRUE); } } } } } /** * Resolve a Reference, part of initialise() * @param fd FieldDescriptor */ private void initialiseReference(FieldDescriptor fd) { // bag references = (references != null) ? references : new TreeMap<String, DisplayReference>(String.CASE_INSENSITIVE_ORDER); ReferenceDescriptor ref = (ReferenceDescriptor) fd; // check whether reference is null without dereferencing Object proxyObject = null; ProxyReference proxy = null; try { proxyObject = object.getFieldProxy(ref.getName()); } catch (IllegalAccessException e1) { e1.printStackTrace(); } if (proxyObject instanceof org.intermine.objectstore.proxy.ProxyReference) { proxy = (ProxyReference) proxyObject; } else { // no go on objects that are not Proxies, ie Tests } DisplayReference newReference = null; try { newReference = new DisplayReference(proxy, ref, webConfig, im.getClassKeys()); } catch (Exception e) { e.printStackTrace(); } if (newReference != null) { if (newReference.collection.size() > 0) { references.put(fd.getName(), newReference); } } } /** * Resolve a Collection, part of initialise() * @param fd FieldDescriptor */ private void initialiseCollection(FieldDescriptor fd) { // bag collections = (collections != null) ? collections : new TreeMap<String, DisplayCollection>(String.CASE_INSENSITIVE_ORDER); Object fieldValue = null; try { fieldValue = object.getFieldValue(fd.getName()); } catch (IllegalAccessException e) { e.printStackTrace(); } // determine the types in the collection List<Class<?>> listOfTypes = PathQueryResultHelper. queryForTypesInCollection(object, fd.getName(), os); DisplayCollection newCollection = null; try { newCollection = new DisplayCollection((Collection<?>) fieldValue, (CollectionDescriptor) fd, webConfig, im.getClassKeys(), listOfTypes); } catch (Exception e) { e.printStackTrace(); } if (newCollection != null) { if (newCollection.getCollection().size() > 0) { collections.put(fd.getName(), newCollection); } } } /** * Create the Maps and Lists returned by the getters in this class. */ private void initialise() { // combined Map of References & Collections refsAndCollections = new TreeMap<String, DisplayField>(String.CASE_INSENSITIVE_ORDER); /** InlineLists **/ Type type = webConfig.getTypes().get(getClassDescriptor().getName()); // init lists from WebConfig Type List<InlineList> inlineListsWebConfig = type.getInlineLists(); // a map of inlineList object names so we do not include them elsewhere HashMap<String, Boolean> bagOfInlineListNames = new HashMap<String, Boolean>(); // fill up for (int i = 0; i < inlineListsWebConfig.size(); i++) { initialiseInlineList(inlineListsWebConfig.get(i), bagOfInlineListNames); } /** Attributes, References, Collections through FieldDescriptors **/ for (FieldDescriptor fd : getClassDescriptor().getAllFieldDescriptors()) { // only continue if we have not included this object in an inline list if (bagOfInlineListNames.get(fd.getName()) == null) { if (fd.isAttribute() && !"id".equals(fd.getName())) { /** Attribute **/ initialiseAttribute(fd); } else if (fd.isReference()) { /** Reference **/ initialiseReference(fd); } else if (fd.isCollection()) { /** Collection **/ initialiseCollection(fd); } } else { /** InlineList (cont...) **/ // assign Descriptor from FieldDescriptors to the InlineList setDescriptorOnInlineList(fd.getName(), fd); } } // make a combined Map if (references != null) refsAndCollections.putAll(references); if (collections != null) refsAndCollections.putAll(collections); } /** * Get all the reference and collection fields and values for this object * @return the collections */ public Map<String, DisplayField> getRefsAndCollections() { if (refsAndCollections == null) { initialise(); } return refsAndCollections; } /** * * @return Set */ public Set<String> getReplacedFieldExprs() { Set<String> replacedFieldExprs = new HashSet<String>(); for (CustomDisplayer reportDisplayer : getAllReportDisplayers()) { replacedFieldExprs.addAll(reportDisplayer.getReplacedFieldExprs()); } return replacedFieldExprs; } /** * * @return Set */ public Set<CustomDisplayer> getAllReportDisplayers() { DisplayerManager displayerManager = DisplayerManager.getInstance(webConfig, im); String clsName = DynamicUtil.getSimpleClass(object).getSimpleName(); return displayerManager.getAllReportDisplayersForType(clsName); } /** * Get attribute descriptors. * @return map of attribute descriptors */ public Map<String, FieldDescriptor> getAttributeDescriptors() { if (attributeDescriptors == null) { initialise(); } return attributeDescriptors; } /** * Set Descriptor (for placement) on an InlineList, only done for normal lists * @param name * @param fd */ private void setDescriptorOnInlineList(String name, FieldDescriptor fd) { done: for (InlineList list : inlineListsNormal) { Object path = list.getPath(); if (((String) path).substring(0, ((String) path).indexOf('.')).equals(name)) { list.setDescriptor(fd); break done; } } } /** * * @return InlineLists that are resolved into their respective placements */ public List<InlineList> getNormalInlineLists() { if (inlineListsNormal == null) { initialise(); } return inlineListsNormal; } /** * * @return InlineLists to be shown in the header */ public List<InlineList> getHeaderInlineLists() { if (inlineListsHeader == null) { initialise(); } return inlineListsHeader; } /** * Used from JSP * @return true if we have inlineListsHeader */ public Boolean getHasHeaderInlineLists() { return (getHeaderInlineLists() != null); } /** * Used from JSP * @return true if we have InlineLists with no placement yet */ public Boolean getHasNormalInlineLists() { return (getNormalInlineLists() != null); } }
package org.intermine.web.logic.query; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringReader; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.intermine.TestUtil; import org.intermine.metadata.FieldDescriptor; import org.intermine.metadata.Model; import org.intermine.model.testmodel.Company; import org.intermine.model.testmodel.Department; import org.intermine.model.testmodel.Employee; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreFactory; import org.intermine.objectstore.query.ConstraintOp; import org.intermine.objectstore.query.ConstraintSet; import org.intermine.objectstore.query.ContainsConstraint; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.query.QueryClass; import org.intermine.objectstore.query.QueryEvaluable; import org.intermine.objectstore.query.QueryExpression; import org.intermine.objectstore.query.QueryField; import org.intermine.objectstore.query.QueryNode; import org.intermine.objectstore.query.QueryObjectReference; import org.intermine.objectstore.query.QueryValue; import org.intermine.objectstore.query.SimpleConstraint; import org.intermine.pathquery.Constraint; import org.intermine.pathquery.LogicExpression; import org.intermine.pathquery.Path; import org.intermine.pathquery.PathNode; import org.intermine.pathquery.PathQuery; import org.intermine.pathquery.PathQueryBinding; import org.intermine.util.StringUtil; import org.intermine.web.logic.bag.BagQueryConfig; import org.intermine.web.logic.bag.BagQueryHelper; import org.intermine.web.logic.bag.BagQueryRunner; /** * Tests for the MainHelper class * * @author Kim Rutherford */ public class MainHelperTest extends TestCase { private BagQueryConfig bagQueryConfig; private ObjectStore os; private Map<String, List<FieldDescriptor>> classKeys; private BagQueryRunner bagQueryRunner; public MainHelperTest(String arg) { super(arg); } public void setUp() throws Exception { super.setUp(); os = ObjectStoreFactory.getObjectStore("os.unittest"); classKeys = TestUtil.getClassKeys(TestUtil.getModel()); InputStream config = MainHelperTest.class.getClassLoader() .getResourceAsStream("bag-queries.xml"); bagQueryConfig = BagQueryHelper.readBagQueryConfig(os.getModel(), config); bagQueryRunner = new BagQueryRunner(os, classKeys, bagQueryConfig, Collections.EMPTY_LIST); } // Method gets the last index of a '.' or a ':' public void testGetLastJoinIndex() { assertEquals(3, MainHelper.getLastJoinIndex("CEO.company")); assertEquals(3, MainHelper.getLastJoinIndex("CEO:company")); assertEquals(11, MainHelper.getLastJoinIndex("CEO.company:department")); assertEquals(11, MainHelper.getLastJoinIndex("CEO:company.department")); assertEquals(-1, MainHelper.getLastJoinIndex("CEO")); } // Method gets the first index of a '.' or a ':' public void testGetFirstJoinIndex() { assertEquals(3, MainHelper.getFirstJoinIndex("CEO.company")); assertEquals(3, MainHelper.getFirstJoinIndex("CEO:company")); assertEquals(3, MainHelper.getFirstJoinIndex("CEO.company:department")); assertEquals(3, MainHelper.getFirstJoinIndex("CEO:company.department")); assertEquals(-1, MainHelper.getFirstJoinIndex("CEO")); } public void testContainsPath() { assertTrue(MainHelper.containsJoin("Company.department")); assertTrue(MainHelper.containsJoin("Company:department")); assertTrue(MainHelper.containsJoin("Company:department.name")); assertFalse(MainHelper.containsJoin("Company")); } public void testGetTypeForPath() throws Exception { Model model = Model.getInstanceByName("testmodel"); PathQuery query = new PathQuery(model); PathNode employeeNode = query.addNode("Employee"); employeeNode.setType("Employee"); query.addNode("Employee.department"); query.addNode("Employee.age"); PathNode managerNode = query.addNode("Employee.department.manager"); managerNode.setType("CEO"); List<Path> paths = new LinkedList<Path> (); paths.add(PathQuery.makePath(model, query, "Employee")); paths.add(PathQuery.makePath(model, query, "Employee.end")); paths.add(PathQuery.makePath(model, query, "Employee.age")); paths.add(PathQuery.makePath(model, query, "Employee.department.manager")); paths.add(PathQuery.makePath(model, query, "Employee.department.manager.seniority")); paths.add(PathQuery.makePath(model, query, "Employee.department.manager.secretarys.name")); paths.add(PathQuery.makePath(model, query, "Employee.address.address")); query.addViewPaths(paths); assertEquals("org.intermine.model.testmodel.Employee", MainHelper.getTypeForPath("Employee", query)); assertEquals("java.lang.String", MainHelper.getTypeForPath("Employee.end", query)); assertEquals("int", MainHelper.getTypeForPath("Employee.age", query)); assertEquals("org.intermine.model.testmodel.CEO", MainHelper.getTypeForPath("Employee.department.manager", query)); assertEquals("org.intermine.model.testmodel.Department", MainHelper.getTypeForPath("Employee.department", query)); assertEquals("java.lang.Integer", MainHelper.getTypeForPath("Employee.department.manager.seniority", query)); assertEquals("java.lang.String", MainHelper.getTypeForPath("Employee.department.manager.secretarys.name", query)); assertEquals("java.lang.String", MainHelper.getTypeForPath("Employee.address.address", query)); try { MainHelper.getTypeForPath("Employee.foobar", query); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected } try { MainHelper.getTypeForPath("some.illegal.class", query); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected } try { MainHelper.getTypeForPath("some_illegal_class", query); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected } try { MainHelper.getTypeForPath(null, query); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected } try { MainHelper.getTypeForPath("Employee.department", null); fail("expected IllegalArgumentException"); } catch (IllegalArgumentException e) { // expected } } public void testMakeConstraintSets() { HashMap map = new HashMap(); LogicExpression expr = new LogicExpression("a and b"); ConstraintSet set = MainHelper.makeConstraintSets(expr, map, new ConstraintSet(ConstraintOp.AND)); assertEquals(2, map.size()); assertEquals(ConstraintOp.AND, set.getOp()); HashMap expecting = new HashMap(); expecting.put("a", set); expecting.put("b", set); assertEquals(expecting, map); expr = new LogicExpression("a and (b or c)"); set = MainHelper.makeConstraintSets(expr, map, new ConstraintSet(ConstraintOp.AND)); assertEquals(3, map.size()); assertEquals(ConstraintOp.AND, set.getOp()); assertEquals(1, set.getConstraints().size()); assertEquals(ConstraintOp.OR, ((ConstraintSet) set.getConstraints().iterator().next()).getOp()); expecting = new HashMap(); expecting.put("a", set); expecting.put("b", (ConstraintSet) set.getConstraints().iterator().next()); expecting.put("c", (ConstraintSet) set.getConstraints().iterator().next()); assertEquals(expecting, map); } // Select Employee.name public void testMakeQueryOneField() throws Exception { Map queries = readQueries(); PathQuery pq = (PathQuery) queries.get("employeeName"); Query q = new Query(); QueryClass qc1 = new QueryClass(Employee.class); q.addToSelect(qc1); q.addFrom(qc1); q.addToOrderBy(new QueryField(qc1, "name")); assertEquals(q.toString(), MainHelper.makeQuery(pq, new HashMap(), null, bagQueryRunner, new HashMap(), false).toString()); } // Select Employee.name, Employee.departments.name, Employee.departments.company.name // Constrain Employee.department.name = 'DepartmentA1' public void testMakeQueryThreeClasses() throws Exception { Map queries = readQueries(); PathQuery pq = (PathQuery) queries.get("employeeDepartmentCompany"); ConstraintSet cs = new ConstraintSet(ConstraintOp.AND); Query q = new Query(); QueryClass qc1 = new QueryClass(Employee.class); q.addToSelect(qc1); q.addFrom(qc1); QueryClass qc2 = new QueryClass(Department.class); q.addToSelect(qc2); q.addFrom(qc2); QueryField qf1 = new QueryField(qc2, "name"); QueryExpression qFunc = new QueryExpression(QueryExpression.LOWER, (QueryField) qf1); SimpleConstraint sc1 = new SimpleConstraint(qFunc, ConstraintOp.MATCHES, new QueryValue("departmenta1")); QueryObjectReference qor1 = new QueryObjectReference(qc1, "department"); ContainsConstraint cc1 = new ContainsConstraint(qor1, ConstraintOp.CONTAINS, qc2); cs.addConstraint(cc1); cs.addConstraint(sc1); QueryClass qc3 = new QueryClass(Company.class); q.addToSelect(qc3); q.addFrom(qc3); QueryObjectReference qor2 = new QueryObjectReference(qc2, "company"); ContainsConstraint cc2 = new ContainsConstraint(qor2, ConstraintOp.CONTAINS, qc3); cs.addConstraint(cc2); q.setConstraint(cs); q.addToOrderBy(new QueryField(qc1, "name")); q.addToOrderBy(qf1); q.addToOrderBy(new QueryField(qc3, "name")); assertEquals(q.toString(), MainHelper.makeQuery(pq, new HashMap(), null, bagQueryRunner, new HashMap(), false).toString()); } // As above but add a wildcard in the constraint which makes a MATCHES constraint // Constrain Employee.department.name = 'DepartmentA*' public void testMakeQueryWildcard() throws Exception { Map queries = readQueries(); PathQuery pq = (PathQuery) queries.get("employeeDepartmentCompanyWildcard"); ConstraintSet cs = new ConstraintSet(ConstraintOp.AND); Query q = new Query(); QueryClass qc1 = new QueryClass(Employee.class); q.addToSelect(qc1); q.addFrom(qc1); QueryClass qc2 = new QueryClass(Department.class); q.addToSelect(qc2); q.addFrom(qc2); QueryField qf1 = new QueryField(qc2, "name"); QueryExpression qFunc = new QueryExpression(QueryExpression.LOWER, (QueryField) qf1); SimpleConstraint sc1 = new SimpleConstraint(qFunc, ConstraintOp.MATCHES, new QueryValue("departmenta%")); QueryObjectReference qor1 = new QueryObjectReference(qc1, "department"); ContainsConstraint cc1 = new ContainsConstraint(qor1, ConstraintOp.CONTAINS, qc2); cs.addConstraint(cc1); cs.addConstraint(sc1); QueryClass qc3 = new QueryClass(Company.class); q.addToSelect(qc3); q.addFrom(qc3); QueryObjectReference qor2 = new QueryObjectReference(qc2, "company"); ContainsConstraint cc2 = new ContainsConstraint(qor2, ConstraintOp.CONTAINS, qc3); cs.addConstraint(cc2); q.setConstraint(cs); q.addToOrderBy(new QueryField(qc1, "name")); q.addToOrderBy(qf1); q.addToOrderBy(new QueryField(qc3, "name")); assertEquals(q.toString(), MainHelper.makeQuery(pq, new HashMap(), null, bagQueryRunner, new HashMap(), false).toString()); } // Select Employee.name, Employee.departments.company.name (should not select Department) // Constrain Employee.department.name = 'DepartmentA1' public void testConstrainedButNotInView() throws Exception { Map queries = readQueries(); PathQuery pq = (PathQuery) queries.get("employeeCompany"); ConstraintSet cs = new ConstraintSet(ConstraintOp.AND); Query q = new Query(); QueryClass qc1 = new QueryClass(Employee.class); q.addToSelect(qc1); q.addFrom(qc1); QueryClass qc2 = new QueryClass(Department.class); q.addFrom(qc2); QueryField qf1 = new QueryField(qc2, "name"); QueryExpression qFunc = new QueryExpression(QueryExpression.LOWER, (QueryField) qf1); SimpleConstraint sc1 = new SimpleConstraint(qFunc, ConstraintOp.MATCHES, new QueryValue("departmenta1")); QueryObjectReference qor1 = new QueryObjectReference(qc1, "department"); ContainsConstraint cc1 = new ContainsConstraint(qor1, ConstraintOp.CONTAINS, qc2); cs.addConstraint(cc1); cs.addConstraint(sc1); QueryClass qc3 = new QueryClass(Company.class); q.addToSelect(qc3); q.addFrom(qc3); QueryObjectReference qor2 = new QueryObjectReference(qc2, "company"); ContainsConstraint cc2 = new ContainsConstraint(qor2, ConstraintOp.CONTAINS, qc3); cs.addConstraint(cc2); q.setConstraint(cs); q.addToOrderBy(new QueryField(qc1, "name")); q.addToOrderBy(new QueryField(qc3, "name")); assertEquals(q.toString(), MainHelper.makeQuery(pq, new HashMap(), null, bagQueryRunner, new HashMap(), false).toString()); } public void testMakeQueryDateConstraint() throws Exception { // 11:02:39am Sun Nov 16, 2008 QueryNode qn = new QueryValue(new Date(1226833359000L)); // startOfDate < queryDate = 12:20:34am Mon Nov 17, 2008 < endOfDay Date queryDate = new Date(1226881234565L); Date startOfDay = new Date(1226880000000L); Date endOfDay = new Date(1226966399999L); SimpleConstraint expLTConstraint = new SimpleConstraint((QueryEvaluable) qn, ConstraintOp.LESS_THAN, new QueryValue(startOfDay)); Constraint ltConstraint = new Constraint(ConstraintOp.LESS_THAN, queryDate); org.intermine.objectstore.query.Constraint resLTConstraint = MainHelper.makeQueryDateConstraint(qn, ltConstraint); assertEquals(expLTConstraint, resLTConstraint); SimpleConstraint expLTEConstraint = new SimpleConstraint((QueryEvaluable) qn, ConstraintOp.LESS_THAN_EQUALS, new QueryValue(endOfDay)); Constraint lteConstraint = new Constraint(ConstraintOp.LESS_THAN_EQUALS, queryDate); org.intermine.objectstore.query.Constraint resLTEConstraint = MainHelper.makeQueryDateConstraint(qn, lteConstraint); assertEquals(expLTEConstraint, resLTEConstraint); SimpleConstraint expGTConstraint = new SimpleConstraint((QueryEvaluable) qn, ConstraintOp.LESS_THAN, new QueryValue(startOfDay)); Constraint gtConstraint = new Constraint(ConstraintOp.LESS_THAN, queryDate); org.intermine.objectstore.query.Constraint resGTConstraint = MainHelper.makeQueryDateConstraint(qn, gtConstraint); assertEquals(expGTConstraint, resGTConstraint); SimpleConstraint expGTEConstraint = new SimpleConstraint((QueryEvaluable) qn, ConstraintOp.LESS_THAN_EQUALS, new QueryValue(endOfDay)); Constraint gteConstraint = new Constraint(ConstraintOp.LESS_THAN_EQUALS, queryDate); org.intermine.objectstore.query.Constraint resGTEConstraint = MainHelper.makeQueryDateConstraint(qn, gteConstraint); assertEquals(expGTEConstraint, resGTEConstraint); ConstraintSet expEQConstraint = new ConstraintSet(ConstraintOp.AND); SimpleConstraint expEQStartConstraint = new SimpleConstraint((QueryEvaluable) qn, ConstraintOp.GREATER_THAN_EQUALS, new QueryValue(startOfDay)); SimpleConstraint expEQEndConstraint = new SimpleConstraint((QueryEvaluable) qn, ConstraintOp.LESS_THAN_EQUALS, new QueryValue(endOfDay)); expEQConstraint.addConstraint(expEQStartConstraint); expEQConstraint.addConstraint(expEQEndConstraint); Constraint eqConstraint = new Constraint(ConstraintOp.EQUALS, queryDate); org.intermine.objectstore.query.Constraint resEQConstraint = MainHelper.makeQueryDateConstraint(qn, eqConstraint); assertEquals(expEQConstraint, resEQConstraint); ConstraintSet expNEQConstraint = new ConstraintSet(ConstraintOp.OR); SimpleConstraint expNEQStartConstraint = new SimpleConstraint((QueryEvaluable) qn, ConstraintOp.LESS_THAN, new QueryValue(startOfDay)); SimpleConstraint expNEQEndConstraint = new SimpleConstraint((QueryEvaluable) qn, ConstraintOp.GREATER_THAN, new QueryValue(endOfDay)); expNEQConstraint.addConstraint(expNEQStartConstraint); expNEQConstraint.addConstraint(expNEQEndConstraint); Constraint neqConstraint = new Constraint(ConstraintOp.NOT_EQUALS, queryDate); org.intermine.objectstore.query.Constraint resNEQConstraint = MainHelper.makeQueryDateConstraint(qn, neqConstraint); assertEquals(expNEQConstraint, resNEQConstraint); } // test that loop constraint queries are generated correctly public void testLoopConstraint() throws Exception { Map queries = readQueries(); PathQuery pq = (PathQuery) queries.get("loopConstraint"); Query q = MainHelper.makeQuery(pq, new HashMap(), null, bagQueryRunner, new HashMap(), false); String got = q.toString(); String iql = "SELECT DISTINCT a1_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a2_ WHERE (a1_.departments CONTAINS a2_ AND a2_.company CONTAINS a1_) ORDER BY a1_.name"; assertEquals("Expected: " + iql + ", got: " + got, iql, got); } private Map readQueries() throws Exception { InputStream is = getClass().getClassLoader().getResourceAsStream("MainHelperTest.xml"); Map ret = PathQueryBinding.unmarshal(new InputStreamReader(is)); return ret; } public void test1() throws Exception { doQuery("<query name=\"test\" model=\"testmodel\" view=\"Employee\"></query>", "SELECT DISTINCT a1_ FROM org.intermine.model.testmodel.Employee AS a1_ ORDER BY a1_", "org.intermine.objectstore.query.QueryClass cannot be cast to org.intermine.objectstore.query.QueryField|org.intermine.objectstore.query.QueryClass"); } public void test2() throws Exception { doQuery("<query name=\"test\" model=\"testmodel\" view=\"Employee\"><node path=\"Employee\" type=\"Employee\"></node><node path=\"Employee.age\" type=\"int\"><constraint op=\"&gt;=\" value=\"10\" description=\"\" identifier=\"\" code=\"A\"></constraint></node></query>", "SELECT DISTINCT a1_ FROM org.intermine.model.testmodel.Employee AS a1_ WHERE a1_.age >= 10 ORDER BY a1_", "org.intermine.objectstore.query.QueryClass cannot be cast to org.intermine.objectstore.query.QueryField|org.intermine.objectstore.query.QueryClass"); } public void test3() throws Exception { doQuery("<query name=\"test\" model=\"testmodel\" view=\"Employee\" constraintLogic=\"A and B\"><node path=\"Employee\" type=\"Employee\"></node><node path=\"Employee.age\" type=\"int\"><constraint op=\"&gt;=\" value=\"10\" description=\"\" identifier=\"\" code=\"A\"></constraint></node><node path=\"Employee.fullTime\" type=\"boolean\"><constraint op=\"=\" value=\"true\" description=\"\" identifier=\"\" code=\"B\"></constraint></node></query>", "SELECT DISTINCT a1_ FROM org.intermine.model.testmodel.Employee AS a1_ WHERE (a1_.age >= 10 AND a1_.fullTime = true) ORDER BY a1_", "org.intermine.objectstore.query.QueryClass cannot be cast to org.intermine.objectstore.query.QueryField|org.intermine.objectstore.query.QueryClass"); } public void test4() throws Exception { doQuery("<query name=\"test\" model=\"testmodel\" view=\"Employee\" constraintLogic=\"A or B\"><node path=\"Employee\" type=\"Employee\"></node><node path=\"Employee.age\" type=\"int\"><constraint op=\"&gt;=\" value=\"10\" description=\"\" identifier=\"\" code=\"A\"></constraint></node><node path=\"Employee.fullTime\" type=\"boolean\"><constraint op=\"=\" value=\"true\" description=\"\" identifier=\"\" code=\"B\"></constraint></node></query>", "SELECT DISTINCT a1_ FROM org.intermine.model.testmodel.Employee AS a1_ WHERE (a1_.age >= 10 OR a1_.fullTime = true) ORDER BY a1_", "org.intermine.objectstore.query.QueryClass cannot be cast to org.intermine.objectstore.query.QueryField|org.intermine.objectstore.query.QueryClass"); } public void test5() throws Exception { doQuery("<query name=\"test\" model=\"testmodel\" view=\"Employee\" constraintLogic=\"(A or B) and C\"><node path=\"Employee\" type=\"Employee\"></node><node path=\"Employee.age\" type=\"int\"><constraint op=\"&gt;=\" value=\"10\" description=\"\" identifier=\"\" code=\"A\"></constraint></node><node path=\"Employee.fullTime\" type=\"boolean\"><constraint op=\"=\" value=\"true\" description=\"\" identifier=\"\" code=\"B\"></constraint></node><node path=\"Employee.name\" type=\"String\"><constraint op=\"=\" value=\"EmployeeA2\" description=\"\" identifier=\"\" code=\"C\"></constraint></node></query>", "SELECT DISTINCT a1_ FROM org.intermine.model.testmodel.Employee AS a1_ WHERE ((a1_.age >= 10 OR a1_.fullTime = true) AND LOWER(a1_.name) LIKE 'employeea2') ORDER BY a1_", "org.intermine.objectstore.query.QueryClass cannot be cast to org.intermine.objectstore.query.QueryField|org.intermine.objectstore.query.QueryClass"); } public void test7() throws Exception { doQuery("<query name=\"test\" model=\"testmodel\" view=\"Employee Employee.department\"><node path=\"Employee\" type=\"Employee\"></node><node path=\"Employee.department\" type=\"Department\"></node><node path=\"Employee.department.employees\" type=\"Employee\"><constraint op=\"=\" value=\"Employee\"></constraint></node></query>", "SELECT DISTINCT a1_, a2_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_ WHERE (a1_.department CONTAINS a2_ AND a2_.employees CONTAINS a1_) ORDER BY a1_, a2_", "org.intermine.objectstore.query.QueryClass cannot be cast to org.intermine.objectstore.query.QueryField|org.intermine.objectstore.query.QueryClass", "org.intermine.objectstore.query.QueryClass cannot be cast to org.intermine.objectstore.query.QueryField|org.intermine.objectstore.query.QueryClass"); } public void test8() throws Exception { doQuery("<query name=\"test\" model=\"testmodel\" view=\"Company.name Company.contractors.name\"><node path=\"Company\" type=\"Company\"></node><node path=\"Company.contractors\" type=\"Contractor\"></node><node path=\"Company.oldContracts\" type=\"Contractor\"><constraint op=\"=\" value=\"Company.contractors\" description=\"\" identifier=\"\" code=\"A\"></constraint></node></query>", "SELECT DISTINCT a1_, a2_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Contractor AS a2_ WHERE (a1_.contractors CONTAINS a2_ AND a1_.oldContracts CONTAINS a2_) ORDER BY a1_.name, a2_.name", "SELECT DISTINCT a1_.a3_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a1_.name AS a3_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Contractor AS a2_ WHERE (a1_.contractors CONTAINS a2_ AND a1_.oldContracts CONTAINS a2_)) AS a1_ GROUP BY a1_.a3_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a3_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a2_.name AS a3_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Contractor AS a2_ WHERE (a1_.contractors CONTAINS a2_ AND a1_.oldContracts CONTAINS a2_)) AS a1_ GROUP BY a1_.a3_ ORDER BY COUNT(*) DESC"); } public void test9() throws Exception { doQuery("<query name=\"test\" model=\"testmodel\" view=\"Employee.name Employee.department.name Employee.department.company.name Employee.age Employee.fullTime Employee.address.address\"><node path=\"Employee\" type=\"Employee\"></node><node path=\"Employee.department\" type=\"Department\"></node><node path=\"Employee.department.company\" type=\"Company\"></node><node path=\"Employee.department.company.address\" type=\"Address\"><constraint op=\"=\" value=\"Employee.address\" description=\"\" identifier=\"\" code=\"A\"></constraint></node><node path=\"Employee.address\" type=\"Address\"></node></query>", "SELECT DISTINCT a1_, a2_, a3_, a4_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_, org.intermine.model.testmodel.Address AS a4_ WHERE (a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_ AND a1_.address CONTAINS a4_ AND a3_.address CONTAINS a4_) ORDER BY a1_.name, a2_.name, a3_.name, a1_.age, a1_.fullTime, a4_.address", "SELECT DISTINCT a1_.a5_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a3_, a4_, a1_.name AS a5_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_, org.intermine.model.testmodel.Address AS a4_ WHERE (a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_ AND a1_.address CONTAINS a4_ AND a3_.address CONTAINS a4_)) AS a1_ GROUP BY a1_.a5_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a5_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a3_, a4_, a2_.name AS a5_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_, org.intermine.model.testmodel.Address AS a4_ WHERE (a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_ AND a1_.address CONTAINS a4_ AND a3_.address CONTAINS a4_)) AS a1_ GROUP BY a1_.a5_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a5_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a3_, a4_, a3_.name AS a5_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_, org.intermine.model.testmodel.Address AS a4_ WHERE (a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_ AND a1_.address CONTAINS a4_ AND a3_.address CONTAINS a4_)) AS a1_ GROUP BY a1_.a5_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT MIN(a1_.a5_) AS a2_, MAX(a1_.a5_) AS a3_, AVG(a1_.a5_) AS a4_, STDDEV(a1_.a5_) AS a5_ FROM (SELECT DISTINCT a1_, a2_, a3_, a4_, a1_.age AS a5_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_, org.intermine.model.testmodel.Address AS a4_ WHERE (a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_ AND a1_.address CONTAINS a4_ AND a3_.address CONTAINS a4_)) AS a1_", "SELECT DISTINCT a1_.a5_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a3_, a4_, a1_.fullTime AS a5_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_, org.intermine.model.testmodel.Address AS a4_ WHERE (a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_ AND a1_.address CONTAINS a4_ AND a3_.address CONTAINS a4_)) AS a1_ GROUP BY a1_.a5_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a5_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a3_, a4_, a4_.address AS a5_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_, org.intermine.model.testmodel.Address AS a4_ WHERE (a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_ AND a1_.address CONTAINS a4_ AND a3_.address CONTAINS a4_)) AS a1_ GROUP BY a1_.a5_ ORDER BY COUNT(*) DESC"); } public void test10() throws Exception { doQuery("<query name=\"test\" model=\"testmodel\" view=\"Employee.name Employee.department.name Employee.department.company.name Employee.age Employee.fullTime Employee.address.address\"><node path=\"Employee\" type=\"Employee\"></node><node path=\"Employee.department\" type=\"Department\"></node><node path=\"Employee.department.company\" type=\"Company\"></node><node path=\"Employee.department.company.address\" type=\"Address\"><constraint op=\"!=\" value=\"Employee.address\" description=\"\" identifier=\"\" code=\"A\"></constraint></node><node path=\"Employee.address\" type=\"Address\"></node></query>", "SELECT DISTINCT a1_, a2_, a3_, a5_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_, org.intermine.model.testmodel.Address AS a4_, org.intermine.model.testmodel.Address AS a5_ WHERE (a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_ AND a3_.address CONTAINS a4_ AND a1_.address CONTAINS a5_ AND a4_ != a5_) ORDER BY a1_.name, a2_.name, a3_.name, a1_.age, a1_.fullTime, a5_.address", "SELECT DISTINCT a1_.a6_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a3_, a5_, a1_.name AS a6_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_, org.intermine.model.testmodel.Address AS a4_, org.intermine.model.testmodel.Address AS a5_ WHERE (a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_ AND a3_.address CONTAINS a4_ AND a1_.address CONTAINS a5_ AND a4_ != a5_)) AS a1_ GROUP BY a1_.a6_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a6_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a3_, a5_, a2_.name AS a6_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_, org.intermine.model.testmodel.Address AS a4_, org.intermine.model.testmodel.Address AS a5_ WHERE (a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_ AND a3_.address CONTAINS a4_ AND a1_.address CONTAINS a5_ AND a4_ != a5_)) AS a1_ GROUP BY a1_.a6_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a6_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a3_, a5_, a3_.name AS a6_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_, org.intermine.model.testmodel.Address AS a4_, org.intermine.model.testmodel.Address AS a5_ WHERE (a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_ AND a3_.address CONTAINS a4_ AND a1_.address CONTAINS a5_ AND a4_ != a5_)) AS a1_ GROUP BY a1_.a6_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT MIN(a1_.a6_) AS a2_, MAX(a1_.a6_) AS a3_, AVG(a1_.a6_) AS a4_, STDDEV(a1_.a6_) AS a5_ FROM (SELECT DISTINCT a1_, a2_, a3_, a5_, a1_.age AS a6_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_, org.intermine.model.testmodel.Address AS a4_, org.intermine.model.testmodel.Address AS a5_ WHERE (a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_ AND a3_.address CONTAINS a4_ AND a1_.address CONTAINS a5_ AND a4_ != a5_)) AS a1_", "SELECT DISTINCT a1_.a6_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a3_, a5_, a1_.fullTime AS a6_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_, org.intermine.model.testmodel.Address AS a4_, org.intermine.model.testmodel.Address AS a5_ WHERE (a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_ AND a3_.address CONTAINS a4_ AND a1_.address CONTAINS a5_ AND a4_ != a5_)) AS a1_ GROUP BY a1_.a6_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a6_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a3_, a5_, a5_.address AS a6_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_, org.intermine.model.testmodel.Address AS a4_, org.intermine.model.testmodel.Address AS a5_ WHERE (a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_ AND a3_.address CONTAINS a4_ AND a1_.address CONTAINS a5_ AND a4_ != a5_)) AS a1_ GROUP BY a1_.a6_ ORDER BY COUNT(*) DESC"); } public void test11() throws Exception { doQuery("<query name=\"test\" model=\"testmodel\" view=\"Employee.name Employee.department.name Employee.department.company.name Employee.age Employee.fullTime Employee.department.company.address.address\"><node path=\"Employee\" type=\"Employee\"></node><node path=\"Employee.department\" type=\"Department\"></node><node path=\"Employee.department.company\" type=\"Company\"></node><node path=\"Employee.department.company.address\" type=\"Address\"><constraint op=\"=\" value=\"Employee.address\" description=\"\" identifier=\"\" code=\"A\"></constraint></node><node path=\"Employee.address\" type=\"Address\"></node></query>", "SELECT DISTINCT a1_, a2_, a3_, a4_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_, org.intermine.model.testmodel.Address AS a4_ WHERE (a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_ AND a1_.address CONTAINS a4_ AND a3_.address CONTAINS a4_) ORDER BY a1_.name, a2_.name, a3_.name, a1_.age, a1_.fullTime, a4_.address", "SELECT DISTINCT a1_.a5_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a3_, a4_, a1_.name AS a5_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_, org.intermine.model.testmodel.Address AS a4_ WHERE (a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_ AND a1_.address CONTAINS a4_ AND a3_.address CONTAINS a4_)) AS a1_ GROUP BY a1_.a5_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a5_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a3_, a4_, a2_.name AS a5_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_, org.intermine.model.testmodel.Address AS a4_ WHERE (a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_ AND a1_.address CONTAINS a4_ AND a3_.address CONTAINS a4_)) AS a1_ GROUP BY a1_.a5_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a5_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a3_, a4_, a3_.name AS a5_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_, org.intermine.model.testmodel.Address AS a4_ WHERE (a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_ AND a1_.address CONTAINS a4_ AND a3_.address CONTAINS a4_)) AS a1_ GROUP BY a1_.a5_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT MIN(a1_.a5_) AS a2_, MAX(a1_.a5_) AS a3_, AVG(a1_.a5_) AS a4_, STDDEV(a1_.a5_) AS a5_ FROM (SELECT DISTINCT a1_, a2_, a3_, a4_, a1_.age AS a5_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_, org.intermine.model.testmodel.Address AS a4_ WHERE (a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_ AND a1_.address CONTAINS a4_ AND a3_.address CONTAINS a4_)) AS a1_", "SELECT DISTINCT a1_.a5_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a3_, a4_, a1_.fullTime AS a5_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_, org.intermine.model.testmodel.Address AS a4_ WHERE (a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_ AND a1_.address CONTAINS a4_ AND a3_.address CONTAINS a4_)) AS a1_ GROUP BY a1_.a5_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a5_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a3_, a4_, a4_.address AS a5_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_, org.intermine.model.testmodel.Address AS a4_ WHERE (a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_ AND a1_.address CONTAINS a4_ AND a3_.address CONTAINS a4_)) AS a1_ GROUP BY a1_.a5_ ORDER BY COUNT(*) DESC"); } // This test exercises the MainHelper where there is a constraint that would be a loop if it wasn't ORed with another constraint. public void test12() throws Exception { doQuery("<query name=\"test\" model=\"testmodel\" view=\"Employee.name Employee.department.name Employee.department.company.name Employee.age Employee.fullTime Employee.department.company.address.address\" constraintLogic=\"A or B\"><node path=\"Employee\" type=\"Employee\"></node><node path=\"Employee.name\"><constraint op=\"=\" value=\"EmployeeA1\" code=\"A\"></constraint></node><node path=\"Employee.department\" type=\"Department\"></node><node path=\"Employee.department.company\" type=\"Company\"></node><node path=\"Employee.department.company.address\" type=\"Address\"><constraint op=\"=\" value=\"Employee.address\" description=\"\" identifier=\"\" code=\"B\"></constraint></node><node path=\"Employee.address\" type=\"Address\"></node></query>", "SELECT DISTINCT a1_, a2_, a3_, a4_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_, org.intermine.model.testmodel.Address AS a4_, org.intermine.model.testmodel.Address AS a5_ WHERE ((LOWER(a1_.name) LIKE 'employeea1' OR a4_ = a5_) AND a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_ AND a3_.address CONTAINS a4_ AND a1_.address CONTAINS a5_) ORDER BY a1_.name, a2_.name, a3_.name, a1_.age, a1_.fullTime, a4_.address", "SELECT DISTINCT a1_.a6_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a3_, a4_, a1_.name AS a6_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_, org.intermine.model.testmodel.Address AS a4_, org.intermine.model.testmodel.Address AS a5_ WHERE ((LOWER(a1_.name) LIKE 'employeea1' OR a4_ = a5_) AND a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_ AND a3_.address CONTAINS a4_ AND a1_.address CONTAINS a5_)) AS a1_ GROUP BY a1_.a6_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a6_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a3_, a4_, a2_.name AS a6_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_, org.intermine.model.testmodel.Address AS a4_, org.intermine.model.testmodel.Address AS a5_ WHERE ((LOWER(a1_.name) LIKE 'employeea1' OR a4_ = a5_) AND a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_ AND a3_.address CONTAINS a4_ AND a1_.address CONTAINS a5_)) AS a1_ GROUP BY a1_.a6_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a6_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a3_, a4_, a3_.name AS a6_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_, org.intermine.model.testmodel.Address AS a4_, org.intermine.model.testmodel.Address AS a5_ WHERE ((LOWER(a1_.name) LIKE 'employeea1' OR a4_ = a5_) AND a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_ AND a3_.address CONTAINS a4_ AND a1_.address CONTAINS a5_)) AS a1_ GROUP BY a1_.a6_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT MIN(a1_.a6_) AS a2_, MAX(a1_.a6_) AS a3_, AVG(a1_.a6_) AS a4_, STDDEV(a1_.a6_) AS a5_ FROM (SELECT DISTINCT a1_, a2_, a3_, a4_, a1_.age AS a6_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_, org.intermine.model.testmodel.Address AS a4_, org.intermine.model.testmodel.Address AS a5_ WHERE ((LOWER(a1_.name) LIKE 'employeea1' OR a4_ = a5_) AND a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_ AND a3_.address CONTAINS a4_ AND a1_.address CONTAINS a5_)) AS a1_", "SELECT DISTINCT a1_.a6_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a3_, a4_, a1_.fullTime AS a6_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_, org.intermine.model.testmodel.Address AS a4_, org.intermine.model.testmodel.Address AS a5_ WHERE ((LOWER(a1_.name) LIKE 'employeea1' OR a4_ = a5_) AND a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_ AND a3_.address CONTAINS a4_ AND a1_.address CONTAINS a5_)) AS a1_ GROUP BY a1_.a6_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a6_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a3_, a4_, a4_.address AS a6_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_, org.intermine.model.testmodel.Address AS a4_, org.intermine.model.testmodel.Address AS a5_ WHERE ((LOWER(a1_.name) LIKE 'employeea1' OR a4_ = a5_) AND a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_ AND a3_.address CONTAINS a4_ AND a1_.address CONTAINS a5_)) AS a1_ GROUP BY a1_.a6_ ORDER BY COUNT(*) DESC"); } public void test13() throws Exception { doQuery("<query name=\"test\" model=\"testmodel\" view=\"Employee.name Employee.department.name Employee.department.company.name Employee.age Employee.fullTime Employee.department.company.address.address\" constraintLogic=\"A and B and C\"><node path=\"Employee\" type=\"Employee\"></node><node path=\"Employee.name\"><constraint op=\"=\" value=\"EmployeeA1\" code=\"A\"></constraint></node><node path=\"Employee.department\" type=\"Department\"></node><node path=\"Employee.department.company\" type=\"Company\"></node><node path=\"Employee.department.company.address\" type=\"Address\"><constraint op=\"=\" value=\"Employee.address\" description=\"\" identifier=\"\" code=\"B\"></constraint></node><node path=\"Employee.address\" type=\"Address\"></node><node path=\"Employee.address.address\"><constraint op=\"!=\" value=\"fred\" code=\"C\"></constraint></node></query>", "SELECT DISTINCT a1_, a2_, a3_, a4_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_, org.intermine.model.testmodel.Address AS a4_ WHERE (LOWER(a1_.name) LIKE 'employeea1' AND a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_ AND a1_.address CONTAINS a4_ AND LOWER(a4_.address) NOT LIKE 'fred' AND a3_.address CONTAINS a4_) ORDER BY a1_.name, a2_.name, a3_.name, a1_.age, a1_.fullTime, a4_.address", "SELECT DISTINCT a1_.a5_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a3_, a4_, a1_.name AS a5_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_, org.intermine.model.testmodel.Address AS a4_ WHERE (LOWER(a1_.name) LIKE 'employeea1' AND a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_ AND a1_.address CONTAINS a4_ AND LOWER(a4_.address) NOT LIKE 'fred' AND a3_.address CONTAINS a4_)) AS a1_ GROUP BY a1_.a5_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a5_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a3_, a4_, a2_.name AS a5_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_, org.intermine.model.testmodel.Address AS a4_ WHERE (LOWER(a1_.name) LIKE 'employeea1' AND a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_ AND a1_.address CONTAINS a4_ AND LOWER(a4_.address) NOT LIKE 'fred' AND a3_.address CONTAINS a4_)) AS a1_ GROUP BY a1_.a5_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a5_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a3_, a4_, a3_.name AS a5_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_, org.intermine.model.testmodel.Address AS a4_ WHERE (LOWER(a1_.name) LIKE 'employeea1' AND a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_ AND a1_.address CONTAINS a4_ AND LOWER(a4_.address) NOT LIKE 'fred' AND a3_.address CONTAINS a4_)) AS a1_ GROUP BY a1_.a5_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT MIN(a1_.a5_) AS a2_, MAX(a1_.a5_) AS a3_, AVG(a1_.a5_) AS a4_, STDDEV(a1_.a5_) AS a5_ FROM (SELECT DISTINCT a1_, a2_, a3_, a4_, a1_.age AS a5_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_, org.intermine.model.testmodel.Address AS a4_ WHERE (LOWER(a1_.name) LIKE 'employeea1' AND a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_ AND a1_.address CONTAINS a4_ AND LOWER(a4_.address) NOT LIKE 'fred' AND a3_.address CONTAINS a4_)) AS a1_", "SELECT DISTINCT a1_.a5_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a3_, a4_, a1_.fullTime AS a5_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_, org.intermine.model.testmodel.Address AS a4_ WHERE (LOWER(a1_.name) LIKE 'employeea1' AND a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_ AND a1_.address CONTAINS a4_ AND LOWER(a4_.address) NOT LIKE 'fred' AND a3_.address CONTAINS a4_)) AS a1_ GROUP BY a1_.a5_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a5_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a3_, a4_, a4_.address AS a5_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_, org.intermine.model.testmodel.Address AS a4_ WHERE (LOWER(a1_.name) LIKE 'employeea1' AND a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_ AND a1_.address CONTAINS a4_ AND LOWER(a4_.address) NOT LIKE 'fred' AND a3_.address CONTAINS a4_)) AS a1_ GROUP BY a1_.a5_ ORDER BY COUNT(*) DESC"); } public void test14() throws Exception { doQuery("<query name=\"test\" model=\"testmodel\" view=\"Employee.name Employee.department.employees.name\"><node path=\"Employee\" type=\"Employee\"></node><node path=\"Employee.department\" type=\"Department\"></node><node path=\"Employee.department.employees\" type=\"Employee\"><constraint op=\"!=\" value=\"Employee\" description=\"\" identifier=\"\" code=\"A\"></constraint></node></query>", "SELECT DISTINCT a1_, a3_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Employee AS a3_ WHERE (a1_.department CONTAINS a2_ AND a2_.employees CONTAINS a3_ AND a3_ != a1_) ORDER BY a1_.name, a3_.name", "SELECT DISTINCT a1_.a4_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a3_, a1_.name AS a4_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Employee AS a3_ WHERE (a1_.department CONTAINS a2_ AND a2_.employees CONTAINS a3_ AND a3_ != a1_)) AS a1_ GROUP BY a1_.a4_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a4_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a3_, a3_.name AS a4_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Employee AS a3_ WHERE (a1_.department CONTAINS a2_ AND a2_.employees CONTAINS a3_ AND a3_ != a1_)) AS a1_ GROUP BY a1_.a4_ ORDER BY COUNT(*) DESC"); } public void test15() throws Exception { doQuery("<query name=\"test\" model=\"testmodel\" view=\"Employee.name Employee:department.name\"/>", "SELECT DISTINCT a1_, a1_.department AS a2_ FROM org.intermine.model.testmodel.Employee AS a1_ ORDER BY a1_.name", "SELECT DISTINCT a1_.a2_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a1_.name AS a2_ FROM org.intermine.model.testmodel.Employee AS a1_) AS a1_ GROUP BY a1_.a2_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a3_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a2_.name AS a3_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_ WHERE a1_.department CONTAINS a2_) AS a1_ GROUP BY a1_.a3_ ORDER BY COUNT(*) DESC"); } public void test16() throws Exception { doQuery("<query name=\"test\" model=\"testmodel\" view=\"Employee.name Employee:department.name Employee:department:company.name\"/>", "SELECT DISTINCT a1_, a2_.0 AS a3_, a2_.1 AS a4_ FROM org.intermine.model.testmodel.Employee AS a1_ ORDER BY a1_.name PATH a1_.department(SELECT default, default.company) AS a2_", "SELECT DISTINCT a1_.a4_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a1_.name AS a4_ FROM org.intermine.model.testmodel.Employee AS a1_) AS a1_ GROUP BY a1_.a4_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a5_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a4_, a4_.name AS a5_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a4_ WHERE a1_.department CONTAINS a4_) AS a1_ GROUP BY a1_.a5_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a4_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a3_, a3_.name AS a4_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_ WHERE (a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_)) AS a1_ GROUP BY a1_.a4_ ORDER BY COUNT(*) DESC"); } public void test17() throws Exception { doQuery("<query name=\"test\" model=\"testmodel\" view=\"Company.name Company:departments.name Company:departments:employees.name\"/>", "SELECT DISTINCT a1_, a1_.departments(SELECT default, default.employees(SELECT default)) AS a2_ FROM org.intermine.model.testmodel.Company AS a1_ ORDER BY a1_.name", "SELECT DISTINCT a1_.a2_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a1_.name AS a2_ FROM org.intermine.model.testmodel.Company AS a1_) AS a1_ GROUP BY a1_.a2_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a3_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a2_.name AS a3_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a2_ WHERE a1_.departments CONTAINS a2_) AS a1_ GROUP BY a1_.a3_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a4_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a3_, a3_.name AS a4_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Employee AS a3_ WHERE (a1_.departments CONTAINS a2_ AND a2_.employees CONTAINS a3_)) AS a1_ GROUP BY a1_.a4_ ORDER BY COUNT(*) DESC"); } public void test18() throws Exception { doQuery("<query name=\"test\" model=\"testmodel\" view=\"Company.name\"><node path=\"Company\" type=\"Company\"><constraint op=\"LOOKUP\" value=\"CompanyAkjhadf\"/></node></query>", "SELECT DISTINCT a1_ FROM org.intermine.model.testmodel.Company AS a1_ WHERE a1_.id IN ? ORDER BY a1_.name 1: []", "SELECT DISTINCT a1_.a2_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a1_.name AS a2_ FROM org.intermine.model.testmodel.Company AS a1_ WHERE a1_.id IN ? 1: []) AS a1_ GROUP BY a1_.a2_ ORDER BY COUNT(*) DESC"); } public void test19() throws Exception { doQuery("<query name=\"test\" model=\"testmodel\" view=\"Company.name Company:departments.name\"><node path=\"Company:departments.name\"><constraint op=\"=\" value=\"%1\"/></node></query>", "SELECT DISTINCT a1_, a1_.departments(SELECT default WHERE LOWER(default.name) LIKE '%1') AS a2_ FROM org.intermine.model.testmodel.Company AS a1_ ORDER BY a1_.name", "SELECT DISTINCT a1_.a2_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a1_.name AS a2_ FROM org.intermine.model.testmodel.Company AS a1_) AS a1_ GROUP BY a1_.a2_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a3_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a2_.name AS a3_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a2_ WHERE (a1_.departments CONTAINS a2_ AND LOWER(a2_.name) LIKE '%1')) AS a1_ GROUP BY a1_.a3_ ORDER BY COUNT(*) DESC"); } public void test20() throws Exception { doQuery("<query name=\"test\" model=\"testmodel\" view=\"Company.name Company:departments.name Company:departments.employees.name\"/>", "SELECT DISTINCT a1_, a1_.departments(SELECT default, a1_ FROM org.intermine.model.testmodel.Employee AS a1_ WHERE default.employees CONTAINS a1_) AS a2_ FROM org.intermine.model.testmodel.Company AS a1_ ORDER BY a1_.name", "SELECT DISTINCT a1_.a2_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a1_.name AS a2_ FROM org.intermine.model.testmodel.Company AS a1_) AS a1_ GROUP BY a1_.a2_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a4_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a3_, a2_.name AS a4_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Employee AS a3_ WHERE (a1_.departments CONTAINS a2_ AND a2_.employees CONTAINS a3_)) AS a1_ GROUP BY a1_.a4_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a4_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a3_, a3_.name AS a4_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Employee AS a3_ WHERE (a1_.departments CONTAINS a2_ AND a2_.employees CONTAINS a3_)) AS a1_ GROUP BY a1_.a4_ ORDER BY COUNT(*) DESC"); } public void test21() throws Exception { doQuery("<query name=\"test\" model=\"testmodel\" view=\"Department.name Department:company.name Department:company.departments.name\"/>", "SELECT DISTINCT a1_, a1_.company(SELECT default, a1_ FROM org.intermine.model.testmodel.Department AS a1_ WHERE default.departments CONTAINS a1_) AS a2_ FROM org.intermine.model.testmodel.Department AS a1_ ORDER BY a1_.name", "SELECT DISTINCT a1_.a2_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a1_.name AS a2_ FROM org.intermine.model.testmodel.Department AS a1_) AS a1_ GROUP BY a1_.a2_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a4_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a3_, a2_.name AS a4_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Company AS a2_, org.intermine.model.testmodel.Department AS a3_ WHERE (a1_.company CONTAINS a2_ AND a2_.departments CONTAINS a3_)) AS a1_ GROUP BY a1_.a4_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a4_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a3_, a3_.name AS a4_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Company AS a2_, org.intermine.model.testmodel.Department AS a3_ WHERE (a1_.company CONTAINS a2_ AND a2_.departments CONTAINS a3_)) AS a1_ GROUP BY a1_.a4_ ORDER BY COUNT(*) DESC"); } public void test22() throws Exception { doQuery("<query name=\"test\" model=\"testmodel\" view=\"Employee.name Employee:department:company.name\"/>", "SELECT DISTINCT a1_, a2_.0 AS a3_, a2_.1 AS a4_ FROM org.intermine.model.testmodel.Employee AS a1_ ORDER BY a1_.name PATH a1_.department(SELECT default, default.company) AS a2_", "SELECT DISTINCT a1_.a4_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a1_.name AS a4_ FROM org.intermine.model.testmodel.Employee AS a1_) AS a1_ GROUP BY a1_.a4_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a4_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a3_, a3_.name AS a4_ FROM org.intermine.model.testmodel.Employee AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_ WHERE (a1_.department CONTAINS a2_ AND a2_.company CONTAINS a3_)) AS a1_ GROUP BY a1_.a4_ ORDER BY COUNT(*) DESC"); } public void test23() throws Exception { doQuery("<query name=\"test\" model=\"testmodel\" view=\"Department.name Department:company.name Department:company.departments.name\"><node path=\"Department\"><constraint op=\"=\" value=\"Department:company.departments\"/></node></query>", "Error - loop constraint spans path expression from Department to Department:company.departments", "Error - loop constraint spans path expression from Department to Department:company.departments", "Error - loop constraint spans path expression from Department to Department:company.departments", "Error - loop constraint spans path expression from Department to Department:company.departments"); } public void test24() throws Exception { doQuery("<query name=\"test\" model=\"testmodel\" view=\"Department.name Department.company.name Department.company.departments.name\"><node path=\"Department\"><constraint op=\"=\" value=\"Department.company.departments\"/></node></query>", "SELECT DISTINCT a1_, a2_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Company AS a2_ WHERE (a1_.company CONTAINS a2_ AND a2_.departments CONTAINS a1_) ORDER BY a1_.name, a2_.name", "SELECT DISTINCT a1_.a3_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a1_.name AS a3_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Company AS a2_ WHERE (a1_.company CONTAINS a2_ AND a2_.departments CONTAINS a1_)) AS a1_ GROUP BY a1_.a3_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a3_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a2_.name AS a3_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Company AS a2_ WHERE (a1_.company CONTAINS a2_ AND a2_.departments CONTAINS a1_)) AS a1_ GROUP BY a1_.a3_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a3_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a1_.name AS a3_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Company AS a2_ WHERE (a1_.company CONTAINS a2_ AND a2_.departments CONTAINS a1_)) AS a1_ GROUP BY a1_.a3_ ORDER BY COUNT(*) DESC"); } public void test25() throws Exception { doQuery("<query name=\"test\" model=\"testmodel\" view=\"Department.name Department:company.name Department:company:departments.name\"/>", "SELECT DISTINCT a1_, a2_.0 AS a3_, a2_.1 AS a4_ FROM org.intermine.model.testmodel.Department AS a1_ ORDER BY a1_.name PATH a1_.company(SELECT default, default.departments(SELECT default)) AS a2_", "SELECT DISTINCT a1_.a4_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a1_.name AS a4_ FROM org.intermine.model.testmodel.Department AS a1_) AS a1_ GROUP BY a1_.a4_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a5_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a4_, a4_.name AS a5_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Company AS a4_ WHERE a1_.company CONTAINS a4_) AS a1_ GROUP BY a1_.a5_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a4_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a3_, a3_.name AS a4_ FROM org.intermine.model.testmodel.Department AS a1_, org.intermine.model.testmodel.Company AS a2_, org.intermine.model.testmodel.Department AS a3_ WHERE (a1_.company CONTAINS a2_ AND a2_.departments CONTAINS a3_)) AS a1_ GROUP BY a1_.a4_ ORDER BY COUNT(*) DESC"); } public void test26() throws Exception { doQuery("<query name=\"test\" model=\"testmodel\" view=\"Company.name Company:departments.name Company:departments:company.name\"/>", "SELECT DISTINCT a1_, a1_.departments(SELECT default, default.company) AS a2_ FROM org.intermine.model.testmodel.Company AS a1_ ORDER BY a1_.name", "SELECT DISTINCT a1_.a2_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a1_.name AS a2_ FROM org.intermine.model.testmodel.Company AS a1_) AS a1_ GROUP BY a1_.a2_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a3_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a2_.name AS a3_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a2_ WHERE a1_.departments CONTAINS a2_) AS a1_ GROUP BY a1_.a3_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a4_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a3_, a3_.name AS a4_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Company AS a3_ WHERE (a1_.departments CONTAINS a2_ AND a2_.company CONTAINS a3_)) AS a1_ GROUP BY a1_.a4_ ORDER BY COUNT(*) DESC"); } public void test27() throws Exception { doQuery("<query name=\"test\" model=\"testmodel\" view=\"Company.name Company:contractors.name Company:departments.name Company:departments:employees.name\"/>", "SELECT DISTINCT a1_, a1_.contractors(SELECT default) AS a2_, a1_.departments(SELECT default, default.employees(SELECT default)) AS a3_ FROM org.intermine.model.testmodel.Company AS a1_ ORDER BY a1_.name", "SELECT DISTINCT a1_.a3_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a1_.name AS a3_ FROM org.intermine.model.testmodel.Company AS a1_) AS a1_ GROUP BY a1_.a3_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a4_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a3_, a3_.name AS a4_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Contractor AS a3_ WHERE a1_.contractors CONTAINS a3_) AS a1_ GROUP BY a1_.a4_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a4_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a3_, a3_.name AS a4_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a3_ WHERE a1_.departments CONTAINS a3_) AS a1_ GROUP BY a1_.a4_ ORDER BY COUNT(*) DESC", "SELECT DISTINCT a1_.a4_ AS a2_, COUNT(*) AS a3_ FROM (SELECT DISTINCT a1_, a2_, a3_, a3_.name AS a4_ FROM org.intermine.model.testmodel.Company AS a1_, org.intermine.model.testmodel.Department AS a2_, org.intermine.model.testmodel.Employee AS a3_ WHERE (a1_.departments CONTAINS a2_ AND a2_.employees CONTAINS a3_)) AS a1_ GROUP BY a1_.a4_ ORDER BY COUNT(*) DESC"); } public void doQuery(String web, String iql, String ... summaries) throws Exception { try { Map parsed = PathQueryBinding.unmarshal(new StringReader(web)); PathQuery pq = (PathQuery) parsed.get("test"); Query q = MainHelper.makeQuery(pq, new HashMap(), null, bagQueryRunner, new HashMap(), false); String got = q.toString(); assertEquals("Expected: " + iql + ", but was: " + got, iql, got); } catch (Exception e) { if (!Arrays.asList(StringUtil.split(iql, "|")).contains(e.getMessage())) { throw e; } } int columnNo = 0; String summaryPath = null; try { Map parsed = PathQueryBinding.unmarshal(new StringReader(web)); PathQuery pq = (PathQuery) parsed.get("test"); for (String summary : summaries) { try { summaryPath = pq.getViewStrings().get(columnNo); Query q = MainHelper.makeSummaryQuery(pq, summaryPath, new HashMap(), new HashMap(), bagQueryRunner); String got = q.toString(); assertEquals("Failed for summaryPath " + summaryPath + ". Expected: " + summary + ", but was; " + got, summary, got); summaryPath = null; } catch (Exception e) { if (!Arrays.asList(StringUtil.split(summary, "|")).contains(e.getMessage())) { throw e; } } finally { columnNo++; } } assertEquals("Columns do not have summary tests", pq.getViewStrings().size(), columnNo); } catch (Exception e) { throw new Exception("Exception while testing summaryPath " + summaryPath, e); } } }
package org.intermine.web; import java.io.Reader; import java.sql.SQLException; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamWriter; import org.apache.log4j.Logger; import org.intermine.model.userprofile.Tag; import org.intermine.modelproduction.MetadataManager; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreWriter; import org.intermine.objectstore.intermine.ObjectStoreInterMineImpl; import org.intermine.objectstore.intermine.ObjectStoreWriterInterMineImpl; import org.intermine.sql.Database; import org.intermine.util.SAXParser; import org.intermine.web.bag.PkQueryIdUpgrader; import org.intermine.web.logic.bag.IdUpgrader; import org.intermine.web.logic.profile.Profile; import org.intermine.web.logic.profile.ProfileManager; import org.intermine.web.logic.profile.TagManager; import org.intermine.web.logic.profile.TagManagerFactory; import org.xml.sax.Attributes; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; /** * Code for reading and writing ProfileManager objects as XML * * @author Ernst Rutherford */ public class ProfileManagerBinding { private static final Logger LOG = Logger.getLogger(ProfileManagerBinding.class); /** * Default version of profile if it is not specified. */ public static final String ZERO_PROFILE_VERSION = "0"; /** * Convert the contents of a ProfileManager to XML and write the XML to the given writer. * @param profileManager the ProfileManager * @param writer the XMLStreamWriter to write to */ public static void marshal(ProfileManager profileManager, XMLStreamWriter writer) { try { writer.writeStartElement("userprofiles"); String profileVersion = getProfileVersion(profileManager.getObjectStore()); writer.writeAttribute(MetadataManager.PROFILE_FORMAT_VERSION, profileVersion); List usernames = profileManager.getProfileUserNames(); Iterator iter = usernames.iterator(); while (iter.hasNext()) { Profile profile = profileManager.getProfile((String) iter.next()); LOG.info("Writing profile: " + profile.getUsername()); long startTime = System.currentTimeMillis(); ProfileBinding.marshal(profile, profileManager.getObjectStore(), writer); long totalTime = System.currentTimeMillis() - startTime; LOG.info("Finished writing profile: " + profile.getUsername() + " took " + totalTime + "ms."); } writer.writeEndElement(); } catch (XMLStreamException e) { throw new RuntimeException(e); } } /** Returns profile format version from database. Version 0 corresponds to * situation when constraint values are saved in the internal format. Internal * format is format where '*' are replaced with % and other changes. * @see Util.wildcardSqlToUser() * @return saved format version or "0" if not saved in database */ private static String getProfileVersion(ObjectStore os) { Database database = ((ObjectStoreInterMineImpl) os).getDatabase(); try { String ret = MetadataManager.retrieve(database, MetadataManager.PROFILE_FORMAT_VERSION); if (ret == null) { ret = ZERO_PROFILE_VERSION; } return ret; } catch (SQLException e) { throw new RuntimeException("Error during retrieving profile version from database.", e); } } /** * Read a ProfileManager from an XML stream Reader * @param reader contains the ProfileManager XML * @param profileManager the ProfileManager to store the unmarshalled Profiles to * @param osw ObjectStoreWriter used to resolve object ids and write bags * @param idUpgrader the IdUpgrader to use to find objects in the new ObjectStore that * correspond to object in old bags. * @param abortOnError if true, throw an exception if there is a problem. If false, log the * problem and continue if possible (used by read-userprofile-xml). */ public static void unmarshal(Reader reader, ProfileManager profileManager, ObjectStoreWriter osw, PkQueryIdUpgrader idUpgrader, boolean abortOnError) { try { ProfileManagerHandler profileManagerHandler = new ProfileManagerHandler(profileManager, idUpgrader, osw, abortOnError); SAXParser.parse(new InputSource(reader), profileManagerHandler); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e); } } /** * Read a ProfileManager from an XML stream Reader. If there is a problem, throw an * exception. * @param reader contains the ProfileManager XML * @param profileManager the ProfileManager to store the unmarshalled Profiles to * @param osw ObjectStoreWriter used to resolve object ids and write bags * @param idUpgrader the IdUpgrader to use to find objects in the new ObjectStore that * correspond to object in old bags. */ public static void unmarshal(Reader reader, ProfileManager profileManager, ObjectStoreWriter osw, PkQueryIdUpgrader idUpgrader) { unmarshal(reader, profileManager, osw, idUpgrader, true); } } /** * Extension of DefaultHandler to handle parsing ProfileManagers * @author Kim Rutherford */ class ProfileManagerHandler extends DefaultHandler { private ProfileHandler profileHandler = null; private ProfileManager profileManager = null; private IdUpgrader idUpgrader; private ObjectStoreWriter osw; private boolean abortOnError; private long startTime = 0; private static final Logger LOG = Logger.getLogger(ProfileManagerBinding.class); /** * Create a new ProfileManagerHandler * @param profileManager the ProfileManager to store the unmarshalled Profile to * @param idUpgrader the IdUpgrader to use to find objects in the new ObjectStore that * correspond to object in old bags. * @param osw an ObjectStoreWriter to the production database, to write bags * @param abortOnError if true, throw an exception if there is a problem. If false, log the * problem and continue if possible (used by read-userprofile-xml). */ public ProfileManagerHandler(ProfileManager profileManager, IdUpgrader idUpgrader, ObjectStoreWriter osw, boolean abortOnError) { super(); this.profileManager = profileManager; this.idUpgrader = idUpgrader; this.osw = osw; this.abortOnError = abortOnError; } /** * {@inheritDoc} */ @Override public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { if (qName.equals("userprofiles")) { String value = attrs.getValue(MetadataManager.PROFILE_FORMAT_VERSION); saveProfileVersion(value, profileManager.getProfileObjectStoreWriter()); } if (qName.equals("userprofile")) { startTime = System.currentTimeMillis(); profileHandler = new ProfileHandler(profileManager, idUpgrader, osw, abortOnError); } if (profileHandler != null) { profileHandler.startElement(uri, localName, qName, attrs); } } private void saveProfileVersion(String value, ObjectStoreWriter osw) { if (value == null) { value = ProfileManagerBinding.ZERO_PROFILE_VERSION; } Database dat = ((ObjectStoreWriterInterMineImpl) osw).getDatabase(); try { MetadataManager.store(dat, MetadataManager.PROFILE_FORMAT_VERSION, value); System.out.println("Saving attribute with key: " + MetadataManager.PROFILE_FORMAT_VERSION + " and value: " + value); } catch (SQLException ex) { throw new RuntimeException("Saving profile format version to database failed.", ex); } } /** * {@inheritDoc} */ @Override public void endElement(String uri, String localName, String qName) throws SAXException { super.endElement(uri, localName, qName); if (qName.equals("userprofile")) { Profile profile = profileHandler.getProfile(); profileManager.createProfile(profile); Set<Tag> tags = profileHandler.getTags(); TagManager tagManager = new TagManagerFactory(profile.getProfileManager()).getTagManager(); for (Tag tag : tags) { try { tagManager.addTag(tag.getTagName(), tag.getObjectIdentifier(), tag.getType(), profile.getUsername()); } catch (RuntimeException e) { if (abortOnError) { throw e; } else { LOG.error("Error during adding tag: " + tag.toString(), e); } } } profileHandler = null; long totalTime = System.currentTimeMillis() - startTime; LOG.info("Finished profile: " + profile.getUsername() + " took " + totalTime + "ms."); } if (profileHandler != null) { profileHandler.endElement(uri, localName, qName); } } }
package org.opendaylight.controller.common.actor; import akka.actor.ActorPath; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.dispatch.BoundedDequeBasedMailbox; import akka.dispatch.MailboxType; import akka.dispatch.ProducesMessageQueue; import com.codahale.metrics.Gauge; import com.codahale.metrics.MetricRegistry; import com.google.common.base.Preconditions; import com.typesafe.config.Config; import org.opendaylight.controller.common.reporting.MetricsReporter; import scala.concurrent.duration.FiniteDuration; import java.util.concurrent.TimeUnit; public class MeteredBoundedMailbox implements MailboxType, ProducesMessageQueue<MeteredBoundedMailbox.MeteredMessageQueue> { private MeteredMessageQueue queue; private Integer capacity; private FiniteDuration pushTimeOut; private ActorPath actorPath; private MetricsReporter reporter; private final String QUEUE_SIZE = "queue-size"; private final String CAPACITY = "mailbox-capacity"; private final String TIMEOUT = "mailbox-push-timeout-time"; private final Long DEFAULT_TIMEOUT = 10L; public MeteredBoundedMailbox(ActorSystem.Settings settings, Config config) { Preconditions.checkArgument( config.hasPath("mailbox-capacity"), "Missing configuration [mailbox-capacity]" ); this.capacity = config.getInt(CAPACITY); Preconditions.checkArgument( this.capacity > 0, "mailbox-capacity must be > 0"); Long timeout = -1L; if ( config.hasPath(TIMEOUT) ){ timeout = config.getDuration(TIMEOUT, TimeUnit.NANOSECONDS); } else { timeout = DEFAULT_TIMEOUT; } Preconditions.checkArgument( timeout > 0, "mailbox-push-timeout-time must be > 0"); this.pushTimeOut = new FiniteDuration(timeout, TimeUnit.NANOSECONDS); reporter = MetricsReporter.getInstance(); } @Override public MeteredMessageQueue create(final scala.Option<ActorRef> owner, scala.Option<ActorSystem> system) { this.queue = new MeteredMessageQueue(this.capacity, this.pushTimeOut); monitorQueueSize(owner, this.queue); return this.queue; } private void monitorQueueSize(scala.Option<ActorRef> owner, final MeteredMessageQueue monitoredQueue) { if (owner.isEmpty()) { return; //there's no actor to monitor } actorPath = owner.get().path(); String actorInstanceId = Integer.toString(owner.get().hashCode()); MetricRegistry registry = reporter.getMetricsRegistry(); String actorName = registry.name(actorPath.toString(), actorInstanceId, QUEUE_SIZE); if (registry.getMetrics().containsKey(actorName)) return; //already registered registry.register(actorName, new Gauge<Integer>() { @Override public Integer getValue() { return monitoredQueue.size(); } }); } public static class MeteredMessageQueue extends BoundedDequeBasedMailbox.MessageQueue { public MeteredMessageQueue(int capacity, FiniteDuration pushTimeOut) { super(capacity, pushTimeOut); } } }
package org.usfirst.frc.team1736.robot; import edu.wpi.first.wpilibj.Timer; public class IntegralCalculator { private double prev_time; private double accumulator; private double[] point_num; private int choice; private double value; IntegralCalculator(int choice_in){ prev_time = Timer.getFPGATimestamp(); accumulator = 0; point_num = new double [5]; choice = choice_in; } public double calcIntegral(double in){ double cur_time = Timer.getFPGATimestamp(); /*Integration method - "Sample and hold"*/ point_num[4] = point_num[3]; point_num[3] = point_num[2]; point_num[2] = point_num[1]; point_num[1] = point_num[0]; point_num[0] = in; if (choice == 0) /*trapezoid rule*/{ value = ((cur_time-prev_time)/2)*(point_num[0] + point_num[1]); } if (choice == 1) /*simpson's rule*/{ value = (1/2)*((cur_time-prev_time)/6)*(point_num[0] + (4*point_num[1]) + point_num[2]); } if (choice == 2) /*simpson's 3/8 rule*/{ value = (1/3)*((cur_time-prev_time)/8)*(point_num[0] + (3*point_num[1]) + (3*point_num[2])+ point_num[3]); } if (choice == 3) /*boole's rule*/{ value = (1/4)*((cur_time-prev_time)/90)*((7*point_num[0]) + (32*point_num[1]) + (12*point_num[2])+ (32*point_num[3]) + (7 * point_num[4])); } if (choice == 4) /*rectangular rule*/ { value += in * (cur_time - prev_time); } /*Save values for next loop and return*/ accumulator = accumulator + value; prev_time = cur_time; return accumulator; } public void resetIntegral(){ accumulator = 0; } }
package org.jetbrains.jps.incremental.java; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.Key; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.io.FileFilters; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.ExceptionUtil; import com.intellij.util.concurrency.Semaphore; import com.intellij.util.concurrency.SequentialTaskExecutor; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.JBIterable; import com.intellij.util.containers.SmartHashSet; import com.intellij.util.execution.ParametersListUtil; import com.intellij.util.io.PersistentEnumeratorBase; import com.intellij.util.lang.JavaVersion; import gnu.trove.THashMap; import gnu.trove.THashSet; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.jps.ModuleChunk; import org.jetbrains.jps.PathUtils; import org.jetbrains.jps.ProjectPaths; import org.jetbrains.jps.api.GlobalOptions; import org.jetbrains.jps.builders.BuildRootIndex; import org.jetbrains.jps.builders.DirtyFilesHolder; import org.jetbrains.jps.builders.FileProcessor; import org.jetbrains.jps.builders.impl.DirtyFilesHolderBase; import org.jetbrains.jps.builders.java.JavaBuilderExtension; import org.jetbrains.jps.builders.java.JavaBuilderUtil; import org.jetbrains.jps.builders.java.JavaCompilingTool; import org.jetbrains.jps.builders.java.JavaSourceRootDescriptor; import org.jetbrains.jps.builders.logging.ProjectBuilderLogger; import org.jetbrains.jps.builders.storage.BuildDataCorruptedException; import org.jetbrains.jps.cmdline.ProjectDescriptor; import org.jetbrains.jps.incremental.*; import org.jetbrains.jps.incremental.messages.BuildMessage; import org.jetbrains.jps.incremental.messages.CompilerMessage; import org.jetbrains.jps.incremental.messages.ProgressMessage; import org.jetbrains.jps.javac.*; import org.jetbrains.jps.model.JpsDummyElement; import org.jetbrains.jps.model.JpsProject; import org.jetbrains.jps.model.java.JpsJavaExtensionService; import org.jetbrains.jps.model.java.JpsJavaSdkType; import org.jetbrains.jps.model.java.LanguageLevel; import org.jetbrains.jps.model.java.compiler.*; import org.jetbrains.jps.model.library.sdk.JpsSdk; import org.jetbrains.jps.model.module.JpsModule; import org.jetbrains.jps.model.module.JpsModuleType; import org.jetbrains.jps.model.serialization.JpsModelSerializationDataService; import org.jetbrains.jps.model.serialization.PathMacroUtil; import org.jetbrains.jps.service.JpsServiceManager; import org.jetbrains.jps.service.SharedThreadPool; import javax.tools.*; import java.io.File; import java.io.FileFilter; import java.io.IOException; import java.net.ServerSocket; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Executor; import java.util.concurrent.Future; import java.util.function.BiConsumer; import java.util.stream.Collectors; import static com.intellij.openapi.util.Pair.pair; /** * @author Eugene Zhuravlev * @since 21.09.2011 */ public class JavaBuilder extends ModuleLevelBuilder { private static final Logger LOG = Logger.getInstance("#org.jetbrains.jps.incremental.java.JavaBuilder"); private static final String JAVA_EXTENSION = "java"; public static final String BUILDER_NAME = "java"; public static final Key<Boolean> IS_ENABLED = Key.create("_java_compiler_enabled_"); public static final FileFilter JAVA_SOURCES_FILTER = FileFilters.withExtension(JAVA_EXTENSION); private static final Key<Boolean> PREFER_TARGET_JDK_COMPILER = GlobalContextKey.create("_prefer_target_jdk_javac_"); private static final Key<JavaCompilingTool> COMPILING_TOOL = Key.create("_java_compiling_tool_"); private static final Key<ConcurrentMap<String, Collection<String>>> COMPILER_USAGE_STATISTICS = Key.create("_java_compiler_usage_stats_"); private static final List<String> COMPILABLE_EXTENSIONS = Collections.singletonList(JAVA_EXTENSION); private static final Set<String> FILTERED_OPTIONS = ContainerUtil.newHashSet( "-target" ); private static final Set<String> FILTERED_SINGLE_OPTIONS = ContainerUtil.newHashSet( "-g", "-deprecation", "-nowarn", "-verbose", "-proc:none", "-proc:only", "-proceedOnError" ); private static final List<ClassPostProcessor> ourClassProcessors = new ArrayList<>(); private static final Set<JpsModuleType<?>> ourCompilableModuleTypes = new HashSet<>(); @Nullable private static final File ourDefaultRtJar; static { for (JavaBuilderExtension extension : JpsServiceManager.getInstance().getExtensions(JavaBuilderExtension.class)) { ourCompilableModuleTypes.addAll(extension.getCompilableModuleTypes()); } File rtJar = null; StringTokenizer tokenizer = new StringTokenizer(System.getProperty("sun.boot.class.path", ""), File.pathSeparator, false); while (tokenizer.hasMoreTokens()) { File file = new File(tokenizer.nextToken()); if ("rt.jar".equals(file.getName())) { rtJar = file; break; } } ourDefaultRtJar = rtJar; } public static void registerClassPostProcessor(ClassPostProcessor processor) { ourClassProcessors.add(processor); } private final Executor myTaskRunner; public JavaBuilder(Executor tasksExecutor) { super(BuilderCategory.TRANSLATOR); myTaskRunner = SequentialTaskExecutor.createSequentialApplicationPoolExecutor("JavaBuilder Pool", tasksExecutor); //add here class processors in the sequence they should be executed } @Override @NotNull public String getPresentableName() { return BUILDER_NAME; } @Override public void buildStarted(CompileContext context) { final String compilerId = getUsedCompilerId(context); if (LOG.isDebugEnabled()) { LOG.debug("Java compiler ID: " + compilerId); } JavaCompilingTool compilingTool = JavaBuilderUtil.findCompilingTool(compilerId); COMPILING_TOOL.set(context, compilingTool); COMPILER_USAGE_STATISTICS.set(context, new ConcurrentHashMap<>()); } @Override public void chunkBuildStarted(final CompileContext context, final ModuleChunk chunk) { // before the first compilation round starts: find and mark dirty all classes that depend on removed or moved classes so // that all such files are compiled in the first round. try { JavaBuilderUtil.markDirtyDependenciesForInitialRound(context, new DirtyFilesHolderBase<JavaSourceRootDescriptor, ModuleBuildTarget>(context) { @Override public void processDirtyFiles(@NotNull FileProcessor<JavaSourceRootDescriptor, ModuleBuildTarget> processor) throws IOException { FSOperations.processFilesToRecompile(context, chunk, processor); } }, chunk); } catch (IOException e) { throw new RuntimeException(e); } } @Override public void buildFinished(CompileContext context) { final ConcurrentMap<String, Collection<String>> stats = COMPILER_USAGE_STATISTICS.get(context); if (stats.size() == 1) { final Map.Entry<String, Collection<String>> entry = stats.entrySet().iterator().next(); final String compilerName = entry.getKey(); context.processMessage(new CompilerMessage("", BuildMessage.Kind.JPS_INFO, compilerName + " was used to compile java sources")); LOG.info(compilerName + " was used to compile " + entry.getValue()); } else { for (Map.Entry<String, Collection<String>> entry : stats.entrySet()) { final String compilerName = entry.getKey(); final Collection<String> moduleNames = entry.getValue(); context.processMessage(new CompilerMessage("", BuildMessage.Kind.JPS_INFO, moduleNames.size() == 1 ? compilerName + " was used to compile [" + moduleNames.iterator().next() + "]" : compilerName + " was used to compile " + moduleNames.size() + " modules" )); LOG.info(compilerName + " was used to compile " + moduleNames); } } } @Override public List<String> getCompilableFileExtensions() { return COMPILABLE_EXTENSIONS; } @Override public ExitCode build(@NotNull CompileContext context, @NotNull ModuleChunk chunk, @NotNull DirtyFilesHolder<JavaSourceRootDescriptor, ModuleBuildTarget> dirtyFilesHolder, @NotNull OutputConsumer outputConsumer) throws ProjectBuildException, IOException { JavaCompilingTool compilingTool = COMPILING_TOOL.get(context); if (!IS_ENABLED.get(context, Boolean.TRUE) || compilingTool == null) { return ExitCode.NOTHING_DONE; } return doBuild(context, chunk, dirtyFilesHolder, outputConsumer, compilingTool); } public ExitCode doBuild(@NotNull CompileContext context, @NotNull ModuleChunk chunk, @NotNull DirtyFilesHolder<JavaSourceRootDescriptor, ModuleBuildTarget> dirtyFilesHolder, @NotNull OutputConsumer outputConsumer, @NotNull JavaCompilingTool compilingTool) throws ProjectBuildException, IOException { try { final Set<File> filesToCompile = new THashSet<>(FileUtil.FILE_HASHING_STRATEGY); dirtyFilesHolder.processDirtyFiles((target, file, descriptor) -> { if (JAVA_SOURCES_FILTER.accept(file) && ourCompilableModuleTypes.contains(target.getModule().getModuleType())) { filesToCompile.add(file); } return true; }); int javaModulesCount = 0; if ((!filesToCompile.isEmpty() || dirtyFilesHolder.hasRemovedFiles()) && getTargetPlatformLanguageVersion(chunk.representativeTarget().getModule()) >= 9) { for (ModuleBuildTarget target : chunk.getTargets()) { if (JavaBuilderUtil.findModuleInfoFile(context, target) != null) { javaModulesCount++; } } } if (JavaBuilderUtil.isCompileJavaIncrementally(context)) { ProjectBuilderLogger logger = context.getLoggingManager().getProjectBuilderLogger(); if (logger.isEnabled() && !filesToCompile.isEmpty()) { logger.logCompiledFiles(filesToCompile, BUILDER_NAME, "Compiling files:"); } } if (javaModulesCount > 1) { String prefix = "Cannot compile a module cycle with multiple module-info.java files: "; String message = chunk.getModules().stream().map(JpsModule::getName).collect(Collectors.joining(", ", prefix, "")); context.processMessage(new CompilerMessage(BUILDER_NAME, BuildMessage.Kind.ERROR, message)); return ExitCode.ABORT; } return compile(context, chunk, dirtyFilesHolder, filesToCompile, outputConsumer, compilingTool, javaModulesCount > 0); } catch (BuildDataCorruptedException | PersistentEnumeratorBase.CorruptedException | ProjectBuildException e) { throw e; } catch (Exception e) { LOG.info(e); String message = e.getMessage(); if (message == null || message.trim().isEmpty()) { message = "Internal error: \n" + ExceptionUtil.getThrowableText(e); } context.processMessage(new CompilerMessage(BUILDER_NAME, BuildMessage.Kind.ERROR, message)); throw new StopBuildException(); } } private ExitCode compile(CompileContext context, ModuleChunk chunk, DirtyFilesHolder<JavaSourceRootDescriptor, ModuleBuildTarget> dirtyFilesHolder, Collection<File> files, OutputConsumer outputConsumer, JavaCompilingTool compilingTool, boolean hasModules) throws Exception { ExitCode exitCode = ExitCode.NOTHING_DONE; final boolean hasSourcesToCompile = !files.isEmpty(); if (!hasSourcesToCompile && !dirtyFilesHolder.hasRemovedFiles()) { return exitCode; } final ProjectDescriptor pd = context.getProjectDescriptor(); JavaBuilderUtil.ensureModuleHasJdk(chunk.representativeTarget().getModule(), context, BUILDER_NAME); final Collection<File> classpath = ProjectPaths.getCompilationClasspath(chunk, false); final Collection<File> platformCp = ProjectPaths.getPlatformCompilationClasspath(chunk, false); // begin compilation round final OutputFilesSink outputSink = new OutputFilesSink(context, outputConsumer, JavaBuilderUtil.getDependenciesRegistrar(context), chunk.getPresentableShortName()); Collection<File> filesWithErrors = null; try { if (hasSourcesToCompile) { exitCode = ExitCode.OK; final Set<File> srcPath = new HashSet<>(); final BuildRootIndex index = pd.getBuildRootIndex(); for (ModuleBuildTarget target : chunk.getTargets()) { for (JavaSourceRootDescriptor rd : index.getTempTargetRoots(target, context)) { srcPath.add(rd.root); } } final DiagnosticSink diagnosticSink = new DiagnosticSink(context); final String chunkName = chunk.getName(); context.processMessage(new ProgressMessage("Parsing java... [" + chunk.getPresentableShortName() + "]")); final int filesCount = files.size(); boolean compiledOk = true; if (filesCount > 0) { LOG.info("Compiling " + filesCount + " java files; module: " + chunkName + (chunk.containsTests() ? " (tests)" : "")); if (LOG.isDebugEnabled()) { for (File file : files) { LOG.debug("Compiling " + file.getPath()); } LOG.debug(" classpath for " + chunkName + ":"); for (File file : classpath) { LOG.debug(" " + file.getAbsolutePath()); } LOG.debug(" platform classpath for " + chunkName + ":"); for (File file : platformCp) { LOG.debug(" " + file.getAbsolutePath()); } } try { compiledOk = compileJava(context, chunk, files, classpath, platformCp, srcPath, diagnosticSink, outputSink, compilingTool, hasModules); } finally { filesWithErrors = diagnosticSink.getFilesWithErrors(); } } context.checkCanceled(); if (!compiledOk && diagnosticSink.getErrorCount() == 0) { // unexpected exception occurred or compiler did not output any errors for some reason diagnosticSink.report(new PlainMessageDiagnostic(Diagnostic.Kind.ERROR, "Compilation failed: internal java compiler error")); } if (diagnosticSink.getErrorCount() > 0) { diagnosticSink.report(new JpsInfoDiagnostic("Errors occurred while compiling module '" + chunkName + "'")); } if (!Utils.PROCEED_ON_ERROR_KEY.get(context, Boolean.FALSE) && diagnosticSink.getErrorCount() > 0) { throw new StopBuildException( "Compilation failed: errors: " + diagnosticSink.getErrorCount() + "; warnings: " + diagnosticSink.getWarningCount() ); } } } finally { JavaBuilderUtil.registerFilesToCompile(context, files); if (filesWithErrors != null) { JavaBuilderUtil.registerFilesWithErrors(context, filesWithErrors); } JavaBuilderUtil.registerSuccessfullyCompiled(context, outputSink.getSuccessfullyCompiled()); } return exitCode; } private boolean compileJava(CompileContext context, ModuleChunk chunk, Collection<File> files, Collection<File> originalClassPath, Collection<File> originalPlatformCp, Collection<File> sourcePath, DiagnosticOutputConsumer diagnosticSink, OutputFileConsumer outputSink, JavaCompilingTool compilingTool, boolean hasModules) { final Semaphore counter = new Semaphore(); COUNTER_KEY.set(context, counter); final Set<JpsModule> modules = chunk.getModules(); ProcessorConfigProfile profile = null; if (modules.size() == 1) { final JpsJavaCompilerConfiguration compilerConfig = JpsJavaExtensionService.getInstance().getCompilerConfiguration(context.getProjectDescriptor().getProject()); assert compilerConfig != null; profile = compilerConfig.getAnnotationProcessingProfile(modules.iterator().next()); } else { final String message = validateCycle(context, chunk); if (message != null) { diagnosticSink.report(new PlainMessageDiagnostic(Diagnostic.Kind.ERROR, message)); return false; } } final Map<File, Set<File>> outs = buildOutputDirectoriesMap(context, chunk); try { final int targetLanguageLevel = getTargetPlatformLanguageVersion(chunk.representativeTarget().getModule()); final boolean shouldForkJavac = shouldForkCompilerProcess(context, chunk, targetLanguageLevel); // when forking external javac, compilers from SDK 1.6 and higher are supported Pair<String, Integer> forkSdk = null; if (shouldForkJavac) { forkSdk = getForkedJavacSdk(chunk, targetLanguageLevel); if (forkSdk == null) { String text = "Cannot start javac process for " + chunk.getName() + ": unknown JDK home path.\nPlease check project configuration."; diagnosticSink.report(new PlainMessageDiagnostic(Diagnostic.Kind.ERROR, text)); return false; } } final int compilerSdkVersion = forkSdk == null ? JavaVersion.current().feature : forkSdk.getSecond(); final Pair<List<String>, List<String>> vm_compilerOptions = getCompilationOptions( compilerSdkVersion, context, chunk, profile, compilingTool ); final List<String> vmOptions = vm_compilerOptions.first; final List<String> options = vm_compilerOptions.second; if (LOG.isDebugEnabled()) { String mode = shouldForkJavac ? "fork" : "in-process"; LOG.debug("Compiling chunk [" + chunk.getName() + "] with options: \"" + StringUtil.join(options, " ") + "\", mode=" + mode); } Collection<File> platformCp = calcEffectivePlatformCp(originalPlatformCp, options, compilingTool); if (platformCp == null) { String text = "Compact compilation profile was requested, but target platform for module \"" + chunk.getName() + "\"" + " differs from javac's platform (" + System.getProperty("java.version") + ")\n" + "Compilation profiles are not supported for such configuration"; context.processMessage(new CompilerMessage(BUILDER_NAME, BuildMessage.Kind.ERROR, text)); return false; } Collection<File> classPath = originalClassPath; Collection<File> modulePath = Collections.emptyList(); Collection<File> upgradeModulePath = Collections.emptyList(); if (hasModules) { // in Java 9, named modules are not allowed to read classes from the classpath // moreover, the compiler requires all transitive dependencies to be on the module path modulePath = ProjectPaths.getCompilationModulePath(chunk, false); classPath = Collections.emptyList(); // modules located above the JDK make a module upgrade path upgradeModulePath = platformCp; platformCp = Collections.emptyList(); } if (!platformCp.isEmpty() && (getChunkSdkVersion(chunk)) >= 9) { // if chunk's SDK is 9 or higher, there is no way to specify full platform classpath // because platform classes are stored in jimage binary files with unknown format. // Because of this we are clearing platform classpath so that javac will resolve against its own boot classpath // and prepending additional jars from the JDK configuration to compilation classpath classPath = JBIterable.from(platformCp).append(classPath).toList(); platformCp = Collections.emptyList(); } final ClassProcessingConsumer classesConsumer = new ClassProcessingConsumer(context, outputSink); final boolean rc; if (!shouldForkJavac) { updateCompilerUsageStatistics(context, compilingTool.getDescription(), chunk); rc = JavacMain.compile( options, files, classPath, platformCp, modulePath, upgradeModulePath, sourcePath, outs, diagnosticSink, classesConsumer, context.getCancelStatus(), compilingTool ); } else { updateCompilerUsageStatistics(context, "javac " + forkSdk.getSecond(), chunk); final ExternalJavacManager server = ensureJavacServerStarted(context); rc = server.forkJavac( forkSdk.getFirst(), Utils.suggestForkedCompilerHeapSize(), vmOptions, options, platformCp, classPath, upgradeModulePath, modulePath, sourcePath, files, outs, diagnosticSink, classesConsumer, compilingTool, context.getCancelStatus() ); } return rc; } finally { counter.waitFor(); } } private static void updateCompilerUsageStatistics(CompileContext context, String compilerName, ModuleChunk chunk) { final ConcurrentMap<String, Collection<String>> map = COMPILER_USAGE_STATISTICS.get(context); Collection<String> names = map.get(compilerName); if (names == null) { names = Collections.synchronizedSet(new HashSet<>()); final Collection<String> prev = map.putIfAbsent(compilerName, names); if (prev != null) { names = prev; } } for (JpsModule module : chunk.getModules()) { names.add(module.getName()); } } @Nullable public static String validateCycle(CompileContext context, ModuleChunk chunk) { final JpsJavaExtensionService javaExt = JpsJavaExtensionService.getInstance(); final JpsJavaCompilerConfiguration compilerConfig = javaExt.getCompilerConfiguration(context.getProjectDescriptor().getProject()); assert compilerConfig != null; final Set<JpsModule> modules = chunk.getModules(); Pair<String, LanguageLevel> pair = null; for (JpsModule module : modules) { final LanguageLevel moduleLevel = javaExt.getLanguageLevel(module); if (pair == null) { pair = pair(module.getName(), moduleLevel); // first value } else if (!Comparing.equal(pair.getSecond(), moduleLevel)) { return "Modules " + pair.getFirst() + " and " + module.getName() + " must have the same language level because of cyclic dependencies between them"; } } final JpsJavaCompilerOptions compilerOptions = compilerConfig.getCurrentCompilerOptions(); final Map<String, String> overrideMap = compilerOptions.ADDITIONAL_OPTIONS_OVERRIDE; if (!overrideMap.isEmpty()) { // check that options are consistently overridden for all modules in the cycle Pair<String, Set<String>> overridden = null; for (JpsModule module : modules) { final String opts = overrideMap.get(module.getName()); if (!StringUtil.isEmptyOrSpaces(opts)) { final Set<String> parsed = parseOptions(opts); if (overridden == null) { overridden = pair(module.getName(), parsed); } else { if (!overridden.second.equals(parsed)) { return "Modules " + overridden.first + " and " + module.getName() + " must have the same 'additional command line parameters' specified because of cyclic dependencies between them"; } } } else { context.processMessage(new CompilerMessage( BUILDER_NAME, BuildMessage.Kind.WARNING, "Some modules with cyclic dependencies [" + chunk.getName() + "] have 'additional command line parameters' overridden in project settings.\nThese compilation options were applied to all modules in the cycle." )); } } } // check that all chunk modules are excluded from annotation processing for (JpsModule module : modules) { final ProcessorConfigProfile prof = compilerConfig.getAnnotationProcessingProfile(module); if (prof.isEnabled()) { return "Annotation processing is not supported for module cycles. Please ensure that all modules from cycle [" + chunk.getName() + "] are excluded from annotation processing"; } } return null; } private static Set<String> parseOptions(String str) { final Set<String> result = new SmartHashSet<>(); StringTokenizer t = new StringTokenizer(str, " \n\t", false); while (t.hasMoreTokens()) { result.add(t.nextToken()); } return result; } private static boolean shouldUseReleaseOption(JpsJavaCompilerConfiguration config, int compilerVersion, int chunkSdkVersion, int targetPlatformVersion) { if (!config.useReleaseOption()) { return false; } // --release option is supported in java9+ and higher if (compilerVersion >= 9 && chunkSdkVersion > 0 && targetPlatformVersion > 0) { if (chunkSdkVersion < 9) { // target sdk is set explicitly and differs from compiler SDK, so for consistency we should link against it return false; } // chunkSdkVersion >= 9, so we have no rt.jar anymore and '-release' is the only cross-compilation option available // Only specify '--release' when cross-compilation is indeed really required. // Otherwise '--release' may not be compatible with other compilation options, e.g. exporting a package from system module return compilerVersion != targetPlatformVersion; } return false; } private static boolean shouldForkCompilerProcess(CompileContext context, ModuleChunk chunk, int chunkLanguageLevel) { if (!isJavac(COMPILING_TOOL.get(context))) { return false; // applicable to javac only } final int compilerSdkVersion = JavaVersion.current().feature; if (preferTargetJdkCompiler(context)) { final Pair<JpsSdk<JpsDummyElement>, Integer> sdkVersionPair = getAssociatedSdk(chunk); if (sdkVersionPair != null) { final Integer chunkSdkVersion = sdkVersionPair.second; if (chunkSdkVersion != compilerSdkVersion && chunkSdkVersion >= 6 /*min. supported compiler version*/) { // there is a special case because of difference in type inference behavior between javac8 and javac6-javac7 // so if corresponding JDK is associated with the module chunk, prefer compiler from this JDK over the newer compiler version return true; } } } if (compilerSdkVersion < 9 || chunkLanguageLevel <= 0) { // javac up to version 9 supports all previous releases // was not able to determine jdk version, so assuming in-process compiler return false; } // compiler version is 9+ here, so: // - java 5 and older are not supported for sure // - applying '5 versions back' policy deduced from the current behavior of those JDKs return chunkLanguageLevel < 6 || Math.abs(compilerSdkVersion - chunkLanguageLevel) > 5; } private static boolean isJavac(final JavaCompilingTool compilingTool) { return compilingTool != null && (compilingTool.getId() == JavaCompilers.JAVAC_ID || compilingTool.getId() == JavaCompilers.JAVAC_API_ID); } private static boolean preferTargetJdkCompiler(CompileContext context) { Boolean val = PREFER_TARGET_JDK_COMPILER.get(context); if (val == null) { final JpsProject project = context.getProjectDescriptor().getProject(); final JpsJavaCompilerConfiguration config = JpsJavaExtensionService.getInstance().getCompilerConfiguration(project); // default val = config != null? config.getCompilerOptions(JavaCompilers.JAVAC_ID).PREFER_TARGET_JDK_COMPILER : Boolean.TRUE; PREFER_TARGET_JDK_COMPILER.set(context, val); } return val; } // If platformCp of the build process is the same as the target platform, do not specify platformCp explicitly // this will allow javac to resolve against ct.sym file, which is required for the "compilation profiles" feature @Nullable private static Collection<File> calcEffectivePlatformCp(Collection<File> platformCp, List<String> options, JavaCompilingTool compilingTool) { if (ourDefaultRtJar == null || !isJavac(compilingTool)) { return platformCp; } boolean profileFeatureRequested = false; for (String option : options) { if ("-profile".equalsIgnoreCase(option)) { profileFeatureRequested = true; break; } } if (!profileFeatureRequested) { return platformCp; } boolean isTargetPlatformSameAsBuildRuntime = false; for (File file : platformCp) { if (FileUtil.filesEqual(file, ourDefaultRtJar)) { isTargetPlatformSameAsBuildRuntime = true; break; } } if (!isTargetPlatformSameAsBuildRuntime) { // compact profile was requested, but we have to use alternative platform classpath to meet project settings // consider this a compile error and let user re-configure the project return null; } // returning empty list will force default behaviour for platform classpath calculation // javac will resolve against its own bootclasspath and use ct.sym file when available return Collections.emptyList(); } private void submitAsyncTask(final CompileContext context, final Runnable taskRunnable) { Semaphore counter = COUNTER_KEY.get(context); assert counter != null; counter.down(); myTaskRunner.execute(() -> { try { taskRunnable.run(); } catch (Throwable e) { context.processMessage(new CompilerMessage(BUILDER_NAME, e)); } finally { counter.up(); } }); } @NotNull private static synchronized ExternalJavacManager ensureJavacServerStarted(@NotNull CompileContext context) { ExternalJavacManager server = ExternalJavacManager.KEY.get(context); if (server != null) { return server; } final int listenPort = findFreePort(); server = new ExternalJavacManager(Utils.getSystemRoot()) { @Override protected ExternalJavacProcessHandler createProcessHandler(@NotNull Process process, @NotNull String commandLine) { return new ExternalJavacProcessHandler(process, commandLine) { @Override @NotNull protected Future<?> executeOnPooledThread(@NotNull Runnable task) { return SharedThreadPool.getInstance().executeOnPooledThread(task); } }; } }; server.start(listenPort); ExternalJavacManager.KEY.set(context, server); return server; } private static int findFreePort() { try { final ServerSocket serverSocket = new ServerSocket(0); try { return serverSocket.getLocalPort(); } finally { //workaround for linux : calling close() immediately after opening socket //may result that socket is not closed synchronized (serverSocket) { try { serverSocket.wait(1); } catch (Throwable ignored) { } } serverSocket.close(); } } catch (IOException e) { e.printStackTrace(System.err); return ExternalJavacManager.DEFAULT_SERVER_PORT; } } private static final Key<String> USER_DEFINED_BYTECODE_TARGET = Key.create("_user_defined_bytecode_target_"); private static Pair<List<String>, List<String>> getCompilationOptions(int compilerSdkVersion, CompileContext context, ModuleChunk chunk, @Nullable ProcessorConfigProfile profile, @NotNull JavaCompilingTool compilingTool) { final List<String> compilationOptions = new ArrayList<>(); final List<String> vmOptions = new ArrayList<>(); final JpsProject project = context.getProjectDescriptor().getProject(); final JpsJavaCompilerOptions compilerOptions = JpsJavaExtensionService.getInstance().getOrCreateCompilerConfiguration(project).getCurrentCompilerOptions(); if (compilerOptions.DEBUGGING_INFO) { compilationOptions.add("-g"); } if (compilerOptions.DEPRECATION) { compilationOptions.add("-deprecation"); } if (compilerOptions.GENERATE_NO_WARNINGS) { compilationOptions.add("-nowarn"); } if (compilerOptions instanceof EclipseCompilerOptions) { final EclipseCompilerOptions eclipseOptions = (EclipseCompilerOptions)compilerOptions; if (eclipseOptions.PROCEED_ON_ERROR) { Utils.PROCEED_ON_ERROR_KEY.set(context, Boolean.TRUE); compilationOptions.add("-proceedOnError"); } } String customArgs = compilerOptions.ADDITIONAL_OPTIONS_STRING; final Map<String, String> overrideMap = compilerOptions.ADDITIONAL_OPTIONS_OVERRIDE; if (!overrideMap.isEmpty()) { for (JpsModule m : chunk.getModules()) { final String overridden = overrideMap.get(m.getName()); if (overridden != null) { customArgs = overridden; break; } } } if (customArgs != null) { BiConsumer<List<String>, String> appender = List::add; final JpsModule module = chunk.representativeTarget().getModule(); final File baseDirectory = JpsModelSerializationDataService.getBaseDirectory(module); if (baseDirectory != null) { //this is a temporary workaround to allow passing per-module compiler options for Eclipse compiler in form // -properties $MODULE_DIR$/.settings/org.eclipse.jdt.core.prefs final String moduleDirPath = FileUtil.toCanonicalPath(baseDirectory.getAbsolutePath()); appender = (strings, option) -> strings.add(StringUtil.replace(option, PathMacroUtil.DEPRECATED_MODULE_DIR, moduleDirPath)); } boolean skip = false; boolean targetOptionFound = false; for (final String userOption : ParametersListUtil.parse(customArgs)) { if (FILTERED_OPTIONS.contains(userOption)) { skip = true; targetOptionFound = "-target".equals(userOption); continue; } if (skip) { skip = false; if (targetOptionFound) { targetOptionFound = false; USER_DEFINED_BYTECODE_TARGET.set(context, userOption); } } else { if (!FILTERED_SINGLE_OPTIONS.contains(userOption)) { if (userOption.startsWith("-J-")) { vmOptions.add(userOption.substring("-J".length())); } else { appender.accept(compilationOptions, userOption); } } } } } for (ExternalJavacOptionsProvider extension : JpsServiceManager.getInstance().getExtensions(ExternalJavacOptionsProvider.class)) { vmOptions.addAll(extension.getOptions(compilingTool)); } addCompilationOptions(compilerSdkVersion, compilationOptions, context, chunk, profile); return pair(vmOptions, compilationOptions); } public static void addCompilationOptions(List<String> options, CompileContext context, ModuleChunk chunk, @Nullable ProcessorConfigProfile profile) { addCompilationOptions(JavaVersion.current().feature, options, context, chunk, profile); } private static void addCompilationOptions(int compilerSdkVersion, List<String> options, CompileContext context, ModuleChunk chunk, @Nullable ProcessorConfigProfile profile) { if (!options.contains("-encoding")) { final CompilerEncodingConfiguration config = context.getProjectDescriptor().getEncodingConfiguration(); final String encoding = config.getPreferredModuleChunkEncoding(chunk); if (config.getAllModuleChunkEncodings(chunk).size() > 1) { final StringBuilder msgBuilder = new StringBuilder(); msgBuilder.append("Multiple encodings set for module chunk ").append(chunk.getName()); if (encoding != null) { msgBuilder.append("\n\"").append(encoding).append("\" will be used by compiler"); } context.processMessage(new CompilerMessage(BUILDER_NAME, BuildMessage.Kind.INFO, msgBuilder.toString())); } if (!StringUtil.isEmpty(encoding)) { options.add("-encoding"); options.add(encoding); } } addCrossCompilationOptions(compilerSdkVersion, options, context, chunk); if (!options.contains("--enable-preview")) { LanguageLevel level = JpsJavaExtensionService.getInstance().getLanguageLevel(chunk.representativeTarget().getModule()); if (level != null && level.isPreview()) { options.add("--enable-preview"); } } if (addAnnotationProcessingOptions(options, profile)) { final File srcOutput = ProjectPaths.getAnnotationProcessorGeneratedSourcesOutputDir( chunk.getModules().iterator().next(), chunk.containsTests(), profile ); if (srcOutput != null) { FileUtil.createDirectory(srcOutput); options.add("-s"); options.add(srcOutput.getPath()); } } } /** * @return true if annotation processing is enabled and corresponding options were added, false if profile is null or disabled */ public static boolean addAnnotationProcessingOptions(List<String> options, @Nullable AnnotationProcessingConfiguration profile) { if (profile == null || !profile.isEnabled()) { options.add("-proc:none"); return false; } // configuring annotation processing if (!profile.isObtainProcessorsFromClasspath()) { final String processorsPath = profile.getProcessorPath(); options.add("-processorpath"); options.add(FileUtil.toSystemDependentName(processorsPath.trim())); } final Set<String> processors = profile.getProcessors(); if (!processors.isEmpty()) { options.add("-processor"); options.add(StringUtil.join(processors, ",")); } for (Map.Entry<String, String> optionEntry : profile.getProcessorOptions().entrySet()) { options.add("-A" + optionEntry.getKey() + "=" + optionEntry.getValue()); } return true; } @NotNull public static String getUsedCompilerId(CompileContext context) { final JpsProject project = context.getProjectDescriptor().getProject(); final JpsJavaCompilerConfiguration config = JpsJavaExtensionService.getInstance().getCompilerConfiguration(project); return config == null ? JavaCompilers.JAVAC_ID : config.getJavaCompilerId(); } private static void addCrossCompilationOptions(int compilerSdkVersion, List<String> options, CompileContext context, ModuleChunk chunk) { final JpsJavaCompilerConfiguration compilerConfiguration = JpsJavaExtensionService.getInstance().getOrCreateCompilerConfiguration( context.getProjectDescriptor().getProject() ); final int languageLevel = getLanguageLevel(chunk.representativeTarget().getModule()); final int chunkSdkVersion = getChunkSdkVersion(chunk); int bytecodeTarget = getModuleBytecodeTarget(context, chunk, compilerConfiguration, languageLevel); if (shouldUseReleaseOption(compilerConfiguration, compilerSdkVersion, chunkSdkVersion, bytecodeTarget)) { options.add("--release"); options.add(complianceOption(bytecodeTarget)); return; } // using older -source, -target and -bootclasspath options if (languageLevel > 0) { options.add("-source"); options.add(complianceOption(languageLevel)); } if (bytecodeTarget > 0) { if (chunkSdkVersion > 0 && compilerSdkVersion > chunkSdkVersion) { // if compiler is newer than module JDK if (compilerSdkVersion >= bytecodeTarget) { // if user-specified bytecode version can be determined and is supported by compiler if (bytecodeTarget > chunkSdkVersion) { // and user-specified bytecode target level is higher than the highest one supported by the target JDK, // force compiler to use highest-available bytecode target version that is supported by the chunk JDK. bytecodeTarget = chunkSdkVersion; } } // otherwise let compiler display compilation error about incorrectly set bytecode target version } } else { if (chunkSdkVersion > 0 && compilerSdkVersion > chunkSdkVersion) { // force lower bytecode target level to match the version of the chunk JDK bytecodeTarget = chunkSdkVersion; } } if (bytecodeTarget > 0) { options.add("-target"); options.add(complianceOption(bytecodeTarget)); } } public static int getModuleBytecodeTarget(CompileContext context, ModuleChunk chunk, JpsJavaCompilerConfiguration compilerConfiguration) { return getModuleBytecodeTarget(context, chunk, compilerConfiguration, getLanguageLevel(chunk.representativeTarget().getModule())); } private static int getModuleBytecodeTarget(CompileContext context, ModuleChunk chunk, JpsJavaCompilerConfiguration compilerConfiguration, int languageLevel) { int bytecodeTarget = 0; for (JpsModule module : chunk.getModules()) { // use the lower possible target among modules that form the chunk final int moduleTarget = JpsJavaSdkType.parseVersion(compilerConfiguration.getByteCodeTargetLevel(module.getName())); if (moduleTarget > 0 && (bytecodeTarget == 0 || moduleTarget < bytecodeTarget)) { bytecodeTarget = moduleTarget; } } if (bytecodeTarget == 0) { if (languageLevel > 0) { // according to IDEA rule: if not specified explicitly, set target to be the same as source language level bytecodeTarget = languageLevel; } else { // last resort and backward compatibility: // check if user explicitly defined bytecode target in additional compiler options String value = USER_DEFINED_BYTECODE_TARGET.get(context); if (value != null) { bytecodeTarget = JpsJavaSdkType.parseVersion(value); } } } return bytecodeTarget; } private static String complianceOption(int major) { return JpsJavaSdkType.complianceOption(JavaVersion.compose(major)); } private static int getLanguageLevel(@NotNull JpsModule module) { final LanguageLevel level = JpsJavaExtensionService.getInstance().getLanguageLevel(module); return level != null ? level.toJavaVersion().feature : 0; } /** * The assumed module's source code language version. * Returns the version number, corresponding to the language level, associated with the given module. * If no language level set (neither on module- nor on project-level), the version of JDK associated with the module is returned. * If no JDK is associated, returns 0. */ private static int getTargetPlatformLanguageVersion(@NotNull JpsModule module) { final int level = getLanguageLevel(module); if (level > 0) { return level; } // when compiling, if language level is not explicitly set, it is assumed to be equal to // the highest possible language level supported by target JDK final JpsSdk<JpsDummyElement> sdk = module.getSdk(JpsJavaSdkType.INSTANCE); if (sdk != null) { return JpsJavaSdkType.getJavaVersion(sdk); } return 0; } private static int getChunkSdkVersion(ModuleChunk chunk) { int chunkSdkVersion = -1; for (JpsModule module : chunk.getModules()) { final JpsSdk<JpsDummyElement> sdk = module.getSdk(JpsJavaSdkType.INSTANCE); if (sdk != null) { final int moduleSdkVersion = JpsJavaSdkType.getJavaVersion(sdk); if (moduleSdkVersion != 0 /*could determine the version*/ && (chunkSdkVersion < 0 || chunkSdkVersion > moduleSdkVersion)) { chunkSdkVersion = moduleSdkVersion; } } } return chunkSdkVersion; } @Nullable private static Pair<String, Integer> getForkedJavacSdk(ModuleChunk chunk, int targetLanguageLevel) { final Pair<JpsSdk<JpsDummyElement>, Integer> sdkVersionPair = getAssociatedSdk(chunk); if (sdkVersionPair != null) { final int sdkVersion = sdkVersionPair.second; if (sdkVersion >= 6 && (sdkVersion < 9 || Math.abs(sdkVersion - targetLanguageLevel) <= 3)) { // current javac compiler does support required language level return pair(sdkVersionPair.first.getHomePath(), sdkVersion); } } final String fallbackJdkHome = System.getProperty(GlobalOptions.FALLBACK_JDK_HOME, null); if (fallbackJdkHome == null) { LOG.info("Fallback JDK is not specified. (See " + GlobalOptions.FALLBACK_JDK_HOME + " option)"); return null; } final String fallbackJdkVersion = System.getProperty(GlobalOptions.FALLBACK_JDK_VERSION, null); if (fallbackJdkVersion == null) { LOG.info("Fallback JDK version is not specified. (See " + GlobalOptions.FALLBACK_JDK_VERSION + " option)"); return null; } final int fallbackVersion = JpsJavaSdkType.parseVersion(fallbackJdkVersion); if (fallbackVersion < 6) { LOG.info("Version string for fallback JDK is '" + fallbackJdkVersion + "' (recognized as version '" + fallbackVersion + "')." + " At least version 6 is required."); return null; } return pair(fallbackJdkHome, fallbackVersion); } @Nullable private static Pair<JpsSdk<JpsDummyElement>, Integer> getAssociatedSdk(ModuleChunk chunk) { // assuming all modules in the chunk have the same associated JDK; // this constraint should be validated on build start final JpsSdk<JpsDummyElement> sdk = chunk.representativeTarget().getModule().getSdk(JpsJavaSdkType.INSTANCE); return sdk != null ? pair(sdk, JpsJavaSdkType.getJavaVersion(sdk)) : null; } @Override public void chunkBuildFinished(CompileContext context, ModuleChunk chunk) { JavaBuilderUtil.cleanupChunkResources(context); } private static Map<File, Set<File>> buildOutputDirectoriesMap(CompileContext context, ModuleChunk chunk) { final Map<File, Set<File>> map = new THashMap<>(FileUtil.FILE_HASHING_STRATEGY); for (ModuleBuildTarget target : chunk.getTargets()) { final File outputDir = target.getOutputDir(); if (outputDir == null) { continue; } final Set<File> roots = new THashSet<>(FileUtil.FILE_HASHING_STRATEGY); for (JavaSourceRootDescriptor descriptor : context.getProjectDescriptor().getBuildRootIndex().getTargetRoots(target, context)) { roots.add(descriptor.root); } map.put(outputDir, roots); } return map; } private static class DiagnosticSink implements DiagnosticOutputConsumer { private final CompileContext myContext; private volatile int myErrorCount; private volatile int myWarningCount; private final Set<File> myFilesWithErrors = new THashSet<>(FileUtil.FILE_HASHING_STRATEGY); private DiagnosticSink(CompileContext context) { myContext = context; } @Override public void javaFileLoaded(File file) { } @Override public void registerImports(final String className, final Collection<String> imports, final Collection<String> staticImports) { //submitAsyncTask(myContext, new Runnable() { // public void run() { // final Callbacks.Backend callback = DELTA_MAPPINGS_CALLBACK_KEY.get(myContext); // if (callback != null) { // callback.registerImports(className, imports, staticImports); } @Override public void customOutputData(String pluginId, String dataName, byte[] data) { for (CustomOutputDataListener listener : JpsServiceManager.getInstance().getExtensions(CustomOutputDataListener.class)) { if (pluginId.equals(listener.getId())) { listener.processData(dataName, data); return; } } } @Override public void outputLineAvailable(String line) { if (!StringUtil.isEmpty(line)) { if (line.startsWith(ExternalJavacManager.STDOUT_LINE_PREFIX)) { //noinspection UseOfSystemOutOrSystemErr System.out.println(line); } else if (line.startsWith(ExternalJavacManager.STDERR_LINE_PREFIX)) { //noinspection UseOfSystemOutOrSystemErr System.err.println(line); } else if (line.contains("java.lang.OutOfMemoryError")) { myContext.processMessage(new CompilerMessage(BUILDER_NAME, BuildMessage.Kind.ERROR, "OutOfMemoryError: insufficient memory")); myErrorCount++; } else { final BuildMessage.Kind kind = getKindByMessageText(line); if (kind == BuildMessage.Kind.ERROR) { myErrorCount++; } else if (kind == BuildMessage.Kind.WARNING) { myWarningCount++; } myContext.processMessage(new CompilerMessage(BUILDER_NAME, kind, line)); } } } private static BuildMessage.Kind getKindByMessageText(String line) { final String lowercasedLine = line.toLowerCase(Locale.US); if (lowercasedLine.contains("error") || lowercasedLine.contains("requires target release")) { return BuildMessage.Kind.ERROR; } return BuildMessage.Kind.INFO; } @Override public void report(Diagnostic<? extends JavaFileObject> diagnostic) { final CompilerMessage.Kind kind; switch (diagnostic.getKind()) { case ERROR: kind = BuildMessage.Kind.ERROR; myErrorCount++; break; case MANDATORY_WARNING: case WARNING: kind = BuildMessage.Kind.WARNING; myWarningCount++; break; case NOTE: kind = BuildMessage.Kind.INFO; break; case OTHER: kind = diagnostic instanceof JpsInfoDiagnostic? BuildMessage.Kind.JPS_INFO : BuildMessage.Kind.OTHER; break; default: kind = BuildMessage.Kind.OTHER; } File sourceFile = null; try { // for eclipse compiler just an attempt to call getSource() may lead to an NPE, // so calling this method under try/catch to avoid induced compiler errors final JavaFileObject source = diagnostic.getSource(); sourceFile = source != null ? PathUtils.convertToFile(source.toUri()) : null; } catch (Exception e) { LOG.info(e); } final String srcPath; if (sourceFile != null) { if (kind == BuildMessage.Kind.ERROR) { myFilesWithErrors.add(sourceFile); } srcPath = FileUtil.toSystemIndependentName(sourceFile.getPath()); } else { srcPath = null; } String message = diagnostic.getMessage(Locale.US); if (Utils.IS_TEST_MODE) { LOG.info(message); } final CompilerMessage compilerMsg = new CompilerMessage( BUILDER_NAME, kind, message, srcPath, diagnostic.getStartPosition(), diagnostic.getEndPosition(), diagnostic.getPosition(), diagnostic.getLineNumber(), diagnostic.getColumnNumber() ); if (LOG.isDebugEnabled()) { LOG.debug(compilerMsg.toString()); } myContext.processMessage(compilerMsg); } int getErrorCount() { return myErrorCount; } int getWarningCount() { return myWarningCount; } @NotNull Collection<File> getFilesWithErrors() { return myFilesWithErrors; } } private class ClassProcessingConsumer implements OutputFileConsumer { private final CompileContext myContext; private final OutputFileConsumer myDelegateOutputFileSink; private ClassProcessingConsumer(CompileContext context, OutputFileConsumer sink) { myContext = context; myDelegateOutputFileSink = sink != null ? sink : fileObject -> { throw new RuntimeException("Output sink for compiler was not specified"); }; } @Override public void save(@NotNull final OutputFileObject fileObject) { // generated files must be saved synchronously, because some compilers (e.g. eclipse) // may want to read them for further compilation try { final BinaryContent content = fileObject.getContent(); final File file = fileObject.getFile(); if (content != null) { content.saveToFile(file); } else { myContext.processMessage(new CompilerMessage(BUILDER_NAME, BuildMessage.Kind.WARNING, "Missing content for file " + file.getPath())); } } catch (IOException e) { myContext.processMessage(new CompilerMessage(BUILDER_NAME, BuildMessage.Kind.ERROR, e.getMessage())); } submitAsyncTask(myContext, () -> { try { for (ClassPostProcessor processor : ourClassProcessors) { processor.process(myContext, fileObject); } } finally { myDelegateOutputFileSink.save(fileObject); } }); } } private static final Key<Semaphore> COUNTER_KEY = Key.create("_async_task_counter_"); }
package org.lilyproject.indexer.batchbuild.test; import java.io.File; import java.io.IOException; import java.io.InputStream; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.client.HBaseAdmin; import org.apache.hadoop.hbase.client.HConnectionManager; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.SolrQuery.ORDER; import org.apache.solr.client.solrj.response.QueryResponse; import org.apache.solr.common.SolrDocumentList; import org.junit.Assert; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.lilyproject.indexer.model.api.IndexBatchBuildState; import org.lilyproject.indexer.model.api.IndexDefinition; import org.lilyproject.indexer.model.api.IndexUpdateState; import org.lilyproject.indexer.model.api.WriteableIndexerModel; import org.lilyproject.lilyservertestfw.LilyProxy; import org.lilyproject.repository.api.FieldType; import org.lilyproject.repository.api.QName; import org.lilyproject.repository.api.Record; import org.lilyproject.repository.api.RecordType; import org.lilyproject.repository.api.Repository; import org.lilyproject.repository.api.Scope; import org.lilyproject.repository.api.TypeManager; import org.lilyproject.solrtestfw.SolrProxy; import org.lilyproject.util.json.JsonFormat; import org.lilyproject.util.test.TestHomeUtil; public class BatchBuildTest { private static LilyProxy lilyProxy; private static File tmpDir; private static int BUILD_TIMEOUT = 120000; private FieldType ft1; private RecordType rt1; private final static String INDEX_NAME = "batchtest"; private static final String COUNTER_NUM_FAILED_RECORDS = "org.lilyproject.indexer.batchbuild.IndexBatchBuildCounters:NUM_FAILED_RECORDS"; @BeforeClass public static void setUpBeforeClass() throws Exception { lilyProxy = new LilyProxy(); // Make multiple record table splits, so that our MR job will have multiple map tasks if (lilyProxy.getMode() == LilyProxy.Mode.CONNECT || lilyProxy.getMode() == LilyProxy.Mode.HADOOP_CONNECT) { // The record table will likely already exist and not be recreated, hence we won't be able to change // the number of regions. Therefore, drop the table. Configuration conf = HBaseConfiguration.create(); conf.set("hbase.zookeeper.quorum", "localhost"); HBaseAdmin hbaseAdmin = new HBaseAdmin(conf); if (hbaseAdmin.tableExists("record")) { hbaseAdmin.disableTable("record"); hbaseAdmin.deleteTable("record"); } HConnectionManager.deleteConnection(hbaseAdmin.getConfiguration(), true); } // Temp dir where we will create conf dir tmpDir = TestHomeUtil.createTestHome("lily-batchbuild-test-"); File customConfDir = setupConfDirectory(tmpDir); String oldCustomConfDir = setProperty("lily.conf.customdir", customConfDir.getAbsolutePath()); String oldRestoreTemplate = setProperty("lily.lilyproxy.restoretemplatedir", "false"); try { lilyProxy.start(); } finally { // Make sure the properties won't be used by later-running tests setProperty("lily.conf.customdir", oldCustomConfDir); setProperty("lily.lilyproxy.restoretemplatedir", oldRestoreTemplate); } // Set the solr schema InputStream is = BatchBuildTest.class.getResourceAsStream("solrschema.xml"); lilyProxy.getSolrProxy().changeSolrSchema(IOUtils.toByteArray(is)); IOUtils.closeQuietly(is); TypeManager typeManager = lilyProxy.getLilyServerProxy().getClient().getRepository().getTypeManager(); FieldType ft1 = typeManager.createFieldType("STRING", new QName("batchindex-test", "field1"), Scope.NON_VERSIONED); typeManager.recordTypeBuilder() .defaultNamespace("batchindex-test") .name("rt1") .fieldEntry().use(ft1).add() .create(); // Set the index lilyProxy.getLilyServerProxy().addIndexFromResource(INDEX_NAME, "org/lilyproject/indexer/batchbuild/test/indexerconf.xml", 500); WriteableIndexerModel model = lilyProxy.getLilyServerProxy().getIndexerModel(); String lock = model.lockIndex(INDEX_NAME); try { IndexDefinition index = model.getMutableIndex("batchtest"); index.setUpdateState(IndexUpdateState.DO_NOT_SUBSCRIBE); model.updateIndex(index, lock); } finally { model.unlockIndex(lock); } } private static String setProperty(String name, String value) { String oldValue = System.getProperty(name); if (value == null) { System.getProperties().remove(name); } else { System.setProperty(name, value); } return oldValue; } private static File setupConfDirectory(File tmpDir) throws Exception { File confDir = new File(tmpDir, "conf"); File generalConfDir = new File(confDir, "general"); FileUtils.forceMkdir(generalConfDir); // Write configuration to activate the decorator String tablesXml = "<tables xmlns:conf='http://kauriproject.org/configuration' conf:inherit='shallow'>" + "<table name='record'><splits><regionCount>5</regionCount>" + "<splitKeys>\\x00020,\\x00040,\\x00060,\\x00080</splitKeys></splits></table>" + "</tables>"; FileUtils.writeStringToFile(new File(generalConfDir, "tables.xml"), tablesXml, "UTF-8"); return confDir; } @Before public void setup() throws Exception { Repository repository = lilyProxy.getLilyServerProxy().getClient().getRepository(); TypeManager typeManager = repository.getTypeManager(); this.ft1 = typeManager.getFieldTypeByName(new QName("batchindex-test", "field1")); this.rt1 = typeManager.getRecordTypeByName(new QName("batchindex-test", "rt1"), null); } @Test public void testBatchIndex() throws Exception { Repository repository = lilyProxy.getLilyServerProxy().getClient().getRepository(); SolrProxy solrProxy = lilyProxy.getSolrProxy(); String assertId = "batch-index-test"; // First create some content repository.recordBuilder() .id("batch-index-test") .recordType(rt1.getName()) .field(ft1.getName(), "test1") .create(); this.buildAndCommit(); QueryResponse response = solrProxy.getSolrServer().query(new SolrQuery("field1:test1*")); Assert.assertEquals(1, response.getResults().size()); Assert.assertEquals("USER." + assertId, response.getResults().get(0).getFieldValue("lily.id")); } /** * Test if the default batch index conf setting works * * @throws Exception */ @Test public void testDefaultBatchIndexConf() throws Exception { Repository repository = lilyProxy.getLilyServerProxy().getClient().getRepository(); SolrProxy solrProxy = lilyProxy.getSolrProxy(); WriteableIndexerModel model = lilyProxy.getLilyServerProxy().getIndexerModel(); String lock = model.lockIndex(this.INDEX_NAME); byte[] defaultConf = null; try { IndexDefinition index = model.getMutableIndex(this.INDEX_NAME); defaultConf = getResourceAsByteArray("defaultBatchIndexConf-test2.json"); index.setDefaultBatchIndexConfiguration(defaultConf); model.updateIndex(index, lock); } finally { model.unlockIndex(lock); } String assertId = "batch-index-test2"; // First create some content repository.recordBuilder() .id(assertId) .recordType(rt1.getName()) .field(ft1.getName(), "test2 index") .create(); repository.recordBuilder() .id("batch-noindex-test2") .recordType(rt1.getName()) .field(ft1.getName(), "test2 noindex") .create(); // Now start the batch index this.buildAndCommit(); // Check if 1 record and not 2 are in the index QueryResponse response = solrProxy.getSolrServer().query(new SolrQuery("field1:test2*")); Assert.assertEquals(1, response.getResults().size()); Assert.assertEquals("USER." + "batch-index-test2", response.getResults().get(0).getFieldValue("lily.id")); // check that the last used batch index conf = default IndexDefinition index = model.getMutableIndex(this.INDEX_NAME); Assert.assertEquals(JsonFormat.deserialize(defaultConf), JsonFormat.deserialize(index.getLastBatchBuildInfo().getBatchIndexConfiguration())); } /** * Test setting a custom batch index conf. * * @throws Exception */ @Test public void testCustomBatchIndexConf() throws Exception { Repository repository = lilyProxy.getLilyServerProxy().getClient().getRepository(); SolrProxy solrProxy = lilyProxy.getSolrProxy(); WriteableIndexerModel model = lilyProxy.getLilyServerProxy().getIndexerModel(); String assertId1 = "batch-index-custom-test3"; String assertId2 = "batch-index-test3"; // First create some content Record recordToChange1 = repository.recordBuilder() .id(assertId2) .recordType(rt1.getName()) .field(ft1.getName(), "test3 index run1") .create(); Record recordToChange2 = repository.recordBuilder() .id(assertId1) .recordType(rt1.getName()) .field(ft1.getName(), "test3 index run1") .create(); repository.recordBuilder() .id("batch-noindex-test3") .recordType(rt1.getName()) .field(ft1.getName(), "test3 noindex run1") .create(); // Index everything with the default conf this.buildAndCommit(); SolrDocumentList results = solrProxy.getSolrServer().query(new SolrQuery("field1:test3*"). addSortField("lily.id", ORDER.asc)).getResults(); Assert.assertEquals(2, results.size()); Assert.assertEquals("USER." + assertId1, results.get(0).getFieldValue("lily.id")); Assert.assertEquals("USER." + assertId2, results.get(1).getFieldValue("lily.id")); // change some fields and reindex using a specific configuration. Only one of the 2 changes should be picked up recordToChange1.setField(ft1.getName(), "test3 index run2"); recordToChange2.setField(ft1.getName(), "test3 index run2"); repository.update(recordToChange1); repository.update(recordToChange2); byte[] batchConf = getResourceAsByteArray("batchIndexConf-test3.json"); ; byte[] defaultConf = getResourceAsByteArray("defaultBatchIndexConf-test2.json"); ; String lock = model.lockIndex(this.INDEX_NAME); try { IndexDefinition index = model.getMutableIndex(this.INDEX_NAME); index.setDefaultBatchIndexConfiguration(defaultConf); index.setBatchIndexConfiguration(batchConf); index.setBatchBuildState(IndexBatchBuildState.BUILD_REQUESTED); model.updateIndex(index, lock); } finally { model.unlockIndex(lock); } boolean indexSuccess = false; try { // Now wait until its finished long tryUntil = System.currentTimeMillis() + BUILD_TIMEOUT; while (System.currentTimeMillis() < tryUntil) { Thread.sleep(100); IndexDefinition definition = model.getIndex(INDEX_NAME); if (definition.getBatchBuildState() == IndexBatchBuildState.INACTIVE) { Long amountFailed = definition.getLastBatchBuildInfo().getCounters() .get(COUNTER_NUM_FAILED_RECORDS); boolean successFlag = definition.getLastBatchBuildInfo().getSuccess(); indexSuccess = successFlag && (amountFailed == null || amountFailed == 0L); } else if (definition.getBatchBuildState() == IndexBatchBuildState.BUILDING) { Assert.assertEquals(JsonFormat.deserialize(batchConf), JsonFormat.deserialize(definition.getActiveBatchBuildInfo().getBatchIndexConfiguration())); } } } catch (Exception e) { throw new Exception("Error checking if batch index job ended.", e); } if (!indexSuccess) { Assert.fail("Batch build did not end after " + BUILD_TIMEOUT + " millis"); } else { lilyProxy.getSolrProxy().getSolrServer().commit(); } // Check if 1 record and not 2 are in the index QueryResponse response = solrProxy.getSolrServer().query(new SolrQuery("field1:test3\\ index\\ run2")); Assert.assertEquals(1, response.getResults().size()); Assert.assertEquals("USER." + assertId1, response.getResults().get(0).getFieldValue("lily.id")); // check that the last used batch index conf = default Assert.assertEquals(JsonFormat.deserialize(batchConf), JsonFormat.deserialize( model.getMutableIndex(this.INDEX_NAME).getLastBatchBuildInfo().getBatchIndexConfiguration())); // Set things up for run 3 where the default configuration should be used again recordToChange1.setField(ft1.getName(), "test3 index run3"); recordToChange2.setField(ft1.getName(), "test3 index run3"); repository.update(recordToChange1); repository.update(recordToChange2); // Now rebuild the index and see if the default indexer has kicked in this.buildAndCommit(); response = solrProxy.getSolrServer().query(new SolrQuery("field1:test3\\ index\\ run3"). addSortField("lily.id", ORDER.asc)); Assert.assertEquals(2, response.getResults().size()); Assert.assertEquals("USER." + assertId1, response.getResults().get(0).getFieldValue("lily.id")); Assert.assertEquals("USER." + assertId2, response.getResults().get(1).getFieldValue("lily.id")); // check that the last used batch index conf = default Assert.assertEquals(JsonFormat.deserialize(defaultConf), JsonFormat.deserialize( model.getMutableIndex(this.INDEX_NAME).getLastBatchBuildInfo().getBatchIndexConfiguration())); } /** * This test should cause a failure when adding a custom batchindex conf without setting a buildrequest * * @throws Exception */ @Test(expected = org.lilyproject.indexer.model.api.IndexValidityException.class) public void testCustomBatchIndexConf_NoBuild() throws Exception { WriteableIndexerModel model = lilyProxy.getLilyServerProxy().getIndexerModel(); String lock = model.lockIndex(this.INDEX_NAME); try { IndexDefinition index = model.getMutableIndex(this.INDEX_NAME); index.setDefaultBatchIndexConfiguration(getResourceAsByteArray("defaultBatchIndexConf-test2.json")); index.setBatchIndexConfiguration(getResourceAsByteArray("batchIndexConf-test3.json")); model.updateIndex(index, lock); } finally { model.unlockIndex(lock); } } private byte[] getResourceAsByteArray(String name) throws IOException { InputStream is = null; try { is = BatchBuildTest.class.getResourceAsStream(name); return IOUtils.toByteArray(is); } finally { IOUtils.closeQuietly(is); } } private void buildAndCommit() throws Exception { boolean success = lilyProxy.getLilyServerProxy().batchBuildIndex(this.INDEX_NAME, BUILD_TIMEOUT); if (success) { lilyProxy.getSolrProxy().getSolrServer().commit(); } else { Assert.fail("Batch build did not end after " + BUILD_TIMEOUT + " millis"); } } }
package com.fsck.k9.mailstore.migrations; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import android.content.ContentValues; import android.database.sqlite.SQLiteDatabase; import android.text.TextUtils; import android.util.Log; import com.fsck.k9.K9; import com.fsck.k9.mail.FetchProfile; import com.fsck.k9.mail.MessagingException; import com.fsck.k9.mailstore.LocalFolder; import com.fsck.k9.mailstore.LocalMessage; import com.fsck.k9.mailstore.LocalStore; import com.fsck.k9.message.extractors.MessageFulltextCreator; public class MigrationTo55 { public static void createFtsSearchTable(SQLiteDatabase db, MigrationsHelper migrationsHelper) { db.execSQL("CREATE VIRTUAL TABLE messages_fulltext USING fts4 (fulltext)"); LocalStore localStore = migrationsHelper.getLocalStore(); MessageFulltextCreator fulltextCreator = localStore.getMessageFulltextCreator(); try { List<LocalFolder> folders = localStore.getPersonalNamespaces(true); ContentValues cv = new ContentValues(); FetchProfile fp = new FetchProfile(); fp.add(FetchProfile.Item.BODY); for (LocalFolder folder : folders) { Iterator<LocalMessage> localMessages = new ArrayList<>(folder.getMessages(null, false)).iterator(); while (localMessages.hasNext()) { LocalMessage localMessage = localMessages.next(); // The LocalMessage objects are heavy once they have been loaded, so we free them asap localMessages.remove(); folder.fetch(Collections.singletonList(localMessage), fp, null); String fulltext = fulltextCreator.createFulltext(localMessage); if (!TextUtils.isEmpty(fulltext)) { Log.d(K9.LOG_TAG, "fulltext for msg id " + localMessage.getId() + " is " + fulltext.length() + " chars long"); cv.clear(); cv.put("docid", localMessage.getId()); cv.put("fulltext", fulltext); db.insert("messages_fulltext", null, cv); } else { Log.d(K9.LOG_TAG, "no fulltext for msg id " + localMessage.getId() + " :("); } } } } catch (MessagingException e) { Log.e(K9.LOG_TAG, "error indexing fulltext - skipping rest, fts index is incomplete!", e); } } }
package io.debezium.connector.sqlserver; import static org.fest.assertions.Assertions.assertThat; import static org.junit.Assert.assertNull; import java.sql.SQLException; import java.time.Instant; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.TimeZone; import java.util.UUID; import java.util.concurrent.TimeUnit; import org.apache.kafka.connect.data.Schema; import org.apache.kafka.connect.data.SchemaBuilder; import org.apache.kafka.connect.data.Struct; import org.apache.kafka.connect.source.SourceRecord; import org.awaitility.Awaitility; import org.awaitility.Duration; import org.fest.assertions.Assertions; import org.junit.After; import org.junit.Before; import org.junit.Test; import io.debezium.config.Configuration; import io.debezium.connector.sqlserver.SqlServerConnectorConfig.SnapshotMode; import io.debezium.connector.sqlserver.util.TestHelper; import io.debezium.data.Envelope; import io.debezium.data.SchemaAndValueField; import io.debezium.data.SourceRecordAssert; import io.debezium.doc.FixFor; import io.debezium.embedded.AbstractConnectorTest; import io.debezium.junit.logging.LogInterceptor; import io.debezium.util.Testing; /** * Integration test for the Debezium SQL Server connector. * * @author Jiri Pechanec */ public class SqlServerConnectorIT extends AbstractConnectorTest { private SqlServerConnection connection; @Before public void before() throws SQLException { TestHelper.createTestDatabase(); connection = TestHelper.testConnection(); connection.execute( "CREATE TABLE tablea (id int primary key, cola varchar(30))", "CREATE TABLE tableb (id int primary key, colb varchar(30))", "INSERT INTO tablea VALUES(1, 'a')"); TestHelper.enableTableCdc(connection, "tablea"); TestHelper.enableTableCdc(connection, "tableb"); initializeConnectorTestFramework(); Testing.Files.delete(TestHelper.DB_HISTORY_PATH); // Testing.Print.enable(); } @After public void after() throws SQLException { if (connection != null) { connection.close(); } } @Test public void createAndDelete() throws Exception { final int RECORDS_PER_TABLE = 5; final int TABLES = 2; final int ID_START = 10; final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .build(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); // Wait for snapshot completion consumeRecordsByTopic(1); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = ID_START + i; connection.execute( "INSERT INTO tablea VALUES(" + id + ", 'a')"); connection.execute( "INSERT INTO tableb VALUES(" + id + ", 'b')"); } final SourceRecords records = consumeRecordsByTopic(RECORDS_PER_TABLE * TABLES); final List<SourceRecord> tableA = records.recordsForTopic("server1.dbo.tablea"); final List<SourceRecord> tableB = records.recordsForTopic("server1.dbo.tableb"); Assertions.assertThat(tableA).hasSize(RECORDS_PER_TABLE); Assertions.assertThat(tableB).hasSize(RECORDS_PER_TABLE); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final SourceRecord recordA = tableA.get(i); final SourceRecord recordB = tableB.get(i); final List<SchemaAndValueField> expectedRowA = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, i + ID_START), new SchemaAndValueField("cola", Schema.OPTIONAL_STRING_SCHEMA, "a")); final List<SchemaAndValueField> expectedRowB = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, i + ID_START), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "b")); final Struct keyA = (Struct) recordA.key(); final Struct valueA = (Struct) recordA.value(); assertRecord((Struct) valueA.get("after"), expectedRowA); assertNull(valueA.get("before")); final Struct keyB = (Struct) recordB.key(); final Struct valueB = (Struct) recordB.value(); assertRecord((Struct) valueB.get("after"), expectedRowB); assertNull(valueB.get("before")); } connection.execute("DELETE FROM tableB"); final SourceRecords deleteRecords = consumeRecordsByTopic(2 * RECORDS_PER_TABLE); final List<SourceRecord> deleteTableA = deleteRecords.recordsForTopic("server1.dbo.tablea"); final List<SourceRecord> deleteTableB = deleteRecords.recordsForTopic("server1.dbo.tableb"); Assertions.assertThat(deleteTableA).isNullOrEmpty(); Assertions.assertThat(deleteTableB).hasSize(2 * RECORDS_PER_TABLE); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final SourceRecord deleteRecord = deleteTableB.get(i * 2); final SourceRecord tombstoneRecord = deleteTableB.get(i * 2 + 1); final List<SchemaAndValueField> expectedDeleteRow = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, i + ID_START), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "b")); final Struct deleteKey = (Struct) deleteRecord.key(); final Struct deleteValue = (Struct) deleteRecord.value(); assertRecord((Struct) deleteValue.get("before"), expectedDeleteRow); assertNull(deleteValue.get("after")); final Struct tombstoneKey = (Struct) tombstoneRecord.key(); final Struct tombstoneValue = (Struct) tombstoneRecord.value(); assertNull(tombstoneValue); } stopConnector(); } @Test @FixFor("DBZ-1642") public void readOnlyApplicationIntent() throws Exception { final LogInterceptor logInterceptor = new LogInterceptor(); final String appId = "readOnlyApplicationIntent-" + UUID.randomUUID(); final int RECORDS_PER_TABLE = 5; final int TABLES = 2; final int ID_START = 10; final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .with("database.applicationIntent", "ReadOnly") .with("database.applicationName", appId) .build(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); // Wait for snapshot completion consumeRecordsByTopic(1); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = ID_START + i; connection.execute( "INSERT INTO tablea VALUES(" + id + ", 'a')"); connection.execute( "INSERT INTO tableb VALUES(" + id + ", 'b')"); } final SourceRecords records = consumeRecordsByTopic(RECORDS_PER_TABLE * TABLES); final List<SourceRecord> tableA = records.recordsForTopic("server1.dbo.tablea"); final List<SourceRecord> tableB = records.recordsForTopic("server1.dbo.tableb"); Assertions.assertThat(tableA).hasSize(RECORDS_PER_TABLE); Assertions.assertThat(tableB).hasSize(RECORDS_PER_TABLE); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final SourceRecord recordA = tableA.get(i); final SourceRecord recordB = tableB.get(i); final List<SchemaAndValueField> expectedRowA = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, i + ID_START), new SchemaAndValueField("cola", Schema.OPTIONAL_STRING_SCHEMA, "a")); final List<SchemaAndValueField> expectedRowB = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, i + ID_START), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "b")); final Struct keyA = (Struct) recordA.key(); final Struct valueA = (Struct) recordA.value(); assertRecord((Struct) valueA.get("after"), expectedRowA); assertNull(valueA.get("before")); final Struct keyB = (Struct) recordB.key(); final Struct valueB = (Struct) recordB.value(); assertRecord((Struct) valueB.get("after"), expectedRowB); assertNull(valueB.get("before")); } assertThat(logInterceptor.containsMessage("Schema locking was disabled in connector configuration")).isTrue(); // Verify that multiple subsequent transactions are used in streaming phase with read-only intent try (final SqlServerConnection admin = TestHelper.adminConnection()) { final Set<Long> txIds = new HashSet<>(); Awaitility.await().atMost(Duration.FIVE_SECONDS).pollInterval(Duration.ONE_HUNDRED_MILLISECONDS).until(() -> { admin.query( "SELECT (SELECT transaction_id FROM sys.dm_tran_session_transactions AS t WHERE s.session_id=t.session_id) FROM sys.dm_exec_sessions AS s WHERE program_name='" + appId + "'", rs -> { rs.next(); txIds.add(rs.getLong(1)); }); return txIds.size() > 2; }); } stopConnector(); } @Test @FixFor("DBZ-1643") public void timestampAndTimezone() throws Exception { final int RECORDS_PER_TABLE = 5; final int TABLES = 2; final int ID_START = 10; final TimeZone currentTimeZone = TimeZone.getDefault(); try { TimeZone.setDefault(TimeZone.getTimeZone("Atlantic/Cape_Verde")); final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .build(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); // Wait for snapshot completion consumeRecordsByTopic(1); final Instant now = Instant.now(); final Instant lowerBound = now.minusSeconds(5 * 60); final Instant upperBound = now.plusSeconds(5 * 60); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = ID_START + i; connection.execute( "INSERT INTO tablea VALUES(" + id + ", 'a')"); connection.execute( "INSERT INTO tableb VALUES(" + id + ", 'b')"); } final SourceRecords records = consumeRecordsByTopic(RECORDS_PER_TABLE * TABLES); final List<SourceRecord> tableA = records.recordsForTopic("server1.dbo.tablea"); final List<SourceRecord> tableB = records.recordsForTopic("server1.dbo.tableb"); Assertions.assertThat(tableA).hasSize(RECORDS_PER_TABLE); Assertions.assertThat(tableB).hasSize(RECORDS_PER_TABLE); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final SourceRecord recordA = tableA.get(i); final long timestamp = ((Struct) recordA.value()).getStruct("source").getInt64("ts_ms"); final Instant instant = Instant.ofEpochMilli(timestamp); Assertions.assertThat(instant.isAfter(lowerBound) && instant.isBefore(upperBound)).isTrue(); } stopConnector(); } finally { TimeZone.setDefault(currentTimeZone); } } @Test public void deleteWithoutTombstone() throws Exception { final int RECORDS_PER_TABLE = 5; final int TABLES = 2; final int ID_START = 10; final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .with(SqlServerConnectorConfig.TOMBSTONES_ON_DELETE, false) .build(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); // Wait for snapshot completion consumeRecordsByTopic(1); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = ID_START + i; connection.execute( "INSERT INTO tablea VALUES(" + id + ", 'a')"); connection.execute( "INSERT INTO tableb VALUES(" + id + ", 'b')"); } final SourceRecords records = consumeRecordsByTopic(RECORDS_PER_TABLE * TABLES); connection.execute("DELETE FROM tableB"); final SourceRecords deleteRecords = consumeRecordsByTopic(RECORDS_PER_TABLE); final List<SourceRecord> deleteTableA = deleteRecords.recordsForTopic("server1.dbo.tablea"); final List<SourceRecord> deleteTableB = deleteRecords.recordsForTopic("server1.dbo.tableb"); Assertions.assertThat(deleteTableA).isNullOrEmpty(); Assertions.assertThat(deleteTableB).hasSize(RECORDS_PER_TABLE); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final SourceRecord deleteRecord = deleteTableB.get(i); final List<SchemaAndValueField> expectedDeleteRow = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, i + ID_START), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "b")); final Struct deleteKey = (Struct) deleteRecord.key(); final Struct deleteValue = (Struct) deleteRecord.value(); assertRecord((Struct) deleteValue.get("before"), expectedDeleteRow); assertNull(deleteValue.get("after")); } stopConnector(); } @Test public void update() throws Exception { final int RECORDS_PER_TABLE = 5; final int ID_START = 10; final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .build(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); // Testing.Print.enable(); // Wait for snapshot completion consumeRecordsByTopic(1); connection.setAutoCommit(false); final String[] tableBInserts = new String[RECORDS_PER_TABLE]; for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = ID_START + i; tableBInserts[i] = "INSERT INTO tableb VALUES(" + id + ", 'b')"; } connection.execute(tableBInserts); connection.setAutoCommit(true); connection.execute("UPDATE tableb SET colb='z'"); final SourceRecords records = consumeRecordsByTopic(RECORDS_PER_TABLE * 2); final List<SourceRecord> tableB = records.recordsForTopic("server1.dbo.tableb"); Assertions.assertThat(tableB).hasSize(RECORDS_PER_TABLE * 2); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final SourceRecord recordB = tableB.get(i); final List<SchemaAndValueField> expectedRowB = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, i + ID_START), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "b")); final Struct keyB = (Struct) recordB.key(); final Struct valueB = (Struct) recordB.value(); assertRecord((Struct) valueB.get("after"), expectedRowB); assertNull(valueB.get("before")); } for (int i = 0; i < RECORDS_PER_TABLE; i++) { final SourceRecord recordB = tableB.get(i + RECORDS_PER_TABLE); final List<SchemaAndValueField> expectedBefore = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, i + ID_START), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "b")); final List<SchemaAndValueField> expectedAfter = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, i + ID_START), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "z")); final Struct keyB = (Struct) recordB.key(); final Struct valueB = (Struct) recordB.value(); assertRecord((Struct) valueB.get("before"), expectedBefore); assertRecord((Struct) valueB.get("after"), expectedAfter); } stopConnector(); } @Test public void updatePrimaryKey() throws Exception { final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .build(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); // Testing.Print.enable(); // Wait for snapshot completion consumeRecordsByTopic(1); connection.execute("INSERT INTO tableb VALUES(1, 'b')"); consumeRecordsByTopic(1); connection.setAutoCommit(false); connection.execute( "UPDATE tablea SET id=100 WHERE id=1", "UPDATE tableb SET id=100 WHERE id=1"); final SourceRecords records = consumeRecordsByTopic(6); final List<SourceRecord> tableA = records.recordsForTopic("server1.dbo.tablea"); final List<SourceRecord> tableB = records.recordsForTopic("server1.dbo.tableb"); Assertions.assertThat(tableA).hasSize(3); Assertions.assertThat(tableB).hasSize(3); final List<SchemaAndValueField> expectedDeleteRowA = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, 1), new SchemaAndValueField("cola", Schema.OPTIONAL_STRING_SCHEMA, "a")); final List<SchemaAndValueField> expectedDeleteKeyA = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, 1)); final List<SchemaAndValueField> expectedInsertRowA = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, 100), new SchemaAndValueField("cola", Schema.OPTIONAL_STRING_SCHEMA, "a")); final List<SchemaAndValueField> expectedInsertKeyA = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, 100)); final SourceRecord deleteRecordA = tableA.get(0); final SourceRecord tombstoneRecordA = tableA.get(1); final SourceRecord insertRecordA = tableA.get(2); final Struct deleteKeyA = (Struct) deleteRecordA.key(); final Struct deleteValueA = (Struct) deleteRecordA.value(); assertRecord(deleteValueA.getStruct("before"), expectedDeleteRowA); assertRecord(deleteKeyA, expectedDeleteKeyA); assertNull(deleteValueA.get("after")); final Struct tombstoneKeyA = (Struct) tombstoneRecordA.key(); final Struct tombstoneValueA = (Struct) tombstoneRecordA.value(); assertRecord(tombstoneKeyA, expectedDeleteKeyA); assertNull(tombstoneValueA); final Struct insertKeyA = (Struct) insertRecordA.key(); final Struct insertValueA = (Struct) insertRecordA.value(); assertRecord(insertValueA.getStruct("after"), expectedInsertRowA); assertRecord(insertKeyA, expectedInsertKeyA); assertNull(insertValueA.get("before")); final List<SchemaAndValueField> expectedDeleteRowB = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, 1), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "b")); final List<SchemaAndValueField> expectedDeleteKeyB = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, 1)); final List<SchemaAndValueField> expectedInsertRowB = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, 100), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "b")); final List<SchemaAndValueField> expectedInsertKeyB = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, 100)); final SourceRecord deleteRecordB = tableB.get(0); final SourceRecord tombstoneRecordB = tableB.get(1); final SourceRecord insertRecordB = tableB.get(2); final Struct deletekeyB = (Struct) deleteRecordB.key(); final Struct deleteValueB = (Struct) deleteRecordB.value(); assertRecord(deleteValueB.getStruct("before"), expectedDeleteRowB); assertRecord(deletekeyB, expectedDeleteKeyB); assertNull(deleteValueB.get("after")); assertThat(deleteValueB.getStruct("source").getInt64("event_serial_no")).isEqualTo(1L); final Struct tombstonekeyB = (Struct) tombstoneRecordB.key(); final Struct tombstoneValueB = (Struct) tombstoneRecordB.value(); assertRecord(tombstonekeyB, expectedDeleteKeyB); assertNull(tombstoneValueB); final Struct insertkeyB = (Struct) insertRecordB.key(); final Struct insertValueB = (Struct) insertRecordB.value(); assertRecord(insertValueB.getStruct("after"), expectedInsertRowB); assertRecord(insertkeyB, expectedInsertKeyB); assertNull(insertValueB.get("before")); assertThat(insertValueB.getStruct("source").getInt64("event_serial_no")).isEqualTo(2L); stopConnector(); } @Test @FixFor("DBZ-1152") public void updatePrimaryKeyWithRestartInMiddle() throws Exception { final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .build(); start(SqlServerConnector.class, config, record -> { final Struct envelope = (Struct) record.value(); return envelope != null && "c".equals(envelope.get("op")) && (envelope.getStruct("after").getInt32("id") == 100); }); assertConnectorIsRunning(); // Testing.Print.enable(); // Wait for snapshot completion consumeRecordsByTopic(1); connection.execute("INSERT INTO tableb VALUES(1, 'b')"); consumeRecordsByTopic(1); connection.setAutoCommit(false); connection.execute( "UPDATE tablea SET id=100 WHERE id=1", "UPDATE tableb SET id=100 WHERE id=1"); final SourceRecords records1 = consumeRecordsByTopic(2); stopConnector(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); final SourceRecords records2 = consumeRecordsByTopic(4); final List<SourceRecord> tableA = records1.recordsForTopic("server1.dbo.tablea"); tableA.addAll(records2.recordsForTopic("server1.dbo.tablea")); final List<SourceRecord> tableB = records2.recordsForTopic("server1.dbo.tableb"); Assertions.assertThat(tableA).hasSize(3); Assertions.assertThat(tableB).hasSize(3); final List<SchemaAndValueField> expectedDeleteRowA = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, 1), new SchemaAndValueField("cola", Schema.OPTIONAL_STRING_SCHEMA, "a")); final List<SchemaAndValueField> expectedDeleteKeyA = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, 1)); final List<SchemaAndValueField> expectedInsertRowA = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, 100), new SchemaAndValueField("cola", Schema.OPTIONAL_STRING_SCHEMA, "a")); final List<SchemaAndValueField> expectedInsertKeyA = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, 100)); final SourceRecord deleteRecordA = tableA.get(0); final SourceRecord tombstoneRecordA = tableA.get(1); final SourceRecord insertRecordA = tableA.get(2); final Struct deleteKeyA = (Struct) deleteRecordA.key(); final Struct deleteValueA = (Struct) deleteRecordA.value(); assertRecord(deleteValueA.getStruct("before"), expectedDeleteRowA); assertRecord(deleteKeyA, expectedDeleteKeyA); assertNull(deleteValueA.get("after")); final Struct tombstoneKeyA = (Struct) tombstoneRecordA.key(); final Struct tombstoneValueA = (Struct) tombstoneRecordA.value(); assertRecord(tombstoneKeyA, expectedDeleteKeyA); assertNull(tombstoneValueA); final Struct insertKeyA = (Struct) insertRecordA.key(); final Struct insertValueA = (Struct) insertRecordA.value(); assertRecord(insertValueA.getStruct("after"), expectedInsertRowA); assertRecord(insertKeyA, expectedInsertKeyA); assertNull(insertValueA.get("before")); final List<SchemaAndValueField> expectedDeleteRowB = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, 1), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "b")); final List<SchemaAndValueField> expectedDeleteKeyB = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, 1)); final List<SchemaAndValueField> expectedInsertRowB = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, 100), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "b")); final List<SchemaAndValueField> expectedInsertKeyB = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, 100)); final SourceRecord deleteRecordB = tableB.get(0); final SourceRecord tombstoneRecordB = tableB.get(1); final SourceRecord insertRecordB = tableB.get(2); final Struct deletekeyB = (Struct) deleteRecordB.key(); final Struct deleteValueB = (Struct) deleteRecordB.value(); assertRecord(deleteValueB.getStruct("before"), expectedDeleteRowB); assertRecord(deletekeyB, expectedDeleteKeyB); assertNull(deleteValueB.get("after")); final Struct tombstonekeyB = (Struct) tombstoneRecordB.key(); final Struct tombstoneValueB = (Struct) tombstoneRecordB.value(); assertRecord(tombstonekeyB, expectedDeleteKeyB); assertNull(tombstoneValueB); final Struct insertkeyB = (Struct) insertRecordB.key(); final Struct insertValueB = (Struct) insertRecordB.value(); assertRecord(insertValueB.getStruct("after"), expectedInsertRowB); assertRecord(insertkeyB, expectedInsertKeyB); assertNull(insertValueB.get("before")); stopConnector(); } @Test public void streamChangesWhileStopped() throws Exception { final int RECORDS_PER_TABLE = 5; final int TABLES = 2; final int ID_START = 10; final int ID_RESTART = 100; final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .build(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); // Wait for snapshot completion consumeRecordsByTopic(1); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = ID_START + i; connection.execute( "INSERT INTO tablea VALUES(" + id + ", 'a')"); connection.execute( "INSERT INTO tableb VALUES(" + id + ", 'b')"); } consumeRecordsByTopic(RECORDS_PER_TABLE * TABLES); stopConnector(); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = ID_RESTART + i; connection.execute( "INSERT INTO tablea VALUES(" + id + ", 'a')"); connection.execute( "INSERT INTO tableb VALUES(" + id + ", 'b')"); } start(SqlServerConnector.class, config); assertConnectorIsRunning(); final SourceRecords records = consumeRecordsByTopic(RECORDS_PER_TABLE * TABLES); final List<SourceRecord> tableA = records.recordsForTopic("server1.dbo.tablea"); List<SourceRecord> tableB = records.recordsForTopic("server1.dbo.tableb"); Assertions.assertThat(tableA).hasSize(RECORDS_PER_TABLE); Assertions.assertThat(tableB).hasSize(RECORDS_PER_TABLE); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = i + ID_RESTART; final SourceRecord recordA = tableA.get(i); final SourceRecord recordB = tableB.get(i); final List<SchemaAndValueField> expectedRowA = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, id), new SchemaAndValueField("cola", Schema.OPTIONAL_STRING_SCHEMA, "a")); final List<SchemaAndValueField> expectedRowB = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, id), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "b")); final Struct valueA = (Struct) recordA.value(); assertRecord((Struct) valueA.get("after"), expectedRowA); assertNull(valueA.get("before")); final Struct valueB = (Struct) recordB.value(); assertRecord((Struct) valueB.get("after"), expectedRowB); assertNull(valueB.get("before")); } } @Test @FixFor("DBZ-1069") public void verifyOffsets() throws Exception { final int RECORDS_PER_TABLE = 5; final int TABLES = 2; final int ID_START = 10; final int ID_RESTART = 100; final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .build(); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = ID_START + i; connection.execute( "INSERT INTO tablea VALUES(" + id + ", 'a')"); connection.execute( "INSERT INTO tableb VALUES(" + id + ", 'b')"); } for (int i = 0; !connection.getMaxLsn().isAvailable(); i++) { if (i == 30) { org.junit.Assert.fail("Initial changes not written to CDC structures"); } Testing.debug("Waiting for initial changes to be propagated to CDC structures"); Thread.sleep(1000); } start(SqlServerConnector.class, config); assertConnectorIsRunning(); List<SourceRecord> records = consumeRecordsByTopic(1 + RECORDS_PER_TABLE * TABLES).allRecordsInOrder(); records = records.subList(1, records.size()); for (Iterator<SourceRecord> it = records.iterator(); it.hasNext();) { SourceRecord record = it.next(); assertThat(record.sourceOffset().get("snapshot")).as("Snapshot phase").isEqualTo(true); if (it.hasNext()) { assertThat(record.sourceOffset().get("snapshot_completed")).as("Snapshot in progress").isEqualTo(false); } else { assertThat(record.sourceOffset().get("snapshot_completed")).as("Snapshot completed").isEqualTo(true); } } stopConnector(); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = ID_RESTART + i; connection.execute( "INSERT INTO tablea VALUES(" + id + ", 'a')"); connection.execute( "INSERT INTO tableb VALUES(" + id + ", 'b')"); } start(SqlServerConnector.class, config); assertConnectorIsRunning(); final SourceRecords sourceRecords = consumeRecordsByTopic(RECORDS_PER_TABLE * TABLES); final List<SourceRecord> tableA = sourceRecords.recordsForTopic("server1.dbo.tablea"); final List<SourceRecord> tableB = sourceRecords.recordsForTopic("server1.dbo.tableb"); Assertions.assertThat(tableA).hasSize(RECORDS_PER_TABLE); Assertions.assertThat(tableB).hasSize(RECORDS_PER_TABLE); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = i + ID_RESTART; final SourceRecord recordA = tableA.get(i); final SourceRecord recordB = tableB.get(i); final List<SchemaAndValueField> expectedRowA = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, id), new SchemaAndValueField("cola", Schema.OPTIONAL_STRING_SCHEMA, "a")); final List<SchemaAndValueField> expectedRowB = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, id), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "b")); final Struct valueA = (Struct) recordA.value(); assertRecord((Struct) valueA.get("after"), expectedRowA); assertNull(valueA.get("before")); final Struct valueB = (Struct) recordB.value(); assertRecord((Struct) valueB.get("after"), expectedRowB); assertNull(valueB.get("before")); assertThat(recordA.sourceOffset().get("snapshot")).as("Streaming phase").isNull(); assertThat(recordA.sourceOffset().get("snapshot_completed")).as("Streaming phase").isNull(); assertThat(recordA.sourceOffset().get("change_lsn")).as("LSN present").isNotNull(); assertThat(recordB.sourceOffset().get("snapshot")).as("Streaming phase").isNull(); assertThat(recordB.sourceOffset().get("snapshot_completed")).as("Streaming phase").isNull(); assertThat(recordB.sourceOffset().get("change_lsn")).as("LSN present").isNotNull(); } } @Test public void whitelistTable() throws Exception { final int RECORDS_PER_TABLE = 5; final int TABLES = 1; final int ID_START = 10; final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.SCHEMA_ONLY) .with(SqlServerConnectorConfig.TABLE_WHITELIST, "dbo.tableb") .build(); connection.execute( "INSERT INTO tableb VALUES(1, 'b')"); start(SqlServerConnector.class, config); assertConnectorIsRunning(); // Wait for snapshot completion consumeRecordsByTopic(1); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = ID_START + i; connection.execute( "INSERT INTO tablea VALUES(" + id + ", 'a')"); connection.execute( "INSERT INTO tableb VALUES(" + id + ", 'b')"); } final SourceRecords records = consumeRecordsByTopic(RECORDS_PER_TABLE * TABLES); final List<SourceRecord> tableA = records.recordsForTopic("server1.dbo.tablea"); final List<SourceRecord> tableB = records.recordsForTopic("server1.dbo.tableb"); Assertions.assertThat(tableA == null || tableA.isEmpty()).isTrue(); Assertions.assertThat(tableB).hasSize(RECORDS_PER_TABLE); stopConnector(); } @Test public void blacklistTable() throws Exception { final int RECORDS_PER_TABLE = 5; final int TABLES = 1; final int ID_START = 10; final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .with(SqlServerConnectorConfig.TABLE_BLACKLIST, "dbo.tablea") .build(); connection.execute( "INSERT INTO tableb VALUES(1, 'b')"); start(SqlServerConnector.class, config); assertConnectorIsRunning(); // Wait for snapshot completion consumeRecordsByTopic(1); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = ID_START + i; connection.execute( "INSERT INTO tablea VALUES(" + id + ", 'a')"); connection.execute( "INSERT INTO tableb VALUES(" + id + ", 'b')"); } final SourceRecords records = consumeRecordsByTopic(RECORDS_PER_TABLE * TABLES); final List<SourceRecord> tableA = records.recordsForTopic("server1.dbo.tablea"); final List<SourceRecord> tableB = records.recordsForTopic("server1.dbo.tableb"); Assertions.assertThat(tableA == null || tableA.isEmpty()).isTrue(); Assertions.assertThat(tableB).hasSize(RECORDS_PER_TABLE); stopConnector(); } @Test @FixFor("DBZ-1617") public void blacklistColumnWhenCdcColumnsDoNotMatchWithOriginalSnapshot() throws Exception { connection.execute("CREATE TABLE table_a (id int, name varchar(30), amount integer primary key(id))"); TestHelper.enableTableCdc(connection, "table_a"); connection.execute("ALTER TABLE table_a ADD blacklisted_column varchar(30)"); final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.SCHEMA_ONLY) .with(SqlServerConnectorConfig.COLUMN_BLACKLIST, "dbo.table_a.blacklisted_column") .build(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); // Wait for snapshot completion consumeRecordsByTopic(1); connection.execute("INSERT INTO table_a VALUES(10, 'some_name', 120, 'some_string')"); final SourceRecords records = consumeRecordsByTopic(1); final List<SourceRecord> tableA = records.recordsForTopic("server1.dbo.table_a"); Schema expectedSchemaA = SchemaBuilder.struct() .optional() .name("server1.dbo.table_a.Value") .field("id", Schema.INT32_SCHEMA) .field("name", Schema.OPTIONAL_STRING_SCHEMA) .field("amount", Schema.OPTIONAL_INT32_SCHEMA) .build(); Struct expectedValueA = new Struct(expectedSchemaA) .put("id", 10) .put("name", "some_name") .put("amount", 120); Assertions.assertThat(tableA).hasSize(1); SourceRecordAssert.assertThat(tableA.get(0)) .valueAfterFieldIsEqualTo(expectedValueA) .valueAfterFieldSchemaIsEqualTo(expectedSchemaA); stopConnector(); } @Test @FixFor("DBZ-1067") public void blacklistColumn() throws Exception { connection.execute( "CREATE TABLE blacklist_column_table_a (id int, name varchar(30), amount integer primary key(id))", "CREATE TABLE blacklist_column_table_b (id int, name varchar(30), amount integer primary key(id))"); TestHelper.enableTableCdc(connection, "blacklist_column_table_a"); TestHelper.enableTableCdc(connection, "blacklist_column_table_b"); final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.SCHEMA_ONLY) .with(SqlServerConnectorConfig.COLUMN_BLACKLIST, "dbo.blacklist_column_table_a.amount") .build(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); // Wait for snapshot completion consumeRecordsByTopic(1); connection.execute("INSERT INTO blacklist_column_table_a VALUES(10, 'some_name', 120)"); connection.execute("INSERT INTO blacklist_column_table_b VALUES(11, 'some_name', 447)"); final SourceRecords records = consumeRecordsByTopic(2); final List<SourceRecord> tableA = records.recordsForTopic("server1.dbo.blacklist_column_table_a"); final List<SourceRecord> tableB = records.recordsForTopic("server1.dbo.blacklist_column_table_b"); Schema expectedSchemaA = SchemaBuilder.struct() .optional() .name("server1.dbo.blacklist_column_table_a.Value") .field("id", Schema.INT32_SCHEMA) .field("name", Schema.OPTIONAL_STRING_SCHEMA) .build(); Struct expectedValueA = new Struct(expectedSchemaA) .put("id", 10) .put("name", "some_name"); Schema expectedSchemaB = SchemaBuilder.struct() .optional() .name("server1.dbo.blacklist_column_table_b.Value") .field("id", Schema.INT32_SCHEMA) .field("name", Schema.OPTIONAL_STRING_SCHEMA) .field("amount", Schema.OPTIONAL_INT32_SCHEMA) .build(); Struct expectedValueB = new Struct(expectedSchemaB) .put("id", 11) .put("name", "some_name") .put("amount", 447); Assertions.assertThat(tableA).hasSize(1); SourceRecordAssert.assertThat(tableA.get(0)) .valueAfterFieldIsEqualTo(expectedValueA) .valueAfterFieldSchemaIsEqualTo(expectedSchemaA); Assertions.assertThat(tableB).hasSize(1); SourceRecordAssert.assertThat(tableB.get(0)) .valueAfterFieldIsEqualTo(expectedValueB) .valueAfterFieldSchemaIsEqualTo(expectedSchemaB); stopConnector(); } /** * Passing the "applicationName" property which can be asserted from the connected sessions". */ @Test @FixFor("DBZ-964") public void shouldPropagateDatabaseDriverProperties() throws Exception { final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.SCHEMA_ONLY) .with("database.applicationName", "Debezium App DBZ-964") .build(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); // consuming one record to make sure the connector establishes the DB connection which happens asynchronously // after the start() call connection.execute("INSERT INTO tablea VALUES(964, 'a')"); consumeRecordsByTopic(1); connection.query("select count(1) from sys.dm_exec_sessions where program_name = 'Debezium App DBZ-964'", rs -> { rs.next(); assertThat(rs.getInt(1)).isGreaterThanOrEqualTo(1); }); } private void restartInTheMiddleOfTx(boolean restartJustAfterSnapshot, boolean afterStreaming) throws Exception { final int RECORDS_PER_TABLE = 30; final int TABLES = 2; final int ID_START = 10; final int ID_RESTART = 1000; final int HALF_ID = ID_START + RECORDS_PER_TABLE / 2; final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .build(); if (restartJustAfterSnapshot) { start(SqlServerConnector.class, config); assertConnectorIsRunning(); // Wait for snapshot to be completed consumeRecordsByTopic(1); stopConnector(); connection.execute("INSERT INTO tablea VALUES(-1, '-a')"); } start(SqlServerConnector.class, config, record -> { if (!"server1.dbo.tablea.Envelope".equals(record.valueSchema().name())) { return false; } final Struct envelope = (Struct) record.value(); final Struct after = envelope.getStruct("after"); final Integer id = after.getInt32("id"); final String value = after.getString("cola"); return id != null && id == HALF_ID && "a".equals(value); }); assertConnectorIsRunning(); // Wait for snapshot to be completed or a first streaming message delivered consumeRecordsByTopic(1); if (afterStreaming) { connection.execute("INSERT INTO tablea VALUES(-2, '-a')"); final SourceRecords records = consumeRecordsByTopic(1); final List<SchemaAndValueField> expectedRow = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, -2), new SchemaAndValueField("cola", Schema.OPTIONAL_STRING_SCHEMA, "-a")); assertRecord(((Struct) records.allRecordsInOrder().get(0).value()).getStruct(Envelope.FieldName.AFTER), expectedRow); } connection.setAutoCommit(false); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = ID_START + i; connection.executeWithoutCommitting( "INSERT INTO tablea VALUES(" + id + ", 'a')"); connection.executeWithoutCommitting( "INSERT INTO tableb VALUES(" + id + ", 'b')"); } connection.connection().commit(); List<SourceRecord> records = consumeRecordsByTopic(RECORDS_PER_TABLE).allRecordsInOrder(); assertThat(records).hasSize(RECORDS_PER_TABLE); SourceRecord lastRecordForOffset = records.get(RECORDS_PER_TABLE - 1); Struct value = (Struct) lastRecordForOffset.value(); final List<SchemaAndValueField> expectedLastRow = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, HALF_ID - 1), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "b")); assertRecord((Struct) value.get("after"), expectedLastRow); stopConnector(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); SourceRecords sourceRecords = consumeRecordsByTopic(RECORDS_PER_TABLE); records = sourceRecords.allRecordsInOrder(); assertThat(records).hasSize(RECORDS_PER_TABLE); List<SourceRecord> tableA = sourceRecords.recordsForTopic("server1.dbo.tablea"); List<SourceRecord> tableB = sourceRecords.recordsForTopic("server1.dbo.tableb"); for (int i = 0; i < RECORDS_PER_TABLE / 2; i++) { final int id = HALF_ID + i; final SourceRecord recordA = tableA.get(i); final SourceRecord recordB = tableB.get(i); final List<SchemaAndValueField> expectedRowA = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, id), new SchemaAndValueField("cola", Schema.OPTIONAL_STRING_SCHEMA, "a")); final List<SchemaAndValueField> expectedRowB = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, id), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "b")); final Struct valueA = (Struct) recordA.value(); assertRecord((Struct) valueA.get("after"), expectedRowA); assertNull(valueA.get("before")); final Struct valueB = (Struct) recordB.value(); assertRecord((Struct) valueB.get("after"), expectedRowB); assertNull(valueB.get("before")); } for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = ID_RESTART + i; connection.executeWithoutCommitting( "INSERT INTO tablea VALUES(" + id + ", 'a')"); connection.executeWithoutCommitting( "INSERT INTO tableb VALUES(" + id + ", 'b')"); connection.connection().commit(); } sourceRecords = consumeRecordsByTopic(RECORDS_PER_TABLE * TABLES); tableA = sourceRecords.recordsForTopic("server1.dbo.tablea"); tableB = sourceRecords.recordsForTopic("server1.dbo.tableb"); Assertions.assertThat(tableA).hasSize(RECORDS_PER_TABLE); Assertions.assertThat(tableB).hasSize(RECORDS_PER_TABLE); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = i + ID_RESTART; final SourceRecord recordA = tableA.get(i); final SourceRecord recordB = tableB.get(i); final List<SchemaAndValueField> expectedRowA = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, id), new SchemaAndValueField("cola", Schema.OPTIONAL_STRING_SCHEMA, "a")); final List<SchemaAndValueField> expectedRowB = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, id), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "b")); final Struct valueA = (Struct) recordA.value(); assertRecord((Struct) valueA.get("after"), expectedRowA); assertNull(valueA.get("before")); final Struct valueB = (Struct) recordB.value(); assertRecord((Struct) valueB.get("after"), expectedRowB); assertNull(valueB.get("before")); } } @Test @FixFor("DBZ-1128") public void restartInTheMiddleOfTxAfterSnapshot() throws Exception { restartInTheMiddleOfTx(true, false); } @Test @FixFor("DBZ-1128") public void restartInTheMiddleOfTxAfterCompletedTx() throws Exception { restartInTheMiddleOfTx(false, true); } @Test @FixFor("DBZ-1128") public void restartInTheMiddleOfTx() throws Exception { restartInTheMiddleOfTx(false, false); } @Test @FixFor("DBZ-1242") public void testEmptySchemaWarningAfterApplyingFilters() throws Exception { // This captures all logged messages, allowing us to verify log message was written. final LogInterceptor logInterceptor = new LogInterceptor(); Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .with(SqlServerConnectorConfig.TABLE_WHITELIST, "my_products") .build(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); waitForAvailableRecords(100, TimeUnit.MILLISECONDS); stopConnector(value -> assertThat(logInterceptor.containsWarnMessage(NO_MONITORED_TABLES_WARNING)).isTrue()); } @Test @FixFor("DBZ-1242") public void testNoEmptySchemaWarningAfterApplyingFilters() throws Exception { // This captures all logged messages, allowing us to verify log message was written. final LogInterceptor logInterceptor = new LogInterceptor(); Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .build(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); waitForAvailableRecords(100, TimeUnit.MILLISECONDS); stopConnector(value -> assertThat(logInterceptor.containsWarnMessage(NO_MONITORED_TABLES_WARNING)).isFalse()); } @Test @FixFor("DBZ-916") public void keylessTable() throws Exception { connection.execute( "CREATE TABLE keyless (id int, name varchar(30))", "INSERT INTO keyless VALUES(1, 'k')"); TestHelper.enableTableCdc(connection, "keyless"); final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .with(SqlServerConnectorConfig.TABLE_WHITELIST, "dbo.keyless") .build(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); final List<SchemaAndValueField> key = Arrays.asList( new SchemaAndValueField("id", Schema.OPTIONAL_INT32_SCHEMA, 1), new SchemaAndValueField("name", Schema.OPTIONAL_STRING_SCHEMA, "k")); final List<SchemaAndValueField> key2 = Arrays.asList( new SchemaAndValueField("id", Schema.OPTIONAL_INT32_SCHEMA, 2), new SchemaAndValueField("name", Schema.OPTIONAL_STRING_SCHEMA, "k")); final List<SchemaAndValueField> key3 = Arrays.asList( new SchemaAndValueField("id", Schema.OPTIONAL_INT32_SCHEMA, 3), new SchemaAndValueField("name", Schema.OPTIONAL_STRING_SCHEMA, "k")); // Wait for snapshot completion SourceRecords records = consumeRecordsByTopic(1); assertThat(records.recordsForTopic("server1.dbo.keyless").get(0).key()).isNull(); assertThat(records.recordsForTopic("server1.dbo.keyless").get(0).keySchema()).isNull(); connection.execute( "INSERT INTO keyless VALUES(2, 'k')"); records = consumeRecordsByTopic(1); assertThat(records.recordsForTopic("server1.dbo.keyless").get(0).key()).isNull(); assertThat(records.recordsForTopic("server1.dbo.keyless").get(0).key()).isNull(); connection.execute( "UPDATE keyless SET id=3 WHERE ID=2"); records = consumeRecordsByTopic(3); final SourceRecord update1 = records.recordsForTopic("server1.dbo.keyless").get(0); assertThat(update1.key()).isNull(); assertThat(update1.keySchema()).isNull(); assertRecord(((Struct) update1.value()).getStruct(Envelope.FieldName.BEFORE), key2); assertRecord(((Struct) update1.value()).getStruct(Envelope.FieldName.AFTER), key3); connection.execute( "DELETE FROM keyless WHERE id=3"); records = consumeRecordsByTopic(2, false); assertThat(records.recordsForTopic("server1.dbo.keyless").get(0).key()).isNull(); assertThat(records.recordsForTopic("server1.dbo.keyless").get(0).keySchema()).isNull(); assertNull(records.recordsForTopic("server1.dbo.keyless").get(1).value()); stopConnector(); } @Test @FixFor("DBZ-1015") public void shouldRewriteIdentityKey() throws InterruptedException, SQLException { connection.execute( "CREATE TABLE keyless (id int, name varchar(30))", "INSERT INTO keyless VALUES(1, 'k')"); TestHelper.enableTableCdc(connection, "keyless"); final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .with(SqlServerConnectorConfig.TABLE_WHITELIST, "dbo.keyless") // rewrite key from table 'products': from {null} to {id} .with(SqlServerConnectorConfig.MSG_KEY_COLUMNS, "(.*).keyless:id") .build(); start(SqlServerConnector.class, config); SourceRecords records = consumeRecordsByTopic(1); List<SourceRecord> recordsForTopic = records.recordsForTopic("server1.dbo.keyless"); assertThat(recordsForTopic.get(0).key()).isNotNull(); Struct key = (Struct) recordsForTopic.get(0).key(); Assertions.assertThat(key.get("id")).isNotNull(); stopConnector(); } private void assertRecord(Struct record, List<SchemaAndValueField> expected) { expected.forEach(schemaAndValueField -> schemaAndValueField.assertFor(record)); } }
package io.debezium.connector.sqlserver; import static io.debezium.connector.sqlserver.util.TestHelper.TYPE_LENGTH_PARAMETER_KEY; import static io.debezium.connector.sqlserver.util.TestHelper.TYPE_NAME_PARAMETER_KEY; import static io.debezium.connector.sqlserver.util.TestHelper.TYPE_SCALE_PARAMETER_KEY; import static org.fest.assertions.Assertions.assertThat; import static org.fest.assertions.MapAssert.entry; import static org.junit.Assert.assertNull; import java.io.IOException; import java.sql.SQLException; import java.time.Instant; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TimeZone; import java.util.UUID; import java.util.concurrent.TimeUnit; import org.apache.kafka.connect.data.Field; import org.apache.kafka.connect.data.Schema; import org.apache.kafka.connect.data.SchemaBuilder; import org.apache.kafka.connect.data.Struct; import org.apache.kafka.connect.source.SourceRecord; import org.awaitility.Awaitility; import org.fest.assertions.Assertions; import org.junit.After; import org.junit.Before; import org.junit.Test; import io.debezium.config.Configuration; import io.debezium.connector.sqlserver.SqlServerConnectorConfig.SnapshotMode; import io.debezium.connector.sqlserver.util.TestHelper; import io.debezium.data.Envelope; import io.debezium.data.SchemaAndValueField; import io.debezium.data.SourceRecordAssert; import io.debezium.data.VerifyRecord; import io.debezium.doc.FixFor; import io.debezium.embedded.AbstractConnectorTest; import io.debezium.junit.logging.LogInterceptor; import io.debezium.relational.Tables; import io.debezium.relational.ddl.DdlParser; import io.debezium.relational.history.DatabaseHistory; import io.debezium.relational.history.DatabaseHistoryException; import io.debezium.relational.history.DatabaseHistoryListener; import io.debezium.relational.history.FileDatabaseHistory; import io.debezium.relational.history.HistoryRecordComparator; import io.debezium.relational.history.TableChanges; import io.debezium.util.Testing; /** * Integration test for the Debezium SQL Server connector. * * @author Jiri Pechanec */ public class SqlServerConnectorIT extends AbstractConnectorTest { private SqlServerConnection connection; @Before public void before() throws SQLException { TestHelper.createTestDatabase(); connection = TestHelper.testConnection(); connection.execute( "CREATE TABLE tablea (id int primary key, cola varchar(30))", "CREATE TABLE tableb (id int primary key, colb varchar(30))", "INSERT INTO tablea VALUES(1, 'a')"); TestHelper.enableTableCdc(connection, "tablea"); TestHelper.enableTableCdc(connection, "tableb"); initializeConnectorTestFramework(); Testing.Files.delete(TestHelper.DB_HISTORY_PATH); // Testing.Print.enable(); } @After public void after() throws SQLException { if (connection != null) { connection.close(); } } @Test public void createAndDelete() throws Exception { final int RECORDS_PER_TABLE = 5; final int TABLES = 2; final int ID_START = 10; final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .build(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); // Wait for snapshot completion consumeRecordsByTopic(1); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = ID_START + i; connection.execute( "INSERT INTO tablea VALUES(" + id + ", 'a')"); connection.execute( "INSERT INTO tableb VALUES(" + id + ", 'b')"); } final SourceRecords records = consumeRecordsByTopic(RECORDS_PER_TABLE * TABLES); final List<SourceRecord> tableA = records.recordsForTopic("server1.dbo.tablea"); final List<SourceRecord> tableB = records.recordsForTopic("server1.dbo.tableb"); Assertions.assertThat(tableA).hasSize(RECORDS_PER_TABLE); Assertions.assertThat(tableB).hasSize(RECORDS_PER_TABLE); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final SourceRecord recordA = tableA.get(i); final SourceRecord recordB = tableB.get(i); final List<SchemaAndValueField> expectedRowA = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, i + ID_START), new SchemaAndValueField("cola", Schema.OPTIONAL_STRING_SCHEMA, "a")); final List<SchemaAndValueField> expectedRowB = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, i + ID_START), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "b")); final Struct keyA = (Struct) recordA.key(); final Struct valueA = (Struct) recordA.value(); assertRecord((Struct) valueA.get("after"), expectedRowA); assertNull(valueA.get("before")); final Struct keyB = (Struct) recordB.key(); final Struct valueB = (Struct) recordB.value(); assertRecord((Struct) valueB.get("after"), expectedRowB); assertNull(valueB.get("before")); } connection.execute("DELETE FROM tableB"); final SourceRecords deleteRecords = consumeRecordsByTopic(2 * RECORDS_PER_TABLE); final List<SourceRecord> deleteTableA = deleteRecords.recordsForTopic("server1.dbo.tablea"); final List<SourceRecord> deleteTableB = deleteRecords.recordsForTopic("server1.dbo.tableb"); Assertions.assertThat(deleteTableA).isNullOrEmpty(); Assertions.assertThat(deleteTableB).hasSize(2 * RECORDS_PER_TABLE); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final SourceRecord deleteRecord = deleteTableB.get(i * 2); final SourceRecord tombstoneRecord = deleteTableB.get(i * 2 + 1); final List<SchemaAndValueField> expectedDeleteRow = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, i + ID_START), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "b")); final Struct deleteKey = (Struct) deleteRecord.key(); final Struct deleteValue = (Struct) deleteRecord.value(); assertRecord((Struct) deleteValue.get("before"), expectedDeleteRow); assertNull(deleteValue.get("after")); final Struct tombstoneKey = (Struct) tombstoneRecord.key(); final Struct tombstoneValue = (Struct) tombstoneRecord.value(); assertNull(tombstoneValue); } stopConnector(); } @Test @FixFor("DBZ-1642") public void readOnlyApplicationIntent() throws Exception { final LogInterceptor logInterceptor = new LogInterceptor(); final String appId = "readOnlyApplicationIntent-" + UUID.randomUUID(); final int RECORDS_PER_TABLE = 5; final int TABLES = 2; final int ID_START = 10; final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .with("database.applicationIntent", "ReadOnly") .with("database.applicationName", appId) .build(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); // Wait for snapshot completion consumeRecordsByTopic(1); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = ID_START + i; connection.execute( "INSERT INTO tablea VALUES(" + id + ", 'a')"); connection.execute( "INSERT INTO tableb VALUES(" + id + ", 'b')"); } final SourceRecords records = consumeRecordsByTopic(RECORDS_PER_TABLE * TABLES); final List<SourceRecord> tableA = records.recordsForTopic("server1.dbo.tablea"); final List<SourceRecord> tableB = records.recordsForTopic("server1.dbo.tableb"); Assertions.assertThat(tableA).hasSize(RECORDS_PER_TABLE); Assertions.assertThat(tableB).hasSize(RECORDS_PER_TABLE); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final SourceRecord recordA = tableA.get(i); final SourceRecord recordB = tableB.get(i); final List<SchemaAndValueField> expectedRowA = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, i + ID_START), new SchemaAndValueField("cola", Schema.OPTIONAL_STRING_SCHEMA, "a")); final List<SchemaAndValueField> expectedRowB = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, i + ID_START), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "b")); final Struct keyA = (Struct) recordA.key(); final Struct valueA = (Struct) recordA.value(); assertRecord((Struct) valueA.get("after"), expectedRowA); assertNull(valueA.get("before")); final Struct keyB = (Struct) recordB.key(); final Struct valueB = (Struct) recordB.value(); assertRecord((Struct) valueB.get("after"), expectedRowB); assertNull(valueB.get("before")); } assertThat(logInterceptor.containsMessage("Schema locking was disabled in connector configuration")).isTrue(); // Verify that multiple subsequent transactions are used in streaming phase with read-only intent try (final SqlServerConnection admin = TestHelper.adminConnection()) { final Set<Long> txIds = new HashSet<>(); Awaitility.await().atMost(TestHelper.waitTimeForRecords() * 5, TimeUnit.SECONDS).pollInterval(100, TimeUnit.MILLISECONDS).until(() -> { admin.query( "SELECT (SELECT transaction_id FROM sys.dm_tran_session_transactions AS t WHERE s.session_id=t.session_id) FROM sys.dm_exec_sessions AS s WHERE program_name='" + appId + "'", rs -> { rs.next(); txIds.add(rs.getLong(1)); }); return txIds.size() > 2; }); } stopConnector(); } @Test @FixFor("DBZ-1643") public void timestampAndTimezone() throws Exception { final int RECORDS_PER_TABLE = 5; final int TABLES = 2; final int ID_START = 10; final TimeZone currentTimeZone = TimeZone.getDefault(); try { TimeZone.setDefault(TimeZone.getTimeZone("Australia/Canberra")); final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .build(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); // Wait for snapshot completion consumeRecordsByTopic(1); final Instant now = Instant.now(); final Instant lowerBound = now.minusSeconds(5 * 60); final Instant upperBound = now.plusSeconds(5 * 60); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = ID_START + i; connection.execute( "INSERT INTO tablea VALUES(" + id + ", 'a')"); connection.execute( "INSERT INTO tableb VALUES(" + id + ", 'b')"); } final SourceRecords records = consumeRecordsByTopic(RECORDS_PER_TABLE * TABLES); final List<SourceRecord> tableA = records.recordsForTopic("server1.dbo.tablea"); final List<SourceRecord> tableB = records.recordsForTopic("server1.dbo.tableb"); Assertions.assertThat(tableA).hasSize(RECORDS_PER_TABLE); Assertions.assertThat(tableB).hasSize(RECORDS_PER_TABLE); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final SourceRecord recordA = tableA.get(i); final long timestamp = ((Struct) recordA.value()).getStruct("source").getInt64("ts_ms"); final Instant instant = Instant.ofEpochMilli(timestamp); Assertions.assertThat(instant.isAfter(lowerBound) && instant.isBefore(upperBound)).isTrue(); } stopConnector(); } finally { TimeZone.setDefault(currentTimeZone); } } @Test public void deleteWithoutTombstone() throws Exception { final int RECORDS_PER_TABLE = 5; final int TABLES = 2; final int ID_START = 10; final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .with(SqlServerConnectorConfig.TOMBSTONES_ON_DELETE, false) .build(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); // Wait for snapshot completion consumeRecordsByTopic(1); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = ID_START + i; connection.execute( "INSERT INTO tablea VALUES(" + id + ", 'a')"); connection.execute( "INSERT INTO tableb VALUES(" + id + ", 'b')"); } final SourceRecords records = consumeRecordsByTopic(RECORDS_PER_TABLE * TABLES); connection.execute("DELETE FROM tableB"); final SourceRecords deleteRecords = consumeRecordsByTopic(RECORDS_PER_TABLE); final List<SourceRecord> deleteTableA = deleteRecords.recordsForTopic("server1.dbo.tablea"); final List<SourceRecord> deleteTableB = deleteRecords.recordsForTopic("server1.dbo.tableb"); Assertions.assertThat(deleteTableA).isNullOrEmpty(); Assertions.assertThat(deleteTableB).hasSize(RECORDS_PER_TABLE); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final SourceRecord deleteRecord = deleteTableB.get(i); final List<SchemaAndValueField> expectedDeleteRow = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, i + ID_START), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "b")); final Struct deleteKey = (Struct) deleteRecord.key(); final Struct deleteValue = (Struct) deleteRecord.value(); assertRecord((Struct) deleteValue.get("before"), expectedDeleteRow); assertNull(deleteValue.get("after")); } stopConnector(); } @Test public void update() throws Exception { final int RECORDS_PER_TABLE = 5; final int ID_START = 10; final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .build(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); // Testing.Print.enable(); // Wait for snapshot completion consumeRecordsByTopic(1); connection.setAutoCommit(false); final String[] tableBInserts = new String[RECORDS_PER_TABLE]; for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = ID_START + i; tableBInserts[i] = "INSERT INTO tableb VALUES(" + id + ", 'b')"; } connection.execute(tableBInserts); connection.setAutoCommit(true); connection.execute("UPDATE tableb SET colb='z'"); final SourceRecords records = consumeRecordsByTopic(RECORDS_PER_TABLE * 2); final List<SourceRecord> tableB = records.recordsForTopic("server1.dbo.tableb"); Assertions.assertThat(tableB).hasSize(RECORDS_PER_TABLE * 2); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final SourceRecord recordB = tableB.get(i); final List<SchemaAndValueField> expectedRowB = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, i + ID_START), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "b")); final Struct keyB = (Struct) recordB.key(); final Struct valueB = (Struct) recordB.value(); assertRecord((Struct) valueB.get("after"), expectedRowB); assertNull(valueB.get("before")); } for (int i = 0; i < RECORDS_PER_TABLE; i++) { final SourceRecord recordB = tableB.get(i + RECORDS_PER_TABLE); final List<SchemaAndValueField> expectedBefore = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, i + ID_START), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "b")); final List<SchemaAndValueField> expectedAfter = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, i + ID_START), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "z")); final Struct keyB = (Struct) recordB.key(); final Struct valueB = (Struct) recordB.value(); assertRecord((Struct) valueB.get("before"), expectedBefore); assertRecord((Struct) valueB.get("after"), expectedAfter); } stopConnector(); } @Test public void updatePrimaryKey() throws Exception { final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .build(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); // Testing.Print.enable(); // Wait for snapshot completion consumeRecordsByTopic(1); connection.execute("INSERT INTO tableb VALUES(1, 'b')"); consumeRecordsByTopic(1); connection.setAutoCommit(false); connection.execute( "UPDATE tablea SET id=100 WHERE id=1", "UPDATE tableb SET id=100 WHERE id=1"); final SourceRecords records = consumeRecordsByTopic(6); final List<SourceRecord> tableA = records.recordsForTopic("server1.dbo.tablea"); final List<SourceRecord> tableB = records.recordsForTopic("server1.dbo.tableb"); Assertions.assertThat(tableA).hasSize(3); Assertions.assertThat(tableB).hasSize(3); final List<SchemaAndValueField> expectedDeleteRowA = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, 1), new SchemaAndValueField("cola", Schema.OPTIONAL_STRING_SCHEMA, "a")); final List<SchemaAndValueField> expectedDeleteKeyA = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, 1)); final List<SchemaAndValueField> expectedInsertRowA = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, 100), new SchemaAndValueField("cola", Schema.OPTIONAL_STRING_SCHEMA, "a")); final List<SchemaAndValueField> expectedInsertKeyA = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, 100)); final SourceRecord deleteRecordA = tableA.get(0); final SourceRecord tombstoneRecordA = tableA.get(1); final SourceRecord insertRecordA = tableA.get(2); final Struct deleteKeyA = (Struct) deleteRecordA.key(); final Struct deleteValueA = (Struct) deleteRecordA.value(); assertRecord(deleteValueA.getStruct("before"), expectedDeleteRowA); assertRecord(deleteKeyA, expectedDeleteKeyA); assertNull(deleteValueA.get("after")); final Struct tombstoneKeyA = (Struct) tombstoneRecordA.key(); final Struct tombstoneValueA = (Struct) tombstoneRecordA.value(); assertRecord(tombstoneKeyA, expectedDeleteKeyA); assertNull(tombstoneValueA); final Struct insertKeyA = (Struct) insertRecordA.key(); final Struct insertValueA = (Struct) insertRecordA.value(); assertRecord(insertValueA.getStruct("after"), expectedInsertRowA); assertRecord(insertKeyA, expectedInsertKeyA); assertNull(insertValueA.get("before")); final List<SchemaAndValueField> expectedDeleteRowB = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, 1), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "b")); final List<SchemaAndValueField> expectedDeleteKeyB = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, 1)); final List<SchemaAndValueField> expectedInsertRowB = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, 100), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "b")); final List<SchemaAndValueField> expectedInsertKeyB = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, 100)); final SourceRecord deleteRecordB = tableB.get(0); final SourceRecord tombstoneRecordB = tableB.get(1); final SourceRecord insertRecordB = tableB.get(2); final Struct deletekeyB = (Struct) deleteRecordB.key(); final Struct deleteValueB = (Struct) deleteRecordB.value(); assertRecord(deleteValueB.getStruct("before"), expectedDeleteRowB); assertRecord(deletekeyB, expectedDeleteKeyB); assertNull(deleteValueB.get("after")); assertThat(deleteValueB.getStruct("source").getInt64("event_serial_no")).isEqualTo(1L); final Struct tombstonekeyB = (Struct) tombstoneRecordB.key(); final Struct tombstoneValueB = (Struct) tombstoneRecordB.value(); assertRecord(tombstonekeyB, expectedDeleteKeyB); assertNull(tombstoneValueB); final Struct insertkeyB = (Struct) insertRecordB.key(); final Struct insertValueB = (Struct) insertRecordB.value(); assertRecord(insertValueB.getStruct("after"), expectedInsertRowB); assertRecord(insertkeyB, expectedInsertKeyB); assertNull(insertValueB.get("before")); assertThat(insertValueB.getStruct("source").getInt64("event_serial_no")).isEqualTo(2L); stopConnector(); } @Test @FixFor("DBZ-1152") public void updatePrimaryKeyWithRestartInMiddle() throws Exception { final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .build(); start(SqlServerConnector.class, config, record -> { final Struct envelope = (Struct) record.value(); return envelope != null && "c".equals(envelope.get("op")) && (envelope.getStruct("after").getInt32("id") == 100); }); assertConnectorIsRunning(); // Testing.Print.enable(); // Wait for snapshot completion consumeRecordsByTopic(1); connection.execute("INSERT INTO tableb VALUES(1, 'b')"); consumeRecordsByTopic(1); connection.setAutoCommit(false); connection.execute( "UPDATE tablea SET id=100 WHERE id=1", "UPDATE tableb SET id=100 WHERE id=1"); final SourceRecords records1 = consumeRecordsByTopic(2); stopConnector(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); final SourceRecords records2 = consumeRecordsByTopic(4); final List<SourceRecord> tableA = records1.recordsForTopic("server1.dbo.tablea"); tableA.addAll(records2.recordsForTopic("server1.dbo.tablea")); final List<SourceRecord> tableB = records2.recordsForTopic("server1.dbo.tableb"); Assertions.assertThat(tableA).hasSize(3); Assertions.assertThat(tableB).hasSize(3); final List<SchemaAndValueField> expectedDeleteRowA = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, 1), new SchemaAndValueField("cola", Schema.OPTIONAL_STRING_SCHEMA, "a")); final List<SchemaAndValueField> expectedDeleteKeyA = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, 1)); final List<SchemaAndValueField> expectedInsertRowA = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, 100), new SchemaAndValueField("cola", Schema.OPTIONAL_STRING_SCHEMA, "a")); final List<SchemaAndValueField> expectedInsertKeyA = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, 100)); final SourceRecord deleteRecordA = tableA.get(0); final SourceRecord tombstoneRecordA = tableA.get(1); final SourceRecord insertRecordA = tableA.get(2); final Struct deleteKeyA = (Struct) deleteRecordA.key(); final Struct deleteValueA = (Struct) deleteRecordA.value(); assertRecord(deleteValueA.getStruct("before"), expectedDeleteRowA); assertRecord(deleteKeyA, expectedDeleteKeyA); assertNull(deleteValueA.get("after")); final Struct tombstoneKeyA = (Struct) tombstoneRecordA.key(); final Struct tombstoneValueA = (Struct) tombstoneRecordA.value(); assertRecord(tombstoneKeyA, expectedDeleteKeyA); assertNull(tombstoneValueA); final Struct insertKeyA = (Struct) insertRecordA.key(); final Struct insertValueA = (Struct) insertRecordA.value(); assertRecord(insertValueA.getStruct("after"), expectedInsertRowA); assertRecord(insertKeyA, expectedInsertKeyA); assertNull(insertValueA.get("before")); final List<SchemaAndValueField> expectedDeleteRowB = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, 1), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "b")); final List<SchemaAndValueField> expectedDeleteKeyB = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, 1)); final List<SchemaAndValueField> expectedInsertRowB = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, 100), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "b")); final List<SchemaAndValueField> expectedInsertKeyB = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, 100)); final SourceRecord deleteRecordB = tableB.get(0); final SourceRecord tombstoneRecordB = tableB.get(1); final SourceRecord insertRecordB = tableB.get(2); final Struct deletekeyB = (Struct) deleteRecordB.key(); final Struct deleteValueB = (Struct) deleteRecordB.value(); assertRecord(deleteValueB.getStruct("before"), expectedDeleteRowB); assertRecord(deletekeyB, expectedDeleteKeyB); assertNull(deleteValueB.get("after")); final Struct tombstonekeyB = (Struct) tombstoneRecordB.key(); final Struct tombstoneValueB = (Struct) tombstoneRecordB.value(); assertRecord(tombstonekeyB, expectedDeleteKeyB); assertNull(tombstoneValueB); final Struct insertkeyB = (Struct) insertRecordB.key(); final Struct insertValueB = (Struct) insertRecordB.value(); assertRecord(insertValueB.getStruct("after"), expectedInsertRowB); assertRecord(insertkeyB, expectedInsertKeyB); assertNull(insertValueB.get("before")); stopConnector(); } @Test public void streamChangesWhileStopped() throws Exception { final int RECORDS_PER_TABLE = 5; final int TABLES = 2; final int ID_START = 10; final int ID_RESTART = 100; final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .build(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); // Wait for snapshot completion consumeRecordsByTopic(1); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = ID_START + i; connection.execute( "INSERT INTO tablea VALUES(" + id + ", 'a')"); connection.execute( "INSERT INTO tableb VALUES(" + id + ", 'b')"); } consumeRecordsByTopic(RECORDS_PER_TABLE * TABLES); stopConnector(); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = ID_RESTART + i; connection.execute( "INSERT INTO tablea VALUES(" + id + ", 'a')"); connection.execute( "INSERT INTO tableb VALUES(" + id + ", 'b')"); } start(SqlServerConnector.class, config); assertConnectorIsRunning(); final SourceRecords records = consumeRecordsByTopic(RECORDS_PER_TABLE * TABLES); final List<SourceRecord> tableA = records.recordsForTopic("server1.dbo.tablea"); List<SourceRecord> tableB = records.recordsForTopic("server1.dbo.tableb"); Assertions.assertThat(tableA).hasSize(RECORDS_PER_TABLE); Assertions.assertThat(tableB).hasSize(RECORDS_PER_TABLE); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = i + ID_RESTART; final SourceRecord recordA = tableA.get(i); final SourceRecord recordB = tableB.get(i); final List<SchemaAndValueField> expectedRowA = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, id), new SchemaAndValueField("cola", Schema.OPTIONAL_STRING_SCHEMA, "a")); final List<SchemaAndValueField> expectedRowB = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, id), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "b")); final Struct valueA = (Struct) recordA.value(); assertRecord((Struct) valueA.get("after"), expectedRowA); assertNull(valueA.get("before")); final Struct valueB = (Struct) recordB.value(); assertRecord((Struct) valueB.get("after"), expectedRowB); assertNull(valueB.get("before")); } } @Test @FixFor("DBZ-1069") public void verifyOffsets() throws Exception { final int RECORDS_PER_TABLE = 5; final int TABLES = 2; final int ID_START = 10; final int ID_RESTART = 100; final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .build(); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = ID_START + i; connection.execute( "INSERT INTO tablea VALUES(" + id + ", 'a')"); connection.execute( "INSERT INTO tableb VALUES(" + id + ", 'b')"); } for (int i = 0; !connection.getMaxLsn().isAvailable(); i++) { if (i == 30) { org.junit.Assert.fail("Initial changes not written to CDC structures"); } Testing.debug("Waiting for initial changes to be propagated to CDC structures"); Thread.sleep(1000); } start(SqlServerConnector.class, config); assertConnectorIsRunning(); List<SourceRecord> records = consumeRecordsByTopic(1 + RECORDS_PER_TABLE * TABLES).allRecordsInOrder(); records = records.subList(1, records.size()); for (Iterator<SourceRecord> it = records.iterator(); it.hasNext();) { SourceRecord record = it.next(); assertThat(record.sourceOffset().get("snapshot")).as("Snapshot phase").isEqualTo(true); if (it.hasNext()) { assertThat(record.sourceOffset().get("snapshot_completed")).as("Snapshot in progress").isEqualTo(false); } else { assertThat(record.sourceOffset().get("snapshot_completed")).as("Snapshot completed").isEqualTo(true); } } stopConnector(); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = ID_RESTART + i; connection.execute( "INSERT INTO tablea VALUES(" + id + ", 'a')"); connection.execute( "INSERT INTO tableb VALUES(" + id + ", 'b')"); } start(SqlServerConnector.class, config); assertConnectorIsRunning(); final SourceRecords sourceRecords = consumeRecordsByTopic(RECORDS_PER_TABLE * TABLES); final List<SourceRecord> tableA = sourceRecords.recordsForTopic("server1.dbo.tablea"); final List<SourceRecord> tableB = sourceRecords.recordsForTopic("server1.dbo.tableb"); Assertions.assertThat(tableA).hasSize(RECORDS_PER_TABLE); Assertions.assertThat(tableB).hasSize(RECORDS_PER_TABLE); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = i + ID_RESTART; final SourceRecord recordA = tableA.get(i); final SourceRecord recordB = tableB.get(i); final List<SchemaAndValueField> expectedRowA = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, id), new SchemaAndValueField("cola", Schema.OPTIONAL_STRING_SCHEMA, "a")); final List<SchemaAndValueField> expectedRowB = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, id), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "b")); final Struct valueA = (Struct) recordA.value(); assertRecord((Struct) valueA.get("after"), expectedRowA); assertNull(valueA.get("before")); final Struct valueB = (Struct) recordB.value(); assertRecord((Struct) valueB.get("after"), expectedRowB); assertNull(valueB.get("before")); assertThat(recordA.sourceOffset().get("snapshot")).as("Streaming phase").isNull(); assertThat(recordA.sourceOffset().get("snapshot_completed")).as("Streaming phase").isNull(); assertThat(recordA.sourceOffset().get("change_lsn")).as("LSN present").isNotNull(); assertThat(recordB.sourceOffset().get("snapshot")).as("Streaming phase").isNull(); assertThat(recordB.sourceOffset().get("snapshot_completed")).as("Streaming phase").isNull(); assertThat(recordB.sourceOffset().get("change_lsn")).as("LSN present").isNotNull(); } } @Test public void whitelistTable() throws Exception { final int RECORDS_PER_TABLE = 5; final int TABLES = 1; final int ID_START = 10; final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.SCHEMA_ONLY) .with(SqlServerConnectorConfig.TABLE_WHITELIST, "dbo.tableb") .build(); connection.execute( "INSERT INTO tableb VALUES(1, 'b')"); start(SqlServerConnector.class, config); assertConnectorIsRunning(); // Wait for snapshot completion consumeRecordsByTopic(1); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = ID_START + i; connection.execute( "INSERT INTO tablea VALUES(" + id + ", 'a')"); connection.execute( "INSERT INTO tableb VALUES(" + id + ", 'b')"); } final SourceRecords records = consumeRecordsByTopic(RECORDS_PER_TABLE * TABLES); final List<SourceRecord> tableA = records.recordsForTopic("server1.dbo.tablea"); final List<SourceRecord> tableB = records.recordsForTopic("server1.dbo.tableb"); Assertions.assertThat(tableA == null || tableA.isEmpty()).isTrue(); Assertions.assertThat(tableB).hasSize(RECORDS_PER_TABLE); stopConnector(); } @Test public void blacklistTable() throws Exception { final int RECORDS_PER_TABLE = 5; final int TABLES = 1; final int ID_START = 10; final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .with(SqlServerConnectorConfig.TABLE_BLACKLIST, "dbo.tablea") .build(); connection.execute( "INSERT INTO tableb VALUES(1, 'b')"); start(SqlServerConnector.class, config); assertConnectorIsRunning(); // Wait for snapshot completion consumeRecordsByTopic(1); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = ID_START + i; connection.execute( "INSERT INTO tablea VALUES(" + id + ", 'a')"); connection.execute( "INSERT INTO tableb VALUES(" + id + ", 'b')"); } final SourceRecords records = consumeRecordsByTopic(RECORDS_PER_TABLE * TABLES); final List<SourceRecord> tableA = records.recordsForTopic("server1.dbo.tablea"); final List<SourceRecord> tableB = records.recordsForTopic("server1.dbo.tableb"); Assertions.assertThat(tableA == null || tableA.isEmpty()).isTrue(); Assertions.assertThat(tableB).hasSize(RECORDS_PER_TABLE); stopConnector(); } @Test @FixFor("DBZ-1617") public void blacklistColumnWhenCdcColumnsDoNotMatchWithOriginalSnapshot() throws Exception { connection.execute("CREATE TABLE table_a (id int, name varchar(30), amount integer primary key(id))"); TestHelper.enableTableCdc(connection, "table_a"); connection.execute("ALTER TABLE table_a ADD blacklisted_column varchar(30)"); final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.SCHEMA_ONLY) .with(SqlServerConnectorConfig.COLUMN_BLACKLIST, "dbo.table_a.blacklisted_column") .build(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); // Wait for snapshot completion consumeRecordsByTopic(1); connection.execute("INSERT INTO table_a VALUES(10, 'some_name', 120, 'some_string')"); final SourceRecords records = consumeRecordsByTopic(1); final List<SourceRecord> tableA = records.recordsForTopic("server1.dbo.table_a"); Schema expectedSchemaA = SchemaBuilder.struct() .optional() .name("server1.dbo.table_a.Value") .field("id", Schema.INT32_SCHEMA) .field("name", Schema.OPTIONAL_STRING_SCHEMA) .field("amount", Schema.OPTIONAL_INT32_SCHEMA) .build(); Struct expectedValueA = new Struct(expectedSchemaA) .put("id", 10) .put("name", "some_name") .put("amount", 120); Assertions.assertThat(tableA).hasSize(1); SourceRecordAssert.assertThat(tableA.get(0)) .valueAfterFieldIsEqualTo(expectedValueA) .valueAfterFieldSchemaIsEqualTo(expectedSchemaA); stopConnector(); } @Test @FixFor("DBZ-1067") public void blacklistColumn() throws Exception { connection.execute( "CREATE TABLE blacklist_column_table_a (id int, name varchar(30), amount integer primary key(id))", "CREATE TABLE blacklist_column_table_b (id int, name varchar(30), amount integer primary key(id))"); TestHelper.enableTableCdc(connection, "blacklist_column_table_a"); TestHelper.enableTableCdc(connection, "blacklist_column_table_b"); final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.SCHEMA_ONLY) .with(SqlServerConnectorConfig.COLUMN_BLACKLIST, "dbo.blacklist_column_table_a.amount") .build(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); // Wait for snapshot completion consumeRecordsByTopic(1); connection.execute("INSERT INTO blacklist_column_table_a VALUES(10, 'some_name', 120)"); connection.execute("INSERT INTO blacklist_column_table_b VALUES(11, 'some_name', 447)"); final SourceRecords records = consumeRecordsByTopic(2); final List<SourceRecord> tableA = records.recordsForTopic("server1.dbo.blacklist_column_table_a"); final List<SourceRecord> tableB = records.recordsForTopic("server1.dbo.blacklist_column_table_b"); Schema expectedSchemaA = SchemaBuilder.struct() .optional() .name("server1.dbo.blacklist_column_table_a.Value") .field("id", Schema.INT32_SCHEMA) .field("name", Schema.OPTIONAL_STRING_SCHEMA) .build(); Struct expectedValueA = new Struct(expectedSchemaA) .put("id", 10) .put("name", "some_name"); Schema expectedSchemaB = SchemaBuilder.struct() .optional() .name("server1.dbo.blacklist_column_table_b.Value") .field("id", Schema.INT32_SCHEMA) .field("name", Schema.OPTIONAL_STRING_SCHEMA) .field("amount", Schema.OPTIONAL_INT32_SCHEMA) .build(); Struct expectedValueB = new Struct(expectedSchemaB) .put("id", 11) .put("name", "some_name") .put("amount", 447); Assertions.assertThat(tableA).hasSize(1); SourceRecordAssert.assertThat(tableA.get(0)) .valueAfterFieldIsEqualTo(expectedValueA) .valueAfterFieldSchemaIsEqualTo(expectedSchemaA); Assertions.assertThat(tableB).hasSize(1); SourceRecordAssert.assertThat(tableB.get(0)) .valueAfterFieldIsEqualTo(expectedValueB) .valueAfterFieldSchemaIsEqualTo(expectedSchemaB); stopConnector(); } @Test @FixFor("DBZ-1692") public void shouldConsumeEventsWithMaskedHashedColumns() throws Exception { connection.execute( "CREATE TABLE masked_hashed_column_table_a (id int, name varchar(255) primary key(id))", "CREATE TABLE masked_hashed_column_table_b (id int, name varchar(20), primary key(id))"); TestHelper.enableTableCdc(connection, "masked_hashed_column_table_a"); TestHelper.enableTableCdc(connection, "masked_hashed_column_table_b"); final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.SCHEMA_ONLY) .with("column.mask.hash.SHA-256.with.salt.CzQMA0cB5K", "testDB.dbo.masked_hashed_column_table_a.name, testDB.dbo.masked_hashed_column_table_b.name") .build(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); // Wait for snapshot completion consumeRecordsByTopic(1); connection.execute("INSERT INTO masked_hashed_column_table_a VALUES(10, 'some_name')"); connection.execute("INSERT INTO masked_hashed_column_table_b VALUES(11, 'some_name')"); final SourceRecords records = consumeRecordsByTopic(2); final List<SourceRecord> tableA = records.recordsForTopic("server1.dbo.masked_hashed_column_table_a"); final List<SourceRecord> tableB = records.recordsForTopic("server1.dbo.masked_hashed_column_table_b"); assertThat(tableA).hasSize(1); SourceRecord record = tableA.get(0); VerifyRecord.isValidInsert(record, "id", 10); Struct value = (Struct) record.value(); if (value.getStruct("after") != null) { assertThat(value.getStruct("after").getString("name")).isEqualTo("3b225d0696535d66f2c0fb2e36b012c520d396af3dd8f18330b9c9cd23ca714e"); } assertThat(tableB).hasSize(1); record = tableB.get(0); VerifyRecord.isValidInsert(record, "id", 11); value = (Struct) record.value(); if (value.getStruct("after") != null) { assertThat(value.getStruct("after").getString("name")).isEqualTo("3b225d0696535d66f2c0"); } stopConnector(); } @Test @FixFor("DBZ-1972") public void shouldConsumeEventsWithMaskedAndTruncatedColumns() throws Exception { connection.execute( "CREATE TABLE masked_hashed_column_table (id int, name varchar(255) primary key(id))", "CREATE TABLE truncated_column_table (id int, name varchar(20), primary key(id))"); TestHelper.enableTableCdc(connection, "masked_hashed_column_table"); TestHelper.enableTableCdc(connection, "truncated_column_table"); final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.SCHEMA_ONLY) .with("column.mask.with.12.chars", "testDB.dbo.masked_hashed_column_table.name") .with("column.truncate.to.4.chars", "testDB.dbo.truncated_column_table.name") .build(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); // Wait for snapshot completion consumeRecordsByTopic(1); connection.execute("INSERT INTO masked_hashed_column_table VALUES(10, 'some_name')"); connection.execute("INSERT INTO truncated_column_table VALUES(11, 'some_name')"); final SourceRecords records = consumeRecordsByTopic(2); final List<SourceRecord> tableA = records.recordsForTopic("server1.dbo.masked_hashed_column_table"); final List<SourceRecord> tableB = records.recordsForTopic("server1.dbo.truncated_column_table"); assertThat(tableA).hasSize(1); SourceRecord record = tableA.get(0); VerifyRecord.isValidInsert(record, "id", 10); Struct value = (Struct) record.value(); if (value.getStruct("after") != null) { assertThat(value.getStruct("after").getString("name")).isEqualTo("************"); } assertThat(tableB).hasSize(1); record = tableB.get(0); VerifyRecord.isValidInsert(record, "id", 11); value = (Struct) record.value(); if (value.getStruct("after") != null) { assertThat(value.getStruct("after").getString("name")).isEqualTo("some"); } stopConnector(); } /** * Passing the "applicationName" property which can be asserted from the connected sessions". */ @Test @FixFor("DBZ-964") public void shouldPropagateDatabaseDriverProperties() throws Exception { final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.SCHEMA_ONLY) .with("database.applicationName", "Debezium App DBZ-964") .build(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); // consuming one record to make sure the connector establishes the DB connection which happens asynchronously // after the start() call connection.execute("INSERT INTO tablea VALUES(964, 'a')"); consumeRecordsByTopic(1); connection.query("select count(1) from sys.dm_exec_sessions where program_name = 'Debezium App DBZ-964'", rs -> { rs.next(); assertThat(rs.getInt(1)).isGreaterThanOrEqualTo(1); }); } private void restartInTheMiddleOfTx(boolean restartJustAfterSnapshot, boolean afterStreaming) throws Exception { final int RECORDS_PER_TABLE = 30; final int TABLES = 2; final int ID_START = 10; final int ID_RESTART = 1000; final int HALF_ID = ID_START + RECORDS_PER_TABLE / 2; final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .build(); if (restartJustAfterSnapshot) { start(SqlServerConnector.class, config); assertConnectorIsRunning(); // Wait for snapshot to be completed consumeRecordsByTopic(1); stopConnector(); connection.execute("INSERT INTO tablea VALUES(-1, '-a')"); } start(SqlServerConnector.class, config, record -> { if (!"server1.dbo.tablea.Envelope".equals(record.valueSchema().name())) { return false; } final Struct envelope = (Struct) record.value(); final Struct after = envelope.getStruct("after"); final Integer id = after.getInt32("id"); final String value = after.getString("cola"); return id != null && id == HALF_ID && "a".equals(value); }); assertConnectorIsRunning(); // Wait for snapshot to be completed or a first streaming message delivered consumeRecordsByTopic(1); if (afterStreaming) { connection.execute("INSERT INTO tablea VALUES(-2, '-a')"); final SourceRecords records = consumeRecordsByTopic(1); final List<SchemaAndValueField> expectedRow = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, -2), new SchemaAndValueField("cola", Schema.OPTIONAL_STRING_SCHEMA, "-a")); assertRecord(((Struct) records.allRecordsInOrder().get(0).value()).getStruct(Envelope.FieldName.AFTER), expectedRow); } connection.setAutoCommit(false); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = ID_START + i; connection.executeWithoutCommitting( "INSERT INTO tablea VALUES(" + id + ", 'a')"); connection.executeWithoutCommitting( "INSERT INTO tableb VALUES(" + id + ", 'b')"); } connection.connection().commit(); List<SourceRecord> records = consumeRecordsByTopic(RECORDS_PER_TABLE).allRecordsInOrder(); assertThat(records).hasSize(RECORDS_PER_TABLE); SourceRecord lastRecordForOffset = records.get(RECORDS_PER_TABLE - 1); Struct value = (Struct) lastRecordForOffset.value(); final List<SchemaAndValueField> expectedLastRow = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, HALF_ID - 1), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "b")); assertRecord((Struct) value.get("after"), expectedLastRow); stopConnector(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); SourceRecords sourceRecords = consumeRecordsByTopic(RECORDS_PER_TABLE); records = sourceRecords.allRecordsInOrder(); assertThat(records).hasSize(RECORDS_PER_TABLE); List<SourceRecord> tableA = sourceRecords.recordsForTopic("server1.dbo.tablea"); List<SourceRecord> tableB = sourceRecords.recordsForTopic("server1.dbo.tableb"); for (int i = 0; i < RECORDS_PER_TABLE / 2; i++) { final int id = HALF_ID + i; final SourceRecord recordA = tableA.get(i); final SourceRecord recordB = tableB.get(i); final List<SchemaAndValueField> expectedRowA = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, id), new SchemaAndValueField("cola", Schema.OPTIONAL_STRING_SCHEMA, "a")); final List<SchemaAndValueField> expectedRowB = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, id), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "b")); final Struct valueA = (Struct) recordA.value(); assertRecord((Struct) valueA.get("after"), expectedRowA); assertNull(valueA.get("before")); final Struct valueB = (Struct) recordB.value(); assertRecord((Struct) valueB.get("after"), expectedRowB); assertNull(valueB.get("before")); } for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = ID_RESTART + i; connection.executeWithoutCommitting( "INSERT INTO tablea VALUES(" + id + ", 'a')"); connection.executeWithoutCommitting( "INSERT INTO tableb VALUES(" + id + ", 'b')"); connection.connection().commit(); } sourceRecords = consumeRecordsByTopic(RECORDS_PER_TABLE * TABLES); tableA = sourceRecords.recordsForTopic("server1.dbo.tablea"); tableB = sourceRecords.recordsForTopic("server1.dbo.tableb"); Assertions.assertThat(tableA).hasSize(RECORDS_PER_TABLE); Assertions.assertThat(tableB).hasSize(RECORDS_PER_TABLE); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = i + ID_RESTART; final SourceRecord recordA = tableA.get(i); final SourceRecord recordB = tableB.get(i); final List<SchemaAndValueField> expectedRowA = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, id), new SchemaAndValueField("cola", Schema.OPTIONAL_STRING_SCHEMA, "a")); final List<SchemaAndValueField> expectedRowB = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, id), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "b")); final Struct valueA = (Struct) recordA.value(); assertRecord((Struct) valueA.get("after"), expectedRowA); assertNull(valueA.get("before")); final Struct valueB = (Struct) recordB.value(); assertRecord((Struct) valueB.get("after"), expectedRowB); assertNull(valueB.get("before")); } } @Test @FixFor("DBZ-1128") public void restartInTheMiddleOfTxAfterSnapshot() throws Exception { restartInTheMiddleOfTx(true, false); } @Test @FixFor("DBZ-1128") public void restartInTheMiddleOfTxAfterCompletedTx() throws Exception { restartInTheMiddleOfTx(false, true); } @Test @FixFor("DBZ-1128") public void restartInTheMiddleOfTx() throws Exception { restartInTheMiddleOfTx(false, false); } @Test @FixFor("DBZ-1242") public void testEmptySchemaWarningAfterApplyingFilters() throws Exception { // This captures all logged messages, allowing us to verify log message was written. final LogInterceptor logInterceptor = new LogInterceptor(); Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .with(SqlServerConnectorConfig.TABLE_WHITELIST, "my_products") .build(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); waitForAvailableRecords(100, TimeUnit.MILLISECONDS); stopConnector(value -> assertThat(logInterceptor.containsWarnMessage(NO_MONITORED_TABLES_WARNING)).isTrue()); } @Test @FixFor("DBZ-1242") public void testNoEmptySchemaWarningAfterApplyingFilters() throws Exception { // This captures all logged messages, allowing us to verify log message was written. final LogInterceptor logInterceptor = new LogInterceptor(); Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .build(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); waitForAvailableRecords(100, TimeUnit.MILLISECONDS); stopConnector(value -> assertThat(logInterceptor.containsWarnMessage(NO_MONITORED_TABLES_WARNING)).isFalse()); } @Test @FixFor("DBZ-916") public void keylessTable() throws Exception { connection.execute( "CREATE TABLE keyless (id int, name varchar(30))", "INSERT INTO keyless VALUES(1, 'k')"); TestHelper.enableTableCdc(connection, "keyless"); final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .with(SqlServerConnectorConfig.TABLE_WHITELIST, "dbo.keyless") .build(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); final List<SchemaAndValueField> key = Arrays.asList( new SchemaAndValueField("id", Schema.OPTIONAL_INT32_SCHEMA, 1), new SchemaAndValueField("name", Schema.OPTIONAL_STRING_SCHEMA, "k")); final List<SchemaAndValueField> key2 = Arrays.asList( new SchemaAndValueField("id", Schema.OPTIONAL_INT32_SCHEMA, 2), new SchemaAndValueField("name", Schema.OPTIONAL_STRING_SCHEMA, "k")); final List<SchemaAndValueField> key3 = Arrays.asList( new SchemaAndValueField("id", Schema.OPTIONAL_INT32_SCHEMA, 3), new SchemaAndValueField("name", Schema.OPTIONAL_STRING_SCHEMA, "k")); // Wait for snapshot completion SourceRecords records = consumeRecordsByTopic(1); assertThat(records.recordsForTopic("server1.dbo.keyless").get(0).key()).isNull(); assertThat(records.recordsForTopic("server1.dbo.keyless").get(0).keySchema()).isNull(); connection.execute( "INSERT INTO keyless VALUES(2, 'k')"); records = consumeRecordsByTopic(1); assertThat(records.recordsForTopic("server1.dbo.keyless").get(0).key()).isNull(); assertThat(records.recordsForTopic("server1.dbo.keyless").get(0).key()).isNull(); connection.execute( "UPDATE keyless SET id=3 WHERE ID=2"); records = consumeRecordsByTopic(3); final SourceRecord update1 = records.recordsForTopic("server1.dbo.keyless").get(0); assertThat(update1.key()).isNull(); assertThat(update1.keySchema()).isNull(); assertRecord(((Struct) update1.value()).getStruct(Envelope.FieldName.BEFORE), key2); assertRecord(((Struct) update1.value()).getStruct(Envelope.FieldName.AFTER), key3); connection.execute( "DELETE FROM keyless WHERE id=3"); records = consumeRecordsByTopic(2, false); assertThat(records.recordsForTopic("server1.dbo.keyless").get(0).key()).isNull(); assertThat(records.recordsForTopic("server1.dbo.keyless").get(0).keySchema()).isNull(); assertNull(records.recordsForTopic("server1.dbo.keyless").get(1).value()); stopConnector(); } @Test @FixFor("DBZ-1015") public void shouldRewriteIdentityKey() throws InterruptedException, SQLException { connection.execute( "CREATE TABLE keyless (id int, name varchar(30))", "INSERT INTO keyless VALUES(1, 'k')"); TestHelper.enableTableCdc(connection, "keyless"); final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .with(SqlServerConnectorConfig.TABLE_WHITELIST, "dbo.keyless") // rewrite key from table 'products': from {null} to {id} .with(SqlServerConnectorConfig.MSG_KEY_COLUMNS, "(.*).keyless:id") .build(); start(SqlServerConnector.class, config); SourceRecords records = consumeRecordsByTopic(1); List<SourceRecord> recordsForTopic = records.recordsForTopic("server1.dbo.keyless"); assertThat(recordsForTopic.get(0).key()).isNotNull(); Struct key = (Struct) recordsForTopic.get(0).key(); Assertions.assertThat(key.get("id")).isNotNull(); stopConnector(); } @Test @FixFor("DBZ-1923") public void shouldDetectPurgedHistory() throws Exception { final int RECORDS_PER_TABLE = 5; final int TABLES = 2; final int ID_START = 10; final int ID_RESTART = 100; final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .with(SqlServerConnectorConfig.DATABASE_HISTORY, PurgableFileDatabaseHistory.class) .build(); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = ID_START + i; connection.execute("INSERT INTO tablea VALUES(" + id + ", 'a')"); connection.execute("INSERT INTO tableb VALUES(" + id + ", 'b')"); } Awaitility.await().atMost(30, TimeUnit.SECONDS).pollInterval(100, TimeUnit.MILLISECONDS).until(() -> { Testing.debug("Waiting for initial changes to be propagated to CDC structures"); return connection.getMaxLsn().isAvailable(); }); start(SqlServerConnector.class, config); assertConnectorIsRunning(); List<SourceRecord> records = consumeRecordsByTopic(1 + RECORDS_PER_TABLE * TABLES).allRecordsInOrder(); records = records.subList(1, records.size()); for (Iterator<SourceRecord> it = records.iterator(); it.hasNext();) { SourceRecord record = it.next(); assertThat(record.sourceOffset().get("snapshot")).as("Snapshot phase").isEqualTo(true); if (it.hasNext()) { assertThat(record.sourceOffset().get("snapshot_completed")).as("Snapshot in progress").isEqualTo(false); } else { assertThat(record.sourceOffset().get("snapshot_completed")).as("Snapshot completed").isEqualTo(true); } } stopConnector(); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = ID_RESTART + i; connection.execute("INSERT INTO tablea VALUES(" + id + ", 'a')"); connection.execute("INSERT INTO tableb VALUES(" + id + ", 'b')"); } Testing.Files.delete(TestHelper.DB_HISTORY_PATH); final LogInterceptor logInterceptor = new LogInterceptor(); start(SqlServerConnector.class, config); assertConnectorNotRunning(); assertThat(logInterceptor.containsStacktraceElement( "The db history topic or its content is fully or partially missing. Please check database history topic configuration and re-execute the snapshot.")) .isTrue(); } @Test @FixFor("DBZ-1988") public void shouldHonorSourceTimestampMode() throws InterruptedException, SQLException { connection.execute("CREATE TABLE source_timestamp_mode (id int, name varchar(30) primary key(id))"); TestHelper.enableTableCdc(connection, "source_timestamp_mode"); final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.SCHEMA_ONLY) .with(SqlServerConnectorConfig.TABLE_WHITELIST, "dbo.source_timestamp_mode") .with(SqlServerConnectorConfig.SOURCE_TIMESTAMP_MODE, "processing") .build(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); waitForSnapshotToBeCompleted("sql_server", "server1"); connection.execute("INSERT INTO source_timestamp_mode VALUES(1, 'abc')"); SourceRecords records = consumeRecordsByTopic(1); List<SourceRecord> recordsForTopic = records.recordsForTopic("server1.dbo.source_timestamp_mode"); SourceRecord record = recordsForTopic.get(0); long eventTs = (long) ((Struct) record.value()).get("ts_ms"); long sourceTs = (long) ((Struct) ((Struct) record.value()).get("source")).get("ts_ms"); // it's not exactly the same as ts_ms, but close enough; assertThat(eventTs - sourceTs).isLessThan(100); stopConnector(); } @Test @FixFor("DBZ-1312") public void useShortTableNamesForColumnMapper() throws Exception { final int RECORDS_PER_TABLE = 5; final int TABLES = 2; final int ID_START = 10; final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .with("column.mask.with.4.chars", "dbo.tablea.cola") .build(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); // Wait for snapshot completion consumeRecordsByTopic(1); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = ID_START + i; connection.execute( "INSERT INTO tablea VALUES(" + id + ", 'a')"); connection.execute( "INSERT INTO tableb VALUES(" + id + ", 'b')"); } final SourceRecords records = consumeRecordsByTopic(RECORDS_PER_TABLE * TABLES); final List<SourceRecord> tableA = records.recordsForTopic("server1.dbo.tablea"); final List<SourceRecord> tableB = records.recordsForTopic("server1.dbo.tableb"); Assertions.assertThat(tableA).hasSize(RECORDS_PER_TABLE); Assertions.assertThat(tableB).hasSize(RECORDS_PER_TABLE); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final SourceRecord recordA = tableA.get(i); final SourceRecord recordB = tableB.get(i); final List<SchemaAndValueField> expectedRowB = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, i + ID_START), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "b")); final Struct valueA = (Struct) recordA.value(); Assertions.assertThat(valueA.getStruct("after").getString("cola")).isEqualTo("****"); final Struct valueB = (Struct) recordB.value(); assertRecord((Struct) valueB.get("after"), expectedRowB); assertNull(valueB.get("before")); } stopConnector(); } @Test @FixFor("DBZ-1312") public void useLongTableNamesForColumnMapper() throws Exception { final int RECORDS_PER_TABLE = 5; final int TABLES = 2; final int ID_START = 10; final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .with("column.mask.with.4.chars", "testDB.dbo.tablea.cola") .build(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); // Wait for snapshot completion consumeRecordsByTopic(1); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = ID_START + i; connection.execute( "INSERT INTO tablea VALUES(" + id + ", 'a')"); connection.execute( "INSERT INTO tableb VALUES(" + id + ", 'b')"); } final SourceRecords records = consumeRecordsByTopic(RECORDS_PER_TABLE * TABLES); final List<SourceRecord> tableA = records.recordsForTopic("server1.dbo.tablea"); final List<SourceRecord> tableB = records.recordsForTopic("server1.dbo.tableb"); Assertions.assertThat(tableA).hasSize(RECORDS_PER_TABLE); Assertions.assertThat(tableB).hasSize(RECORDS_PER_TABLE); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final SourceRecord recordA = tableA.get(i); final SourceRecord recordB = tableB.get(i); final List<SchemaAndValueField> expectedRowB = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, i + ID_START), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "b")); final Struct valueA = (Struct) recordA.value(); Assertions.assertThat(valueA.getStruct("after").getString("cola")).isEqualTo("****"); final Struct valueB = (Struct) recordB.value(); assertRecord((Struct) valueB.get("after"), expectedRowB); assertNull(valueB.get("before")); } stopConnector(); } @Test @FixFor("DBZ-1312") public void useLongTableNamesForKeyMapper() throws Exception { final int RECORDS_PER_TABLE = 5; final int TABLES = 2; final int ID_START = 10; final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .with(SqlServerConnectorConfig.MSG_KEY_COLUMNS, "testDB.dbo.tablea:cola") .build(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); // Wait for snapshot completion consumeRecordsByTopic(1); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = ID_START + i; connection.execute( "INSERT INTO tablea VALUES(" + id + ", 'a')"); connection.execute( "INSERT INTO tableb VALUES(" + id + ", 'b')"); } final SourceRecords records = consumeRecordsByTopic(RECORDS_PER_TABLE * TABLES); final List<SourceRecord> tableA = records.recordsForTopic("server1.dbo.tablea"); final List<SourceRecord> tableB = records.recordsForTopic("server1.dbo.tableb"); Assertions.assertThat(tableA).hasSize(RECORDS_PER_TABLE); Assertions.assertThat(tableB).hasSize(RECORDS_PER_TABLE); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final SourceRecord recordA = tableA.get(i); final SourceRecord recordB = tableB.get(i); final List<SchemaAndValueField> expectedRowB = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, i + ID_START), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "b")); final Struct keyA = (Struct) recordA.key(); Assertions.assertThat(keyA.getString("cola")).isEqualTo("a"); final Struct valueB = (Struct) recordB.value(); assertRecord((Struct) valueB.get("after"), expectedRowB); assertNull(valueB.get("before")); } stopConnector(); } @Test @FixFor("DBZ-1312") public void useShortTableNamesForKeyMapper() throws Exception { final int RECORDS_PER_TABLE = 5; final int TABLES = 2; final int ID_START = 10; final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.INITIAL) .with(SqlServerConnectorConfig.MSG_KEY_COLUMNS, "dbo.tablea:cola") .build(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); // Wait for snapshot completion consumeRecordsByTopic(1); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final int id = ID_START + i; connection.execute( "INSERT INTO tablea VALUES(" + id + ", 'a')"); connection.execute( "INSERT INTO tableb VALUES(" + id + ", 'b')"); } final SourceRecords records = consumeRecordsByTopic(RECORDS_PER_TABLE * TABLES); final List<SourceRecord> tableA = records.recordsForTopic("server1.dbo.tablea"); final List<SourceRecord> tableB = records.recordsForTopic("server1.dbo.tableb"); Assertions.assertThat(tableA).hasSize(RECORDS_PER_TABLE); Assertions.assertThat(tableB).hasSize(RECORDS_PER_TABLE); for (int i = 0; i < RECORDS_PER_TABLE; i++) { final SourceRecord recordA = tableA.get(i); final SourceRecord recordB = tableB.get(i); final List<SchemaAndValueField> expectedRowB = Arrays.asList( new SchemaAndValueField("id", Schema.INT32_SCHEMA, i + ID_START), new SchemaAndValueField("colb", Schema.OPTIONAL_STRING_SCHEMA, "b")); final Struct keyA = (Struct) recordA.key(); Assertions.assertThat(keyA.getString("cola")).isEqualTo("a"); final Struct valueB = (Struct) recordB.value(); assertRecord((Struct) valueB.get("after"), expectedRowB); assertNull(valueB.get("before")); } stopConnector(); } @Test @FixFor({ "DBZ-1916", "DBZ-1830" }) public void shouldPropagateSourceTypeByDatatype() throws Exception { connection.execute("CREATE TABLE dt_table (id int, c1 int, c2 int, c3a numeric(5,2), c3b varchar(128), f1 float(10), f2 decimal(8,4) primary key(id))"); TestHelper.enableTableCdc(connection, "dt_table"); final Configuration config = TestHelper.defaultConfig() .with(SqlServerConnectorConfig.SNAPSHOT_MODE, SnapshotMode.SCHEMA_ONLY) .with(SqlServerConnectorConfig.TABLE_WHITELIST, "dbo.dt_table") .with("datatype.propagate.source.type", ".+\\.NUMERIC,.+\\.VARCHAR,.+\\.REAL,.+\\.DECIMAL") .build(); start(SqlServerConnector.class, config); assertConnectorIsRunning(); waitForSnapshotToBeCompleted("sql_server", "server1"); connection.execute("INSERT INTO dt_table (id,c1,c2,c3a,c3b,f1,f2) values (1, 123, 456, 789.01, 'test', 1.228, 234.56)"); SourceRecords records = consumeRecordsByTopic(1); List<SourceRecord> recordsForTopic = records.recordsForTopic("server1.dbo.dt_table"); final SourceRecord record = recordsForTopic.get(0); final Field before = record.valueSchema().field("before"); assertThat(before.schema().field("id").schema().parameters()).isNull(); assertThat(before.schema().field("c1").schema().parameters()).isNull(); assertThat(before.schema().field("c2").schema().parameters()).isNull(); assertThat(before.schema().field("c3a").schema().parameters()).includes( entry(TYPE_NAME_PARAMETER_KEY, "NUMERIC"), entry(TYPE_LENGTH_PARAMETER_KEY, "5"), entry(TYPE_SCALE_PARAMETER_KEY, "2")); assertThat(before.schema().field("c3b").schema().parameters()).includes( entry(TYPE_NAME_PARAMETER_KEY, "VARCHAR"), entry(TYPE_LENGTH_PARAMETER_KEY, "128")); assertThat(before.schema().field("f2").schema().parameters()).includes( entry(TYPE_NAME_PARAMETER_KEY, "DECIMAL"), entry(TYPE_LENGTH_PARAMETER_KEY, "8"), entry(TYPE_SCALE_PARAMETER_KEY, "4")); assertThat(before.schema().field("f1").schema().parameters()).includes( entry(TYPE_NAME_PARAMETER_KEY, "REAL"), entry(TYPE_LENGTH_PARAMETER_KEY, "24")); stopConnector(); } private void assertRecord(Struct record, List<SchemaAndValueField> expected) { expected.forEach(schemaAndValueField -> schemaAndValueField.assertFor(record)); } public static class PurgableFileDatabaseHistory implements DatabaseHistory { final DatabaseHistory delegate = new FileDatabaseHistory(); @Override public boolean exists() { try { return storageExists() && java.nio.file.Files.size(TestHelper.DB_HISTORY_PATH) > 0; } catch (IOException e) { throw new DatabaseHistoryException("File should exist"); } } @Override public void configure(Configuration config, HistoryRecordComparator comparator, DatabaseHistoryListener listener, boolean useCatalogBeforeSchema) { delegate.configure(config, comparator, listener, useCatalogBeforeSchema); } @Override public void start() { delegate.start(); } @Override public void record(Map<String, ?> source, Map<String, ?> position, String databaseName, String ddl) throws DatabaseHistoryException { delegate.record(source, position, databaseName, ddl); } @Override public void record(Map<String, ?> source, Map<String, ?> position, String databaseName, String schemaName, String ddl, TableChanges changes) throws DatabaseHistoryException { delegate.record(source, position, databaseName, schemaName, ddl, changes); } @Override public void recover(Map<String, ?> source, Map<String, ?> position, Tables schema, DdlParser ddlParser) { delegate.recover(source, position, schema, ddlParser); } @Override public void stop() { delegate.stop(); } @Override public boolean storageExists() { return delegate.storageExists(); } @Override public void initializeStorage() { delegate.initializeStorage(); } } }
//$HeadURL$ package org.deegree.services.wms; import static org.deegree.commons.utils.CollectionUtils.AND; import static org.deegree.commons.utils.CollectionUtils.addAllUncontained; import static org.deegree.commons.utils.CollectionUtils.map; import static org.deegree.commons.utils.CollectionUtils.reduce; import static org.deegree.commons.utils.MapUtils.DEFAULT_PIXEL_SIZE; import static org.deegree.rendering.r2d.RenderHelper.calcScaleWMS130; import static org.deegree.rendering.r2d.context.Java2DHelper.applyHints; import static org.deegree.services.wms.model.layers.Layer.render; import static org.deegree.style.utils.ImageUtils.postprocessPng8bit; import static org.slf4j.LoggerFactory.getLogger; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.xml.namespace.QName; import org.deegree.commons.utils.CollectionUtils; import org.deegree.commons.utils.CollectionUtils.Mapper; import org.deegree.commons.utils.DoublePair; import org.deegree.commons.utils.Pair; import org.deegree.feature.Feature; import org.deegree.feature.FeatureCollection; import org.deegree.feature.Features; import org.deegree.feature.GenericFeatureCollection; import org.deegree.feature.persistence.FeatureStore; import org.deegree.feature.persistence.FeatureStoreException; import org.deegree.feature.persistence.query.Query; import org.deegree.feature.stream.FeatureInputStream; import org.deegree.feature.stream.ThreadedFeatureInputStream; import org.deegree.feature.xpath.TypedObjectNodeXPathEvaluator; import org.deegree.filter.FilterEvaluationException; import org.deegree.filter.XPathEvaluator; import org.deegree.protocol.wms.WMSException.InvalidDimensionValue; import org.deegree.protocol.wms.WMSException.MissingDimensionValue; import org.deegree.protocol.wms.filter.ScaleFunction; import org.deegree.rendering.r2d.Java2DRenderer; import org.deegree.rendering.r2d.Java2DTextRenderer; import org.deegree.services.wms.controller.ops.GetFeatureInfo; import org.deegree.services.wms.controller.ops.GetMap; import org.deegree.services.wms.model.layers.FeatureLayer; import org.deegree.services.wms.model.layers.Layer; import org.deegree.style.se.unevaluated.Style; import org.slf4j.Logger; class OldStyleMapService { private static final Logger LOG = getLogger( OldStyleMapService.class ); private MapService service; OldStyleMapService( MapService service ) { this.service = service; } /** * @param gm * @return a rendered image, containing the requested maps * @throws InvalidDimensionValue * @throws MissingDimensionValue */ Pair<BufferedImage, LinkedList<String>> getMapImage( GetMap gm ) throws MissingDimensionValue, InvalidDimensionValue { LinkedList<String> warnings = new LinkedList<String>(); ScaleFunction.getCurrentScaleValue().set( gm.getScale() ); BufferedImage img = MapService.prepareImage( gm ); Graphics2D g = img.createGraphics(); paintMap( g, gm, warnings ); g.dispose(); // 8 bit png color map support copied from deegree 2, to be optimized if ( gm.getFormat().equals( "image/png; mode=8bit" ) || gm.getFormat().equals( "image/png; subtype=8bit" ) || gm.getFormat().equals( "image/gif" ) ) { img = postprocessPng8bit( img ); } ScaleFunction.getCurrentScaleValue().remove(); return new Pair<BufferedImage, LinkedList<String>>( img, warnings ); } /** * Paints the map on a graphics object. * * @param g * @param gm * @param warnings * @throws InvalidDimensionValue * @throws MissingDimensionValue */ private void paintMap( Graphics2D g, GetMap gm, LinkedList<String> warnings ) throws MissingDimensionValue, InvalidDimensionValue { Iterator<Layer> layers = gm.getLayers().iterator(); Iterator<Style> styles = gm.getStyles().iterator(); if ( reduce( true, map( gm.getLayers(), CollectionUtils.<Layer> getInstanceofMapper( FeatureLayer.class ) ), AND ) ) { LinkedList<FeatureLayer> fls = new LinkedList<FeatureLayer>(); Map<FeatureStore, LinkedList<Query>> queries = new HashMap<FeatureStore, LinkedList<Query>>(); HashMap<QName, FeatureLayer> ftToLayer = new HashMap<QName, FeatureLayer>(); HashMap<QName, Style> ftToStyle = new HashMap<QName, Style>(); double scale = gm.getScale(); if ( reduce( true, map( gm.getLayers(), getFeatureLayerCollector( fls ) ), AND ) ) { while ( layers.hasNext() ) { Layer l = layers.next(); Style s = styles.next(); s = s.filter( scale ); DoublePair scales = l.getScaleHint(); LOG.debug( "Scale settings are: {}, current scale is {}.", scales, scale ); if ( scales.first > scale || scales.second < scale || ( !s.isDefault() && s.getRules().isEmpty() ) ) { LOG.debug( "Not showing layer '{}' because of its scale constraint.", l.getName() == null ? l.getTitle() : l.getName() ); continue; } LinkedList<String> otherWarns = collectFeatureQueries( queries, (FeatureLayer) l, s, gm, ftToLayer, ftToStyle ); if ( otherWarns == null ) { queries.clear(); break; } warnings.addAll( otherWarns ); } } if ( queries.size() == 1 ) { handleCollectedQueries( queries, ftToLayer, ftToStyle, gm, g ); return; } if ( queries.isEmpty() ) { LOG.debug( "No queries found when collecting, probably due to scale constraints in the layers/styles." ); return; } LOG.debug( "Not using collected queries." ); layers = gm.getLayers().iterator(); styles = gm.getStyles().iterator(); } while ( layers.hasNext() ) { Layer l = layers.next(); Style s = styles.next(); applyHints( l.getName(), g, service.layerOptions, service.defaultLayerOptions ); warnings.addAll( paintLayer( l, s, g, gm ) ); } } // must ensure that subtree consists of feature layers only // returns null if not all styles contain distinct feature type names private LinkedList<String> collectFeatureQueries( Map<FeatureStore, LinkedList<Query>> queries, FeatureLayer l, Style style, GetMap gm, HashMap<QName, FeatureLayer> ftToLayer, HashMap<QName, Style> ftToStyle ) throws MissingDimensionValue, InvalidDimensionValue { if ( !l.getClass().equals( FeatureLayer.class ) ) { return null; } LinkedList<String> warns = new LinkedList<String>(); LinkedList<Query> list = queries.get( l.getDataStore() ); if ( list == null ) { list = new LinkedList<Query>(); queries.put( l.getDataStore(), list ); } warns.addAll( l.collectQueries( style, gm, list ) ); QName name = style == null ? null : style.getFeatureType(); if ( name == null || ftToLayer.containsKey( name ) ) { return null; } ftToLayer.put( name, l ); ftToStyle.put( name, style ); for ( Layer child : l.getChildren() ) { LinkedList<String> otherWarns = collectFeatureQueries( queries, (FeatureLayer) child, service.registry.get( child.getInternalName(), null ), gm, ftToLayer, ftToStyle ); if ( otherWarns == null ) { return null; } warns.addAll( otherWarns ); } return warns; } private void handleCollectedQueries( Map<FeatureStore, LinkedList<Query>> queries, HashMap<QName, FeatureLayer> ftToLayer, HashMap<QName, Style> ftToStyle, GetMap gm, Graphics2D g ) { LOG.debug( "Using collected queries for better performance." ); Java2DRenderer renderer = new Java2DRenderer( g, gm.getWidth(), gm.getHeight(), gm.getBoundingBox(), gm.getPixelSize() ); Java2DTextRenderer textRenderer = new Java2DTextRenderer( renderer ); // TODO XPathEvaluator<?> evaluator = new TypedObjectNodeXPathEvaluator(); Collection<LinkedList<Query>> qs = queries.values(); FeatureInputStream rs = null; try { FeatureStore store = queries.keySet().iterator().next(); LinkedList<Query> queriesList = qs.iterator().next(); if ( !queriesList.isEmpty() ) { rs = store.query( queriesList.toArray( new Query[queriesList.size()] ) ); // TODO Should this always be done on this level? What about min and maxFill values? rs = new ThreadedFeatureInputStream( rs, 100, 20 ); for ( Feature f : rs ) { QName name = f.getType().getName(); FeatureLayer l = ftToLayer.get( name ); applyHints( l.getName(), g, service.layerOptions, service.defaultLayerOptions ); render( f, (XPathEvaluator<Feature>) evaluator, ftToStyle.get( name ), renderer, textRenderer, gm.getScale(), gm.getResolution() ); } } else { LOG.warn( "No queries were found for the requested layers." ); } } catch ( FilterEvaluationException e ) { LOG.error( "A filter could not be evaluated. The error was '{}'.", e.getLocalizedMessage() ); LOG.trace( "Stack trace:", e ); } catch ( FeatureStoreException e ) { LOG.error( "Data could not be fetched from the feature store. The error was '{}'.", e.getLocalizedMessage() ); LOG.trace( "Stack trace:", e ); } finally { if ( rs != null ) { rs.close(); } } } private static Mapper<Boolean, Layer> getFeatureLayerCollector( final LinkedList<FeatureLayer> list ) { return new Mapper<Boolean, Layer>() { @Override public Boolean apply( Layer u ) { return collectFeatureLayers( u, list ); } }; } /** * @param l * @param list * @return true, if all sub layers were feature layers and its style had a distinct feature type name */ static boolean collectFeatureLayers( Layer l, final LinkedList<FeatureLayer> list ) { if ( l instanceof FeatureLayer ) { list.add( (FeatureLayer) l ); return reduce( true, map( l.getChildren(), getFeatureLayerCollector( list ) ), AND ); } return false; } protected LinkedList<String> paintLayer( Layer l, Style s, Graphics2D g, GetMap gm ) throws MissingDimensionValue, InvalidDimensionValue { LinkedList<String> warnings = new LinkedList<String>(); double scale = gm.getScale(); DoublePair scales = l.getScaleHint(); LOG.debug( "Scale settings are: {}, current scale is {}.", scales, scale ); if ( scales.first > scale || scales.second < scale ) { LOG.debug( "Not showing layer '{}' because of its scale constraint.", l.getName() == null ? l.getTitle() : l.getName() ); return warnings; } warnings.addAll( l.paintMap( g, gm, s ) ); for ( Layer child : l.getChildren() ) { warnings.addAll( paintLayer( child, service.registry.get( child.getInternalName(), null ), g, gm ) ); } return warnings; } /** * @param fi * @return a collection of feature values for the selected area, and warning headers * @throws InvalidDimensionValue * @throws MissingDimensionValue */ Pair<FeatureCollection, LinkedList<String>> getFeatures( GetFeatureInfo fi ) throws MissingDimensionValue, InvalidDimensionValue { List<Feature> list = new LinkedList<Feature>(); LinkedList<String> warnings = new LinkedList<String>(); Iterator<Style> styles = fi.getStyles().iterator(); double scale = calcScaleWMS130( fi.getWidth(), fi.getHeight(), fi.getEnvelope(), fi.getCoordinateSystem(), DEFAULT_PIXEL_SIZE ); for ( Layer layer : fi.getQueryLayers() ) { DoublePair scales = layer.getScaleHint(); LOG.debug( "Scale settings are: {}, current scale is {}.", scales, scale ); if ( scales.first > scale || scales.second < scale ) { LOG.debug( "Not showing layer '{}' because of its scale constraint.", layer.getName() == null ? layer.getTitle() : layer.getName() ); continue; } warnings.addAll( getFeatures( list, layer, fi, styles.next() ) ); } list = Features.clearDuplicates( list ); if ( list.size() > fi.getFeatureCount() ) { list = list.subList( 0, fi.getFeatureCount() ); } GenericFeatureCollection col = new GenericFeatureCollection(); col.addAll( list ); return new Pair<FeatureCollection, LinkedList<String>>( col, warnings ); } private LinkedList<String> getFeatures( Collection<Feature> feats, Layer l, GetFeatureInfo fi, Style s ) throws MissingDimensionValue, InvalidDimensionValue { LinkedList<String> warnings = new LinkedList<String>(); if ( l.isQueryable() ) { Pair<FeatureCollection, LinkedList<String>> pair = l.getFeatures( fi, s ); if ( pair != null ) { if ( pair.first != null ) { addAllUncontained( feats, pair.first ); } warnings.addAll( pair.second ); } } double scale = calcScaleWMS130( fi.getWidth(), fi.getHeight(), fi.getEnvelope(), fi.getCoordinateSystem(), DEFAULT_PIXEL_SIZE ); for ( Layer c : l.getChildren() ) { DoublePair scales = c.getScaleHint(); LOG.debug( "Scale settings are: {}, current scale is {}.", scales, scale ); if ( scales.first > scale || scales.second < scale ) { LOG.debug( "Not showing layer '{}' because of its scale constraint.", c.getName() == null ? c.getTitle() : c.getName() ); continue; } if ( c.getName() != null ) { s = service.registry.get( c.getName(), null ); } warnings.addAll( getFeatures( feats, c, fi, s ) ); } return warnings; } }
package uk.gov.nationalarchives.droid.profile; import java.io.File; import java.io.IOException; import java.net.URI; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Future; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.anyInt; import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import org.apache.commons.io.FileUtils; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import uk.gov.nationalarchives.droid.core.interfaces.config.RuntimeConfig; import uk.gov.nationalarchives.droid.core.interfaces.signature.SignatureFileInfo; import uk.gov.nationalarchives.droid.core.interfaces.signature.SignatureType; import uk.gov.nationalarchives.droid.results.handlers.ProgressObserver; /** * @author rflitcroft * */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath*:META-INF/spring-profile.xml"}) public class ProfileManagerIntegrationTest { private SignatureFileInfo binarySignatureFileInfo; private SignatureFileInfo containerSignatureFileInfo; @Autowired private ProfileManager profileManager; @BeforeClass public static void setupFiles() throws IOException { RuntimeConfig.configureRuntimeEnvironment(); new File("integration-test-files").mkdir(); new File("integration-test-files/file1").createNewFile(); } @AfterClass public static void tearDown() throws IOException { FileUtils.forceDelete(new File("integration-test-files")); } private boolean isLinux() { return System.getProperty("os.name").equals("Linux"); } @Before public void setup() { binarySignatureFileInfo = new SignatureFileInfo(26, false, SignatureType.BINARY); binarySignatureFileInfo.setFile(new File("test_sig_files/DROID_SignatureFile_V26.xml")); containerSignatureFileInfo = new SignatureFileInfo(26, false, SignatureType.CONTAINER); containerSignatureFileInfo.setFile(new File("test_sig_files/container-signature.xml")); } @Test public void testStartProfileSpecPersistsAJobForEachFileResourceNode() throws Exception { try { FileUtils.forceDelete(new File("profiles/integration-test")); } catch (IOException e) { } File testFile = new File("test_sig_files/sample.pdf"); FileProfileResource fileResource = new FileProfileResource(testFile); assertNotNull(profileManager); ProfileSpec profileSpec = new ProfileSpec(); profileSpec.addResource(fileResource); ProfileResultObserver myObserver = mock(ProfileResultObserver.class); Map<SignatureType, SignatureFileInfo> signatureFiles = new HashMap<SignatureType, SignatureFileInfo>(); signatureFiles.put(SignatureType.BINARY, binarySignatureFileInfo); signatureFiles.put(SignatureType.CONTAINER, containerSignatureFileInfo); ProfileInstance profile = profileManager.createProfile(signatureFiles); profileManager.updateProfileSpec(profile.getUuid(), profileSpec); profileManager.setResultsObserver(profile.getUuid(), myObserver); Collection<ProfileResourceNode> rootNodes = profileManager.findRootNodes(profile.getUuid()); assertEquals(1, rootNodes.size()); assertEquals(testFile.toURI(), rootNodes.iterator().next().getUri()); ProgressObserver progressObserver = mock(ProgressObserver.class); profileManager.setProgressObserver(profile.getUuid(), progressObserver); profile.changeState(ProfileState.VIRGIN); Future<?> submission = profileManager.start(profile.getUuid()); submission.get(); // Assert we got our result ArgumentCaptor<ProfileResourceNode> nodeCaptor = ArgumentCaptor.forClass(ProfileResourceNode.class); verify(myObserver).onResult(nodeCaptor.capture()); URI capturedUri = nodeCaptor.getValue().getUri(); assertEquals(testFile.toURI(), capturedUri); // Now assert that file/1 is in the database List<ProfileResourceNode> nodes = profileManager.findProfileResourceNodeAndImmediateChildren( profile.getUuid(), null); assertEquals(1, nodes.size()); ProfileResourceNode node = nodes.get(0); assertEquals(testFile.toURI(), node.getUri()); // assertEquals(JobStatus.COMPLETE, node.getJob().getStatus()); assertEquals(testFile.length(), node.getMetaData().getSize().longValue()); assertEquals(new Date(testFile.lastModified()), node.getMetaData().getLastModifiedDate()); // check the progress listener was invoked properly. verify(progressObserver, times(1)).onProgress(0); //verify(progressObserver).onProgress(100); } @Test public void testStartProfileSpecPersistsJobsForEachFileInANonRecursiveDirResourceNode() throws Exception { try { FileUtils.forceDelete(new File("profiles/integration-test2")); } catch (IOException e) { } File testFile = new File("test_sig_files"); int folderSize = testFile.listFiles().length; // Test affected because hard coded folder may be in version control // If in older versions of subversion .svn will exist. This is the most // pragmatic check to ensure this test works. Hard coded folder should // only ever be eight files or nine if including .svn assertTrue((folderSize == 8 || folderSize == 9)); final int EXPECTED_RESOURCES = folderSize; final int CHECK_VALUE = 8; final int PROGRESS_CHECK = 100; FileProfileResource fileResource = new DirectoryProfileResource(testFile, false); assertNotNull(profileManager); ProfileSpec profileSpec = new ProfileSpec(); profileSpec.addResource(fileResource); ProfileResultObserver myObserver = mock(ProfileResultObserver.class); Map<SignatureType, SignatureFileInfo> signatureFiles = new HashMap<SignatureType, SignatureFileInfo>(); signatureFiles.put(SignatureType.BINARY, binarySignatureFileInfo); signatureFiles.put(SignatureType.CONTAINER, containerSignatureFileInfo); ProfileInstance profile = profileManager.createProfile(signatureFiles); profile.changeState(ProfileState.VIRGIN); profile.setProcessArchiveFiles(false); String profileId = profile.getUuid(); profileManager.updateProfileSpec(profileId, profileSpec); profileManager.setResultsObserver(profileId, myObserver); ProgressObserver progressObserver = mock(ProgressObserver.class); profileManager.setProgressObserver(profileId, progressObserver); Future<?> submission = profileManager.start(profileId); submission.get(); // Assert we got our result notifications ArgumentCaptor<ProfileResourceNode> nodeCaptor = ArgumentCaptor.forClass(ProfileResourceNode.class); List<ProfileResourceNode> capturedUris = nodeCaptor.getAllValues(); verify(myObserver, atLeast(CHECK_VALUE)).onResult(nodeCaptor.capture()); ProfileResourceNode testFileNode = capturedUris.get(0); Collections.sort(capturedUris, new Comparator<ProfileResourceNode>() { @Override public int compare(ProfileResourceNode o1, ProfileResourceNode o2) { return o1.getUri().compareTo(o2.getUri()); } }); // Now assert that file/1 is in the database List<ProfileResourceNode> nodes = profileManager.findProfileResourceNodeAndImmediateChildren( profile.getUuid(), testFileNode.getId()); // There are n expectedResources in node list assertEquals(EXPECTED_RESOURCES, nodes.size()); ProfileResourceNode samplePdf = null; File samplePdfFile = new File("test_sig_files/sample.pdf"); for (ProfileResourceNode childNode : nodes) { if (childNode.getUri().equals(samplePdfFile.toURI())) { samplePdf = childNode; break; } } assertEquals(samplePdfFile.toURI(), samplePdf.getUri()); assertEquals(samplePdfFile.length(), samplePdf.getMetaData().getSize().longValue()); assertEquals(new Date(samplePdfFile.lastModified()), samplePdf.getMetaData().getLastModifiedDate()); // check the progress listener was invoked properly. verify(progressObserver, atLeast(CHECK_VALUE)).onProgress(anyInt()); verify(progressObserver).onProgress(PROGRESS_CHECK); } }
package org.eclipse.birt.report.engine.data.dte; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.eclipse.birt.core.exception.BirtException; import org.eclipse.birt.data.engine.api.DataEngine; import org.eclipse.birt.data.engine.api.DataEngineContext; import org.eclipse.birt.data.engine.api.IBaseExpression; import org.eclipse.birt.data.engine.api.IBaseQueryDefinition; import org.eclipse.birt.data.engine.api.IConditionalExpression; import org.eclipse.birt.data.engine.api.IPreparedQuery; import org.eclipse.birt.data.engine.api.IQueryDefinition; import org.eclipse.birt.data.engine.api.IQueryResults; import org.eclipse.birt.data.engine.api.IResultIterator; import org.eclipse.birt.data.engine.api.IScriptExpression; import org.eclipse.birt.data.engine.api.ISubqueryDefinition; import org.eclipse.birt.data.engine.script.ScriptEvalUtil; import org.eclipse.birt.report.engine.adapter.ModelDteApiAdapter; import org.eclipse.birt.report.engine.api.EngineException; import org.eclipse.birt.report.engine.data.IDataEngine; import org.eclipse.birt.report.engine.data.IResultSet; import org.eclipse.birt.report.engine.executor.ExecutionContext; import org.eclipse.birt.report.engine.i18n.MessageConstants; import org.eclipse.birt.report.engine.ir.Report; import org.eclipse.birt.report.model.api.DataSetHandle; import org.eclipse.birt.report.model.api.DataSourceHandle; import org.eclipse.birt.report.model.api.ReportDesignHandle; import org.mozilla.javascript.JavaScriptException; import org.mozilla.javascript.Scriptable; public class DteDataEngine implements IDataEngine { /** * execution context */ protected ExecutionContext context; /** * data engine */ protected DataEngine engine; /** * Hashmap which map <code>ReportQuery</code> to * <code>PreparedQuery</code> */ protected HashMap queryMap = new HashMap( ); /** * the logger */ protected static Logger logger = Logger.getLogger( DteDataEngine.class .getName( ) ); /** * resultset stack */ protected LinkedList rsStack = new LinkedList( ); /** * creates data engine, by first look into the directory specified by * configuration variable odadriver, for oda configuration file. The oda * configuration file is at $odadriver/drivers/driverType/odaconfig.xml. * <p> * * If the config variable is not set, search configuration file at * ./drivers/driverType/odaconfig.xml. * * @param context */ public DteDataEngine( ExecutionContext context ) { this.context = context; try { DataEngineContext dteContext = DataEngineContext.newInstance( DataEngineContext.MODE_DIRECTPRESENT, context .getSharedScope( ), null ); engine = DataEngine.newDataEngine( dteContext ); } catch ( Exception ex ) { ex.printStackTrace( ); } } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.data.IDataEngine#prepare(org.eclipse.birt.report.engine.ir.Report) */ public void prepare( Report report ) { prepare( report, null ); } public void prepare( Report report, Map appContext ) { assert ( report != null ); // Handle data sources ReportDesignHandle handle = report.getReportDesign( ); List dataSourceList = handle.getAllDataSources( ); for ( int i = 0; i < dataSourceList.size( ); i++ ) { DataSourceHandle dataSource = (DataSourceHandle) dataSourceList .get( i ); try { engine.defineDataSource( ModelDteApiAdapter.getInstance( ) .createDataSourceDesign( dataSource ) ); } catch ( BirtException e ) { logger.log( Level.SEVERE, e.getMessage( ), e ); context.addException( dataSource, e ); } } // End of data source handling // Handle data sets List dataSetList = handle.getAllDataSets( ); for ( int i = 0; i < dataSetList.size( ); i++ ) { DataSetHandle dataset = (DataSetHandle) dataSetList.get( i ); try { engine.defineDataSet( ModelDteApiAdapter.getInstance( ) .createDataSetDesign( dataset ) ); } catch ( BirtException e ) { logger.log( Level.SEVERE, e.getMessage( ), e ); context.addException( dataset, e ); } } // End of data set handling // build report queries new ReportQueryBuilder( ).build( report, context ); // prepare report queries for ( int i = 0; i < report.getQueries( ).size( ); i++ ) { IQueryDefinition query = (IQueryDefinition) report.getQueries( ) .get( i ); try { IPreparedQuery preparedQuery = engine.prepare( query, appContext ); queryMap.put( query, preparedQuery ); } catch ( BirtException e ) { logger.log( Level.SEVERE, e.getMessage( ), e ); context.addException( e ); } } // end of prepare } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.data.IDataEngine#execute(org.eclipse.birt.model.elements.ReportItemDesign) */ public IResultSet execute( IBaseQueryDefinition query ) { if ( query == null ) return null; if ( query instanceof IQueryDefinition ) { Scriptable scope = context.getSharedScope( ); IPreparedQuery pQuery = (IPreparedQuery) queryMap.get( query ); assert ( pQuery != null ); if ( pQuery != null ) { try { IQueryResults queryResults = getParentQR( ); if ( queryResults == null ) { queryResults = pQuery.execute( scope ); } else { queryResults = pQuery.execute( queryResults, scope ); } IResultIterator ri = queryResults.getResultIterator( ); assert ri != null; DteResultSet dRS = new DteResultSet( queryResults, this, context ); rsStack.addLast( dRS ); return dRS; } catch ( BirtException e ) { logger.log( Level.SEVERE, e.getMessage( ), e ); context.addException( e ); return null; } } } else if ( query instanceof ISubqueryDefinition ) { // Extension Item may used to create the query stack, so we must do // error handling. if ( rsStack.isEmpty( ) ) { return null; } assert ( rsStack.getLast( ) instanceof DteResultSet ); try { IResultIterator ri = ( (DteResultSet) rsStack.getLast( ) ) .getResultIterator( ).getSecondaryIterator( ( (ISubqueryDefinition) query ).getName( ), context.getSharedScope( ) ); assert ri != null; DteResultSet dRS = new DteResultSet( ri, this ); rsStack.addLast( dRS ); return dRS; } catch ( BirtException e ) { logger.log( Level.SEVERE, e.getMessage( ), e ); context.addException( e ); return null; } } assert ( false ); return null; } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.data.IDataEngine#close() */ public void close( ) { assert ( rsStack.size( ) > 0 ); rsStack.removeLast( ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.data.IDataEngine#shutdown() */ public void shutdown( ) { assert ( rsStack.size( ) == 0 ); engine.shutdown( ); } /* * (non-Javadoc) * * @see org.eclipse.birt.report.engine.data.IDataEngine#evaluate(org.eclipse.birt.data.engine.api.IExpression) */ public Object evaluate( IBaseExpression expr ) { if ( expr == null ) { return null; } if ( !rsStack.isEmpty( ) ) // DtE handles evaluation { try { Object value = ( (DteResultSet) rsStack.getLast( ) ) .getResultIterator( ).getValue( expr ); if ( value != null ) { return context.jsToJava( value ); } return null; } catch ( BirtException e ) { logger.log( Level.SEVERE, e.getMessage( ), e ); context.addException( e ); return null; } catch ( JavaScriptException ee ) { logger.log( Level.SEVERE, ee.getMessage( ), ee ); context.addException( new EngineException( MessageConstants.INVALID_EXPRESSION_ERROR, expr, ee ) ); return null; } } // Rhino handles evaluation if ( expr instanceof IScriptExpression ) { return context.evaluate( ( (IScriptExpression) expr ).getText( ) ); } if ( expr instanceof IConditionalExpression ) { return evaluateCondExpr( (IConditionalExpression) expr ); } // unsupported expression type assert ( false ); return null; } protected IQueryResults getParentQR( ) { for ( int i = rsStack.size( ) - 1; i >= 0; i { DteResultSet rs = (DteResultSet) rsStack.get( i ); if ( rs.getQueryResults( ) != null ) { return rs.getQueryResults( ); } } return null; } /** * evaluate conditional expression. A conditional expression can have an * operator, one LHS expression, and up to two expressions on RHS, i.e., * * testExpr operator operand1 operand2 or testExpr between 1 20 * * Now only support comparison between the same data type * * @param expr * the conditional expression to be evaluated * @return a boolean value (as an Object) */ protected Object evaluateCondExpr( IConditionalExpression expr ) { if ( expr == null ) { EngineException e = new EngineException( "Failed to evaluate: null" );//$NON-NLS-1$ context.addException( e ); logger.log( Level.SEVERE, e.getMessage( ), e ); return new Boolean( false ); } int operator = expr.getOperator( ); IScriptExpression testExpr = expr.getExpression( ); IScriptExpression v1 = expr.getOperand1( ); IScriptExpression v2 = expr.getOperand2( ); if ( testExpr == null ) return new Boolean( false ); Object testExprValue = context.evaluate( testExpr.getText( ) ); if ( IConditionalExpression.OP_NONE == operator ) { return testExprValue; } Object vv1 = null; Object vv2 = null; if ( v1 != null ) { vv1 = context.evaluate( v1.getText( ) ); } if ( v2 != null ) { vv2 = context.evaluate( v2.getText( ) ); } try { return ScriptEvalUtil.evalConditionalExpr2( testExprValue, expr .getOperator( ), vv1, vv2 ); } catch ( Exception e ) { logger.log( Level.SEVERE, e.getMessage( ), e ); context.addException( new EngineException( MessageConstants.INVALID_EXPRESSION_ERROR, expr, e ) ); return new Boolean( false ); } } public DataEngine getDataEngine( ) { return engine; } }
package org.monarchinitiative.exomiser.core.analysis; import de.charite.compbio.jannovar.annotation.VariantEffect; import de.charite.compbio.jannovar.mendel.ModeOfInheritance; import de.charite.compbio.jannovar.pedigree.Pedigree; import htsjdk.variant.vcf.VCFHeader; import org.monarchinitiative.exomiser.core.analysis.util.*; import org.monarchinitiative.exomiser.core.filters.GeneFilter; import org.monarchinitiative.exomiser.core.filters.GeneFilterRunner; import org.monarchinitiative.exomiser.core.filters.VariantFilter; import org.monarchinitiative.exomiser.core.filters.VariantFilterRunner; import org.monarchinitiative.exomiser.core.genome.GenomeAnalysisService; import org.monarchinitiative.exomiser.core.genome.VcfFiles; import org.monarchinitiative.exomiser.core.model.Gene; import org.monarchinitiative.exomiser.core.model.RegulatoryFeature; import org.monarchinitiative.exomiser.core.model.TopologicalDomain; import org.monarchinitiative.exomiser.core.model.VariantEvaluation; import org.monarchinitiative.exomiser.core.prioritisers.Prioritiser; import org.monarchinitiative.exomiser.core.prioritisers.PriorityType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.nio.file.Path; import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Stream; import static java.util.stream.Collectors.toConcurrentMap; import static java.util.stream.Collectors.toList; /** * @author Jules Jacobsen <jules.jacobsen@sanger.ac.uk> */ abstract class AbstractAnalysisRunner implements AnalysisRunner { private static final Logger logger = LoggerFactory.getLogger(AbstractAnalysisRunner.class); //arguably this shouldn't even be exposed here... private final GenomeAnalysisService genomeAnalysisService; protected final VariantFilterRunner variantFilterRunner; private final GeneFilterRunner geneFilterRunner; public AbstractAnalysisRunner(GenomeAnalysisService genomeAnalysisService, VariantFilterRunner variantFilterRunner, GeneFilterRunner geneFilterRunner) { this.genomeAnalysisService = genomeAnalysisService; this.variantFilterRunner = variantFilterRunner; this.geneFilterRunner = geneFilterRunner; } @Override public AnalysisResults run(Analysis analysis) { logger.info("Starting analysis"); logger.info("Using genome assembly {}", analysis.getGenomeAssembly()); Path vcfPath = analysis.getVcfPath(); Path pedigreeFilePath = analysis.getPedPath(); logger.info("Setting up analysis for VCF and PED files: {}, {}", vcfPath, pedigreeFilePath); VCFHeader vcfHeader = VcfFiles.readVcfHeader(vcfPath); List<String> sampleNames = vcfHeader.getGenotypeSamples(); String probandSampleName = SampleNameChecker.getProbandSampleName(analysis.getProbandSampleName(), sampleNames); int probandSampleId = SampleNameChecker.getProbandSampleId(probandSampleName, sampleNames); Pedigree pedigree = new PedigreeFactory().createPedigreeForSampleData(pedigreeFilePath, sampleNames); ModeOfInheritance modeOfInheritance = analysis.getModeOfInheritance(); logger.info("Running analysis for proband {} (sample {} in VCF) from samples: {}", probandSampleName, probandSampleId + 1, sampleNames); Instant timeStart = Instant.now(); List<String> hpoIds = analysis.getHpoIds(); //soo many comments - this is a bad sign that this is too complicated. Map<String, Gene> allGenes = makeKnownGenes(); List<VariantEvaluation> variantEvaluations = new ArrayList<>(); // some kind of multi-map with ordered duplicate keys would allow for easy grouping of steps for running the groups together. List<List<AnalysisStep>> analysisStepGroups = analysis.getAnalysisStepsGroupedByFunction(); boolean variantsLoaded = false; for (List<AnalysisStep> analysisGroup : analysisStepGroups) { //this is admittedly pretty confusing code and I'm sorry. It's easiest to follow if you turn on debugging. //The analysis steps are run in groups of VARIANT_FILTER, GENE_ONLY_DEPENDENT or INHERITANCE_MODE_DEPENDENT AnalysisStep firstStep = analysisGroup.get(0); logger.debug("Running {} group: {}", firstStep.getType(), analysisGroup); if (firstStep.isVariantFilter() && !variantsLoaded) { //variants take up 99% of all the memory in an analysis - this scales approximately linearly with the sample size //so for whole genomes this is best run as a stream to filter out the unwanted variants with as many filters as possible in one go variantEvaluations = loadAndFilterVariants(vcfPath, allGenes, analysisGroup, analysis); //this is done here as there are GeneFilter steps which may require Variants in the genes, or the InheritanceModeDependent steps which definitely need them... assignVariantsToGenes(variantEvaluations, allGenes); variantsLoaded = true; } else { runSteps(analysisGroup, hpoIds, new ArrayList<>(allGenes.values()), pedigree, modeOfInheritance); } } //maybe only the non-variant dependent steps have been run in which case we need to load the variants although //the results might be a bit meaningless. //See issue #129 This is an excellent place to put the output of a gene phenotype score only run. //i.e. stream in the variants, annotate them (assign a gene symbol) then write out that variant with the calculated GENE_PHENO_SCORE (prioritiser scores). //this would fit well with a lot of people's pipelines where they only want the phenotype score as they are using VEP or ANNOVAR for variant analysis. if (!variantsLoaded) { try(Stream<VariantEvaluation> variantStream = loadVariants(vcfPath)) { variantEvaluations = variantStream.collect(toList()); } assignVariantsToGenes(variantEvaluations, allGenes); } logger.info("Scoring genes"); GeneScorer geneScorer = new RawScoreGeneScorer(probandSampleId, modeOfInheritance, pedigree); List<Gene> genes = geneScorer.scoreGenes(getGenesWithVariants(allGenes).collect(toList())); List<VariantEvaluation> variants = getFinalVariantList(variantEvaluations); logger.info("Analysed {} genes containing {} filtered variants", genes.size(), variants.size()); logger.info("Creating analysis results from VCF and PED files: {}, {}", vcfPath, pedigreeFilePath); AnalysisResults analysisResults = AnalysisResults.builder() .vcfPath(vcfPath) .pedPath(pedigreeFilePath) .vcfHeader(vcfHeader) .probandSampleName(probandSampleName) .sampleNames(sampleNames) .pedigree(pedigree) .genes(genes) .variantEvaluations(variants) .build(); Duration duration = Duration.between(timeStart, Instant.now()); long ms = duration.toMillis(); logger.info("Finished analysis in {}m {}s {}ms ({} ms)", (ms / 1000) / 60 % 60, ms / 1000 % 60, ms % 1000, ms); return analysisResults; } private List<VariantEvaluation> loadAndFilterVariants(Path vcfPath, Map<String, Gene> allGenes, List<AnalysisStep> analysisGroup, Analysis analysis) { GeneReassigner geneReassigner = createNonCodingVariantGeneReassigner(analysis, allGenes); List<VariantFilter> variantFilters = getVariantFilterSteps(analysisGroup); List<VariantEvaluation> filteredVariants; VariantLogger variantLogger = new VariantLogger(); try (Stream<VariantEvaluation> variantStream = loadVariants(vcfPath)) { filteredVariants = variantStream .peek(variantLogger.logLoadedAndPassedVariants()) .map(reassignNonCodingVariantToBestGeneInJannovarAnnotations(geneReassigner)) .map(reassignNonCodingVariantToBestGeneInTad(geneReassigner)) .filter(isAssociatedWithKnownGene(allGenes)) .filter(runVariantFilters(variantFilters)) .peek(variantLogger.countPassedVariant()) .collect(toList()); } variantLogger.logResults(); return filteredVariants; } private GeneReassigner createNonCodingVariantGeneReassigner(Analysis analysis, Map<String, Gene> allGenes) { ChromosomalRegionIndex<TopologicalDomain> tadIndex = genomeAnalysisService.getTopologicallyAssociatedDomainIndex(); PriorityType mainPriorityType = analysis.getMainPrioritiserType(); return new GeneReassigner(mainPriorityType, allGenes, tadIndex); } private List<VariantFilter> getVariantFilterSteps(List<AnalysisStep> analysisSteps) { logger.info("Filtering variants with:"); return analysisSteps.stream() .filter(AnalysisStep::isVariantFilter) .map(analysisStep -> { logger.info("{}", analysisStep); return (VariantFilter) analysisStep; }) .collect(toList()); } private Function<VariantEvaluation, VariantEvaluation> reassignNonCodingVariantToBestGeneInJannovarAnnotations(GeneReassigner geneReassigner) { return variantEvaluation -> { if (variantEvaluation.isNonCodingVariant()) { geneReassigner.reassignGeneToMostPhenotypicallySimilarGeneInAnnotations(variantEvaluation); } return variantEvaluation; }; } private Function<VariantEvaluation, VariantEvaluation> reassignNonCodingVariantToBestGeneInTad(GeneReassigner geneReassigner) { //todo: this won't function correctly if run before a prioritiser has been run return variantEvaluation -> { geneReassigner.reassignRegulatoryRegionVariantToMostPhenotypicallySimilarGeneInTad(variantEvaluation); return variantEvaluation; }; } /** * Defines the filtering behaviour of the runner when performing the initial load and filter of variants. Allows the * concrete runner to define whether a variant should pass or fail depending on the gene or status of the gene it is * assigned to. * * @param genes * @return */ abstract Predicate<VariantEvaluation> isAssociatedWithKnownGene(Map<String, Gene> genes); /** * Defines the filtering behaviour of the runner when performing the initial load and filter of variants. Allows the * concrete runner to define whether a variant should pass or fail when running the variant through the variant * filters defined in the variant filter group, or the initial group if there are more than one. * * @param variantFilters * @return */ abstract Predicate<VariantEvaluation> runVariantFilters(List<VariantFilter> variantFilters); private Stream<VariantEvaluation> loadVariants(Path vcfPath) { ChromosomalRegionIndex<RegulatoryFeature> regulatoryRegionIndex = genomeAnalysisService.getRegulatoryRegionIndex(); //WARNING!!! THIS IS NOT THREADSAFE DO NOT USE PARALLEL STREAMS return genomeAnalysisService.createVariantEvaluations(vcfPath) .map(setRegulatoryRegionVariantEffect(regulatoryRegionIndex)); } //Adds the missing REGULATORY_REGION_VARIANT effect to variants - this isn't in the Jannovar data set. //This ought to move into the variantFactory/variantDataService private Function<VariantEvaluation, VariantEvaluation> setRegulatoryRegionVariantEffect(ChromosomalRegionIndex<RegulatoryFeature> regulatoryRegionIndex) { return variantEvaluation -> { VariantEffect variantEffect = variantEvaluation.getVariantEffect(); //n.b this check here is important as ENSEMBLE can have regulatory regions overlapping with missense variants. if (isIntergenicOrUpstreamOfGene(variantEffect) && regulatoryRegionIndex.hasRegionContainingVariant(variantEvaluation)) { //the effect is the same for all regulatory regions, so for the sake of speed, just assign it here rather than look it up from the list variantEvaluation.setVariantEffect(VariantEffect.REGULATORY_REGION_VARIANT); } return variantEvaluation; }; } private boolean isIntergenicOrUpstreamOfGene(VariantEffect variantEffect) { return variantEffect == VariantEffect.INTERGENIC_VARIANT || variantEffect == VariantEffect.UPSTREAM_GENE_VARIANT; } private void assignVariantsToGenes(List<VariantEvaluation> variantEvaluations, Map<String, Gene> allGenes) { for (VariantEvaluation variantEvaluation : variantEvaluations) { Gene gene = allGenes.get(variantEvaluation.getGeneSymbol()); if (gene != null) { // It is possible that the gene could be null if no filters have been run and the variant isn't assigned // to a known gene (gene symbol is '.') gene.addVariant(variantEvaluation); } } } /** * @param allGenes * @return */ protected Stream<Gene> getGenesWithVariants(Map<String, Gene> allGenes) { return allGenes.values() .stream() .filter(Gene::hasVariants); } abstract List<VariantEvaluation> getFinalVariantList(List<VariantEvaluation> variants); /** * @return a map of genes indexed by gene symbol. */ private Map<String, Gene> makeKnownGenes() { return genomeAnalysisService.getKnownGenes() .parallelStream() .collect(toConcurrentMap(Gene::getGeneSymbol, Function.identity())); } //might this be a nascent class waiting to get out here? private void runSteps(List<AnalysisStep> analysisSteps, List<String> hpoIds, List<Gene> genes, Pedigree pedigree, ModeOfInheritance modeOfInheritance) { boolean inheritanceModesCalculated = false; for (AnalysisStep analysisStep : analysisSteps) { if (!inheritanceModesCalculated && analysisStep.isInheritanceModeDependent()) { analyseGeneCompatibilityWithInheritanceMode(genes, pedigree, modeOfInheritance); inheritanceModesCalculated = true; } runStep(analysisStep, hpoIds, genes); } } private void runStep(AnalysisStep analysisStep, List<String> hpoIds, List<Gene> genes) { if (analysisStep.isVariantFilter()) { VariantFilter filter = (VariantFilter) analysisStep; logger.info("Running VariantFilter: {}", filter); for (Gene gene : genes) { variantFilterRunner.run(filter, gene.getVariantEvaluations()); } return; } if (GeneFilter.class.isInstance(analysisStep)) { GeneFilter filter = (GeneFilter) analysisStep; logger.info("Running GeneFilter: {}", filter); geneFilterRunner.run(filter, genes); return; } if (Prioritiser.class.isInstance(analysisStep)) { Prioritiser prioritiser = (Prioritiser) analysisStep; logger.info("Running Prioritiser: {}", prioritiser); prioritiser.prioritizeGenes(hpoIds, genes); } } private void analyseGeneCompatibilityWithInheritanceMode(List<Gene> genes, Pedigree pedigree, ModeOfInheritance modeOfInheritance) { InheritanceModeAnalyser inheritanceModeAnalyser = new InheritanceModeAnalyser(modeOfInheritance, pedigree); logger.info("Checking compatibility with {} inheritance mode for genes which passed filters", modeOfInheritance); inheritanceModeAnalyser.analyseInheritanceModes(genes); //could add the OmimPrioritiser in here too - it requires the InheritanceModes in order to run correctly, as does the GeneScorer } /** * Utility class for logging numbers of processed and passed variants. */ private class VariantLogger { private AtomicInteger loaded = new AtomicInteger(); private AtomicInteger passed = new AtomicInteger(); private Consumer<VariantEvaluation> logLoadedAndPassedVariants() { return variantEvaluation -> { loaded.incrementAndGet(); if (loaded.get() % 100000 == 0) { logger.info("Loaded {} variants - {} passed variant filters...", loaded.get(), passed.get()); } }; } private Consumer<VariantEvaluation> countPassedVariant() { return variantEvaluation -> { if (variantEvaluation.passedFilters()) { passed.incrementAndGet(); } }; } void logResults() { logger.info("Loaded {} variants - {} passed variant filters", loaded.get(), passed.get()); } } }
package uk.ac.ebi.quickgo.geneproduct.controller; import uk.ac.ebi.quickgo.common.solr.TemporarySolrDataStore; import uk.ac.ebi.quickgo.geneproduct.GeneProductREST; import uk.ac.ebi.quickgo.geneproduct.common.GeneProductRepository; import uk.ac.ebi.quickgo.geneproduct.common.common.GeneProductDocMocker; import uk.ac.ebi.quickgo.geneproduct.common.document.GeneProductDocument; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.hasSize; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = {GeneProductREST.class}) @WebAppConfiguration public class GeneProductControllerIT { // temporary data store for solr's data, which is automatically cleaned on exit @ClassRule public static final TemporarySolrDataStore solrDataStore = new TemporarySolrDataStore(); private static final String RESOURCE_URL = "/QuickGO/services/geneproduct"; protected static final String COMMA = ","; public static final String NON_EXISTANT_ID = "Y0Y000"; public static final String INVALID_ID = "ZZZZ"; @Autowired private WebApplicationContext webApplicationContext; @Autowired private GeneProductRepository geneProductRepository; private MockMvc mockMvc; private String validId; private String validIdsCSV; private List<String> validIdList; @Before public void setup() { geneProductRepository.deleteAll(); mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build(); List<GeneProductDocument> basicDocs = createBasicDocs(); assertThat(basicDocs.size(), is(greaterThan(1))); validId = basicDocs.get(0).id; validIdsCSV = basicDocs.stream().map(doc -> doc.id).collect(Collectors.joining(",")); validIdList = Arrays.asList(validIdsCSV.split(COMMA)); geneProductRepository.save(basicDocs); } @Test public void canRetrieveOneGeneProductById() throws Exception { ResultActions response = mockMvc.perform(get(buildGeneProductURL(validId))); response.andDo(print()) .andExpect(jsonPath("$.results.*.id", hasSize(1))) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(status().isOk()); } @Test public void canRetrieveMultiGeneProductById() throws Exception { ResultActions result = mockMvc.perform(get(buildGeneProductURL(validIdsCSV))); result.andDo(print()) .andExpect(jsonPath("$.results.*.id", hasSize(3))) .andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(status().isOk()); int index = 0; for (String id : validIdList) { expectFields(result, id, "$.results[" + index++ + "]."); } } @Test public void finds400IfUrlIsEmpty() throws Exception { mockMvc.perform(get(RESOURCE_URL + "/")) .andDo(print()) .andExpect(status().isBadRequest()); } @Test public void finds400IfTermsIdIsEmpty() throws Exception { mockMvc.perform(get(buildGeneProductURL(""))) .andDo(print()) .andExpect(status().isBadRequest()); } @Test public void finds400IfIdIsInvalid() throws Exception { mockMvc.perform(get(buildGeneProductURL(INVALID_ID))) .andDo(print()) .andExpect(jsonPath("$.message", is("Provided ID: 'ZZZZ' is invalid"))) .andExpect(status().isBadRequest()); } @Test public void finds200IfNoResultsBecauseIdsDoNotExist() throws Exception { mockMvc.perform(get(buildGeneProductURL(NON_EXISTANT_ID))) .andDo(print()) .andExpect(status().isOk()); } private ResultActions expectFields(ResultActions result, String id, String path) throws Exception { return result .andDo(print()) .andExpect(jsonPath(path + "id").value(id)) .andExpect(jsonPath(path + "type").value("PROTEIN")) .andExpect(jsonPath(path + "taxonomy.id").value(35758)) .andExpect(jsonPath(path + "taxonomy.name").value("Streptomyces ghanaensis")) .andExpect(jsonPath(path + "symbol").value("Streptomyces ghanaensis - symbol")) .andExpect(jsonPath(path + "parentId").value("UniProtKB:OK0206")) .andExpect(jsonPath(path + "databaseSubset[0]").value("RRR")) .andExpect(jsonPath(path + "databaseSubset[1]").value("QQQ")) .andExpect(jsonPath(path + "isAnnotated").value(true)) .andExpect(jsonPath(path + "isIsoform").value(true)) .andExpect(jsonPath(path + "isCompleteProteome").value(true)) .andExpect(jsonPath(path + "name").value("moeA5")) .andExpect(jsonPath(path + "referenceProteome").value("AAAA")) .andExpect(jsonPath(path + "synonyms[0]").value("3SSW23")); } private String buildGeneProductURL(String id) { return RESOURCE_URL + "/" + id; } private List<GeneProductDocument> createBasicDocs() { return Arrays.asList( GeneProductDocMocker.createDocWithId("A0A000"), GeneProductDocMocker.createDocWithId("A0A001"), GeneProductDocMocker.createDocWithId("A0A002")); } }
package com.liuguangqiang.swipeback; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.RelativeLayout.LayoutParams; public class SwipeBackActivity extends AppCompatActivity implements SwipeBackLayout.SwipeBackListener { private static final SwipeBackLayout.DragEdge DEFAULT_DRAG_EDGE = SwipeBackLayout.DragEdge.LEFT; private SwipeBackLayout swipeBackLayout; private ImageView ivShadow; @Override public void setContentView(int layoutResID) { super.setContentView(getContainer()); View view = LayoutInflater.from(this).inflate(layoutResID, null); swipeBackLayout.addView(view); } private View getContainer() { RelativeLayout container = new RelativeLayout(this); swipeBackLayout = new SwipeBackLayout(this); swipeBackLayout.setDragEdge(DEFAULT_DRAG_EDGE); swipeBackLayout.setOnSwipeBackListener(this); ivShadow = new ImageView(this); ivShadow.setBackgroundColor(getResources().getColor(R.color.black_p50)); LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); container.addView(ivShadow, params); container.addView(swipeBackLayout); return container; } public void setEnableSwipe(boolean enableSwipe) { swipeBackLayout.setEnablePullToBack(enableSwipe); } public void setDragEdge(SwipeBackLayout.DragEdge dragEdge) { swipeBackLayout.setDragEdge(dragEdge); } public void setDragDirectMode(SwipeBackLayout.DragDirectMode dragDirectMode) { swipeBackLayout.setDragDirectMode(dragDirectMode); } public SwipeBackLayout getSwipeBackLayout() { return swipeBackLayout; } public void setOnFinishListener(SwipeBackLayout.OnFinishListener onFinishListener){ swipeBackLayout.setOnFinishListener(onFinishListener); } @Override public void onViewPositionChanged(float fractionAnchor, float fractionScreen) { ivShadow.setAlpha(1 - fractionScreen); } }
package com.sevenheaven.segmentcontrol; import android.content.Context; import android.content.res.ColorStateList; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.drawable.StateListDrawable; import android.os.Build; import android.util.AttributeSet; import android.util.Log; import android.util.TypedValue; import android.view.Gravity; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; public class SegmentControl extends ViewGroup implements View.OnClickListener { private String[] mTexts; private TextView[] mTextViews; private StateListDrawable[] mBackgroundDrawables; private RadiusDrawable mBackgroundDrawable; private int mHorizonGap; private int mVerticalGap; private int mCenterX; private int mCenterY; private int mChildrenWidth; private int mChildrenHeight; private int mSingleChildWidth; private int mSingleChildHeight; private Paint mPaint; public enum Direction{ HORIZON(0), VERTICAL(1); int mV; private Direction(int v){ mV = v; } } private Direction mDirection; private int mTextSize; private ColorStateList mColors; private int mCornerRadius; public SegmentControl(Context context){ this(context, null); } public SegmentControl(Context context,AttributeSet attrs){ this(context, attrs, 0); } public SegmentControl(Context context, AttributeSet attrs, int defStyle){ super(context, attrs, defStyle); TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.SegmentControl); String textArray = ta.getString(R.styleable.SegmentControl_texts); if(textArray != null){ mTexts = textArray.split("\\|"); } mTextSize = ta.getDimensionPixelSize(R.styleable.SegmentControl_android_textSize, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 14, context.getResources().getDisplayMetrics())); mColors = ta.getColorStateList(R.styleable.SegmentControl_colors); mCornerRadius = ta.getDimensionPixelSize(R.styleable.SegmentControl_cornerRadius, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 5, context.getResources().getDisplayMetrics())); mDirection = Direction.values()[ta.getInt(R.styleable.SegmentControl_direction, 0)]; mHorizonGap = ta.getDimensionPixelSize(R.styleable.SegmentControl_horizonGap, 0); mVerticalGap = ta.getDimensionPixelSize(R.styleable.SegmentControl_verticalGap, 0); int gap = ta.getDimensionPixelSize(R.styleable.SegmentControl_gaps, (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 2, context.getResources().getDisplayMetrics())); if(mHorizonGap == 0) mHorizonGap = gap; if(mVerticalGap == 0) mVerticalGap = gap; ta.recycle(); mBackgroundDrawable = new RadiusDrawable(mCornerRadius, true, 0); mBackgroundDrawable.setStrokeWidth(2); mBackgroundDrawable.setStrokeColor(mColors.getDefaultColor()); mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); } public void setText(String... texts){ mTexts = texts; if(mTexts != null){ requestLayout(); }else{ if(mTextViews != null){ for(TextView tv : mTextViews){ if(tv != null){ tv.setText(""); } } } } } public void setColors(ColorStateList colors){ mColors = colors; if(mBackgroundDrawable != null){ mBackgroundDrawable.setStrokeColor(colors.getDefaultColor()); } mPaint.setColor(colors.getDefaultColor()); requestLayout(); invalidate(); } public void setCornerRadius(int cornerRadius){ mCornerRadius = cornerRadius; if(mBackgroundDrawable != null){ mBackgroundDrawable.setRadius(cornerRadius); } requestLayout(); invalidate(); } public void setDirection(Direction direction){ Direction tDirection = mDirection; mDirection = direction; if(tDirection != direction){ requestLayout(); invalidate(); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec){ super.onMeasure(widthMeasureSpec, heightMeasureSpec); int widthMode = MeasureSpec.getMode(widthMeasureSpec); int heightMode = MeasureSpec.getMode(heightMeasureSpec); int widthSize = MeasureSpec.getSize(widthMeasureSpec); int heightSize = MeasureSpec.getSize(heightMeasureSpec); int width = 0; int height = 0; if(mTexts != null){ if(mTextViews == null || mTexts.length != mTextViews.length){ mTextViews = new TextView[mTexts.length]; removeAllViews(); } if(mBackgroundDrawables == null || mBackgroundDrawables.length != mTexts.length){ mBackgroundDrawables = new StateListDrawable[mTexts.length]; } for(int i = 0; i < mTexts.length; i++){ String text = mTexts[i]; if(text != null){ if(mTextViews[i] == null){ mTextViews[i] = new TextView(getContext()); addView(mTextViews[i]); } if(mBackgroundDrawables[i] == null){ mBackgroundDrawables[i] = new StateListDrawable(); int topLeftRadius = 0; int topRightRadius = 0; int bottomLeftRadius = 0; int bottomRightRadius = 0; if(mDirection == Direction.HORIZON){ if(i == 0){ topLeftRadius = mCornerRadius; bottomLeftRadius = mCornerRadius; }else if(i == mTexts.length - 1){ topRightRadius = mCornerRadius; bottomRightRadius = mCornerRadius; } }else{ if(i == 0){ topLeftRadius = mCornerRadius; topRightRadius = mCornerRadius; }else if(i == mTexts.length - 1){ bottomLeftRadius = mCornerRadius; bottomRightRadius = mCornerRadius; } } RadiusDrawable normalDrawable = new RadiusDrawable(topLeftRadius, topRightRadius, bottomLeftRadius, bottomRightRadius, false, 0); RadiusDrawable highlightDrawable = new RadiusDrawable(topLeftRadius, topRightRadius, bottomLeftRadius, bottomRightRadius, false, mColors.getDefaultColor()); highlightDrawable.setStrokeWidth(10); mBackgroundDrawables[i].addState(new int[]{-android.R.attr.state_selected}, normalDrawable); mBackgroundDrawables[i].addState(new int[]{android.R.attr.state_selected}, highlightDrawable); } mTextViews[i].setText(text); mTextViews[i].setTextSize(TypedValue.COMPLEX_UNIT_PX, mTextSize); ColorStateList colorList = new ColorStateList(new int[][]{new int[]{-android.R.attr.state_selected}, new int[]{android.R.attr.state_selected}}, new int[]{mColors.getDefaultColor(), 0xFFFFFFFF}); mTextViews[i].setTextColor(colorList); mTextViews[i].setSingleLine(true); mTextViews[i].setGravity(Gravity.CENTER); mTextViews[i].setSelected(i == 0 ? true : false); if(Build.VERSION.SDK_INT >= 16){ mTextViews[i].setBackground(mBackgroundDrawables[i]); }else{ mTextViews[i].setBackgroundDrawable(mBackgroundDrawables[i]); } mTextViews[i].setClickable(true); mTextViews[i].setOnClickListener(this); mTextViews[i].setId(i + 1); mTextViews[i].measure(MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.AT_MOST), MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.AT_MOST)); if(mSingleChildWidth < mTextViews[i].getMeasuredWidth()) mSingleChildWidth = mTextViews[i].getMeasuredWidth() + mHorizonGap * 2 - 4; if(mSingleChildHeight < mTextViews[i].getMeasuredHeight()) mSingleChildHeight = mTextViews[i].getMeasuredHeight() + mVerticalGap * 2 - 4; } } Log.d("hGap:" + mHorizonGap, "vGap:" + mVerticalGap); switch(widthMode){ case MeasureSpec.AT_MOST: if(mDirection == Direction.HORIZON){ if(widthSize <= mSingleChildWidth * mTexts.length){ mSingleChildWidth = widthSize / mTexts.length; width = widthSize; }else{ width = mSingleChildWidth * mTexts.length; } }else{ width = widthSize <= mSingleChildWidth ? widthSize : mSingleChildWidth; } break; case MeasureSpec.EXACTLY: width = widthSize; break; case MeasureSpec.UNSPECIFIED: if(mDirection == Direction.HORIZON){ width = mSingleChildWidth * mTexts.length; }else{ width = widthSize <= mSingleChildWidth ? widthSize : mSingleChildWidth; } break; } switch(heightMode){ case MeasureSpec.AT_MOST: if(mDirection == Direction.VERTICAL){ if(heightSize <= mSingleChildHeight * mTexts.length){ mSingleChildHeight = heightSize / mTexts.length; height = heightSize; }else{ height = mSingleChildHeight * mTexts.length; } }else{ height = heightSize <= mSingleChildHeight ? heightSize : mSingleChildHeight; } break; case MeasureSpec.EXACTLY: height = heightSize; break; case MeasureSpec.UNSPECIFIED: if(mDirection == Direction.VERTICAL){ height = mSingleChildHeight * mTexts.length; }else{ height = heightSize <= mSingleChildHeight ? heightSize : mSingleChildHeight; } break; } mChildrenWidth = mDirection == Direction.HORIZON ? mSingleChildWidth * mTexts.length : mSingleChildWidth; mChildrenHeight = mDirection == Direction.VERTICAL ? mSingleChildHeight * mTexts.length : mSingleChildHeight; }else{ width = widthMode == MeasureSpec.UNSPECIFIED ? 0 : widthSize; height = heightMode == MeasureSpec.UNSPECIFIED ? 0 : heightSize; } mCenterX = width / 2; mCenterY = height / 2; setMeasuredDimension(width, height); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom){ int startX = mCenterX - mChildrenWidth / 2; int startY = mCenterY - mChildrenHeight / 2; for(int i = 0; i < getChildCount(); i++){ View child = getChildAt(i); int cLeft = 0; int cTop = 0; int cRight = 0; int cBottom = 0; if(mDirection == Direction.HORIZON){ cLeft = startX + (i * mSingleChildWidth); cTop = startY; }else{ cLeft = startX; cTop = startY + (i * mSingleChildHeight); } cRight = cLeft + mSingleChildWidth; cBottom = cTop + mSingleChildHeight; Log.d("left:" + cLeft + ", top:" + cTop, "right:" + cRight + ",bottom:" + cBottom); child.layout(cLeft, cTop, cRight, cBottom); } } @Override public void onClick(View v){ for(TextView tv : mTextViews){ if(tv == v){ tv.setSelected(true); }else{ tv.setSelected(false); } } } @Override public void dispatchDraw(Canvas canvas){ super.dispatchDraw(canvas); if(mBackgroundDrawable != null){ int halfWidth = mChildrenWidth / 2; int halfHeight = mChildrenHeight / 2; mBackgroundDrawable.setBounds(mCenterX - halfWidth, mCenterY - halfHeight, mCenterX + halfWidth, mCenterY + halfHeight); mBackgroundDrawable.draw(canvas); } if(mTextViews != null && mTextViews.length > 0){ for(int i = 0; i < mTextViews.length - 1; i++){ TextView tv = mTextViews[i]; mPaint.setStyle(Paint.Style.STROKE); mPaint.setStrokeWidth(2); mPaint.setColor(mColors.getDefaultColor()); if(mDirection == Direction.HORIZON){ canvas.drawLine(tv.getRight(), tv.getTop(), tv.getRight(), tv.getBottom() - 2, mPaint); }else{ canvas.drawLine(tv.getLeft(), tv.getBottom(), tv.getRight() - 2, tv.getBottom(), mPaint); } } } } }
package liquibase.change.core; import liquibase.change.*; import liquibase.configuration.GlobalConfiguration; import liquibase.configuration.LiquibaseConfiguration; import liquibase.database.Database; import liquibase.database.core.OracleDatabase; import liquibase.database.core.SQLiteDatabase; import liquibase.exception.UnexpectedLiquibaseException; import liquibase.exception.ValidationErrors; import liquibase.parser.core.ParsedNode; import liquibase.parser.core.ParsedNodeException; import liquibase.resource.ResourceAccessor; import liquibase.snapshot.SnapshotGeneratorFactory; import liquibase.sqlgenerator.SqlGeneratorFactory; import liquibase.statement.SqlStatement; import liquibase.statement.core.CreateViewStatement; import liquibase.statement.core.DropViewStatement; import liquibase.statement.core.SetTableRemarksStatement; import liquibase.structure.core.View; import liquibase.util.StreamUtil; import liquibase.util.StringUtils; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.List; /** * Creates a new view. */ @DatabaseChange(name="createView", description = "Create a new database view", priority = ChangeMetaData.PRIORITY_DEFAULT) public class CreateViewChange extends AbstractChange { private String catalogName; private String schemaName; private String viewName; private String selectQuery; private Boolean replaceIfExists; private Boolean fullDefinition; private String path; private Boolean relativeToChangelogFile; private String encoding = null; private String remarks; @DatabaseChangeProperty(since = "3.0") public String getCatalogName() { return catalogName; } public void setCatalogName(String catalogName) { this.catalogName = catalogName; } public String getSchemaName() { return schemaName; } public void setSchemaName(String schemaName) { this.schemaName = schemaName; } @DatabaseChangeProperty(description = "Name of the view to create") public String getViewName() { return viewName; } public void setViewName(String viewName) { this.viewName = viewName; } @DatabaseChangeProperty(serializationType = SerializationType.DIRECT_VALUE, description = "SQL for generating the view", exampleValue = "select id, name from person where id > 10") public String getSelectQuery() { return selectQuery; } public void setSelectQuery(String selectQuery) { this.selectQuery = selectQuery; } @DatabaseChangeProperty(description = "Use 'create or replace' syntax", since = "1.5") public Boolean getReplaceIfExists() { return replaceIfExists; } public void setReplaceIfExists(Boolean replaceIfExists) { this.replaceIfExists = replaceIfExists; } @DatabaseChangeProperty(description = "Set to true if selectQuery is the entire view definition. False if the CREATE VIEW header should be added", since = "3.3") public Boolean getFullDefinition() { return fullDefinition; } public void setFullDefinition(Boolean fullDefinition) { this.fullDefinition = fullDefinition; } @DatabaseChangeProperty(description = "Path to file containing view definition", since = "3.6") public String getPath() { return path; } public void setPath(String path) { this.path = path; } public Boolean getRelativeToChangelogFile() { return relativeToChangelogFile; } public void setRelativeToChangelogFile(Boolean relativeToChangelogFile) { this.relativeToChangelogFile = relativeToChangelogFile; } public String getEncoding() { return encoding; } public void setEncoding(String encoding) { this.encoding = encoding; } public String getRemarks() { return remarks; } public void setRemarks(String remarks) { this.remarks = remarks; } @Override public ValidationErrors validate(Database database) { ValidationErrors validate = super.validate(database); if (!validate.hasErrors()) { if (StringUtils.trimToNull(getSelectQuery()) != null && StringUtils.trimToNull(getPath()) != null) { validate.addError("Cannot specify both 'path' and a nested view definition in " + ChangeFactory.getInstance().getChangeMetaData(this).getName()); } if (StringUtils.trimToNull(getSelectQuery()) == null && StringUtils.trimToNull(getPath()) == null) { validate.addError("For a createView change, you must specify either 'path' or a nested view " + "definition in " + "" + ChangeFactory .getInstance().getChangeMetaData(this).getName()); } } return validate; } protected InputStream openSqlStream() throws IOException { if (path == null) { return null; } try { return StreamUtil.openStream(getPath(), getRelativeToChangelogFile(), getChangeSet(), getResourceAccessor()); } catch (IOException e) { throw new IOException("<" + ChangeFactory.getInstance().getChangeMetaData(this).getName() + " path=" + path + "> -Unable to read file", e); } } /** * Calculates the checksum based on the contained SQL. * * @see liquibase.change.AbstractChange#generateCheckSum() */ @Override public CheckSum generateCheckSum() { if (this.path == null) { return super.generateCheckSum(); } InputStream stream = null; try { stream = openSqlStream(); } catch (IOException e) { throw new UnexpectedLiquibaseException(e); } try { String selectQuery = this.selectQuery; if (stream == null && selectQuery == null) { selectQuery = ""; } String encoding = LiquibaseConfiguration.getInstance().getConfiguration(GlobalConfiguration.class).getOutputEncoding(); if (selectQuery != null) { try { stream = new ByteArrayInputStream(selectQuery.getBytes(encoding)); } catch (UnsupportedEncodingException e) { throw new AssertionError(encoding+" is not supported by the JVM, this should not happen according to the JavaDoc of the Charset class"); } } CheckSum checkSum = CheckSum.compute(new AbstractSQLChange.NormalizingStream(";", false, false, stream), false); return CheckSum.compute(super.generateCheckSum().toString() + ":" + checkSum.toString()); } finally { if (stream != null) { try { stream.close(); } catch (IOException ignore) { } } } } @Override public SqlStatement[] generateStatements(Database database) { List<SqlStatement> statements = new ArrayList<SqlStatement>(); boolean replaceIfExists = false; if (getReplaceIfExists() != null && getReplaceIfExists()) { replaceIfExists = true; } boolean fullDefinition = false; if (this.fullDefinition != null) { fullDefinition = this.fullDefinition; } String selectQuery; String path = getPath(); if (path == null) { selectQuery = StringUtils.trimToNull(getSelectQuery()); } else { try { InputStream stream = openSqlStream(); if (stream == null) { throw new IOException("File does not exist: " + path); } selectQuery = StreamUtil.getStreamContents(stream, encoding); } catch (IOException e) { throw new UnexpectedLiquibaseException(e); } } if (!supportsReplaceIfExistsOption(database) && replaceIfExists) { statements.add(new DropViewStatement(getCatalogName(), getSchemaName(), getViewName())); statements.add(createViewStatement(getCatalogName(), getSchemaName(), getViewName(), selectQuery, false) .setFullDefinition(fullDefinition)); } else { statements.add(createViewStatement(getCatalogName(), getSchemaName(), getViewName(), selectQuery, replaceIfExists) .setFullDefinition(fullDefinition)); } if (database instanceof OracleDatabase && StringUtils.trimToNull(remarks) != null) { SetTableRemarksStatement remarksStatement = new SetTableRemarksStatement(catalogName, schemaName, viewName, remarks); if (SqlGeneratorFactory.getInstance().supports(remarksStatement, database)) { statements.add(remarksStatement); } } return statements.toArray(new SqlStatement[statements.size()]); } protected CreateViewStatement createViewStatement(String catalogName, String schemaName, String viewName, String selectQuery, boolean b) { return new CreateViewStatement(catalogName, schemaName, viewName, selectQuery, b); } @Override public String getConfirmationMessage() { return "View " + getViewName() + " created"; } @Override protected Change[] createInverses() { DropViewChange inverse = new DropViewChange(); inverse.setViewName(getViewName()); inverse.setSchemaName(getSchemaName()); return new Change[] { inverse }; } @Override public ChangeStatus checkStatus(Database database) { ChangeStatus result = new ChangeStatus(); try { View example = new View(getCatalogName(), getSchemaName(), getViewName()); View snapshot = SnapshotGeneratorFactory.getInstance().createSnapshot(example, database); result.assertComplete(snapshot != null, "View does not exist"); return result; } catch (Exception e) { return result.unknown(e); } } private boolean supportsReplaceIfExistsOption(Database database) { return !(database instanceof SQLiteDatabase); } @Override public String getSerializedObjectNamespace() { return STANDARD_CHANGELOG_NAMESPACE; } @Override protected void customLoadLogic(ParsedNode parsedNode, ResourceAccessor resourceAccessor) throws ParsedNodeException { Object value = parsedNode.getValue(); if (value instanceof String) { this.setSelectQuery((String) value); } } }
package org.jlib.container.sequence.index.array; import java.util.Collection; import org.jlib.container.Container; import org.jlib.container.sequence.AppendSequence; import org.jlib.container.sequence.Sequence; import org.jlib.container.sequence.SequenceUtility; import org.jlib.container.sequence.index.DefaultReplaceIndexSequenceTraverser; import org.jlib.container.sequence.index.IndexSequenceCreator; import org.jlib.container.sequence.index.InvalidSequenceIndexRangeException; import org.jlib.container.sequence.index.ReplaceIndexSequenceTraverser; import static org.jlib.container.sequence.SequenceUtility.singleton; /** * {@link ReplaceArraySequence} to which Items can be added. * * @param <Item> * type of items held in the {@link Sequence} * * @author Igor Akkerman */ public class ReplaceAppendArraySequence<Item> extends ReplaceArraySequence<Item> implements AppendSequence<Item> { /** * {@link IndexSequenceCreator} of {@link ReplaceAppendArraySequence} * insstances */ private static final IndexSequenceCreator<?, ? extends ReplaceAppendArraySequence<?>> CREATOR = new IndexSequenceCreator<Object, ReplaceAppendArraySequence<Object>>() { @Override public ReplaceAppendArraySequence<Object> createSequence(final int firstIndex, final int lastIndex) throws InvalidSequenceIndexRangeException { return new ReplaceAppendArraySequence<Object>(firstIndex, lastIndex); } }; /** * Returns the {@link IndexSequenceCreator} of * {@link ReplaceAppendArraySequence} instances. * * @return {@link IndexSequenceCreator} of * {@link ReplaceAppendArraySequence} instances */ @SuppressWarnings("unchecked") public static <Item> IndexSequenceCreator<Item, ? extends ReplaceAppendArraySequence<Item>> getCreator() { return (IndexSequenceCreator<Item, ReplaceAppendArraySequence<Item>>) CREATOR; } protected ReplaceAppendArraySequence(final int firstIndex, final int lastIndex) { super(firstIndex, lastIndex); } @Override public void append(final Item item) { append(singleton(item)); } @Override public void append(final Container<? extends Item> items) { final int addedItemsCount = items.getSize(); assertCapacity(getSize() + addedItemsCount); int itemArrayIndex = getSize(); for (final Item item : items) replaceDelegateArrayItem(itemArrayIndex ++, item); setLastIndex(getLastIndex() + addedItemsCount); } @Override public void append(final Collection<? extends Item> items) { SequenceUtility.append(this, items); } @Override @SafeVarargs public final void append(final Item... items) { SequenceUtility.append(this, items); } @Override public ReplaceIndexSequenceTraverser<Item> createReplaceIndexSequenceTraverser() { return new DefaultReplaceIndexSequenceTraverser<Item, ReplaceAppendArraySequence<Item>>(this); } }
package java.lang; public class ArrayIndexOutOfBoundsException extends IndexOutOfBoundsException { private static final long serialVersionUID = -5116101128118950844L; /** * Constructs an <code>ArrayIndexOutOfBoundsException</code> with no * detail message. */ public ArrayIndexOutOfBoundsException() { super(); } public ArrayIndexOutOfBoundsException(int index) { super("Array index out of range: " + index); } /** * Constructs an <code>ArrayIndexOutOfBoundsException</code> class * with the specified detail message. * * @param s the detail message. */ public ArrayIndexOutOfBoundsException(String s) { super(s); } }
package org.sagebionetworks.repo.model.dbo.persistence; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_ACL_OWNER_ID_COLUMN; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_ACL_ID; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_ACL_ETAG; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.COL_ACL_CREATED_ON; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.DDL_FILE_ACL; import static org.sagebionetworks.repo.model.query.jdo.SqlConstants.TABLE_ACCESS_CONTROL_LIST; import java.sql.ResultSet; import java.sql.SQLException; import java.util.LinkedList; import java.util.List; import java.util.UUID; import org.sagebionetworks.repo.model.dbo.FieldColumn; import org.sagebionetworks.repo.model.dbo.MigratableDatabaseObject; import org.sagebionetworks.repo.model.dbo.TableMapping; import org.sagebionetworks.repo.model.dbo.migration.MigratableTableTranslation; import org.sagebionetworks.repo.model.migration.MigrationType; public class DBOAccessControlList implements MigratableDatabaseObject<DBOAccessControlList, DBOAccessControlList> { private static FieldColumn[] FIELDS = new FieldColumn[] { new FieldColumn("id", COL_ACL_ID, true).withIsBackupId(true), new FieldColumn("etag", COL_ACL_ETAG).withIsEtag(true), new FieldColumn("resource", COL_ACL_OWNER_ID_COLUMN), new FieldColumn("creationDate", COL_ACL_CREATED_ON) }; @Override public TableMapping<DBOAccessControlList> getTableMapping() { return new TableMapping<DBOAccessControlList>(){ @Override public DBOAccessControlList mapRow(ResultSet rs, int rowNum) throws SQLException { DBOAccessControlList acl = new DBOAccessControlList(); acl.setId(rs.getLong(COL_ACL_ID)); acl.setEtag(rs.getString(COL_ACL_ETAG)); acl.setResource(rs.getLong(COL_ACL_OWNER_ID_COLUMN)); acl.setCreationDate(rs.getLong(COL_ACL_CREATED_ON)); return acl; } @Override public String getTableName() { return TABLE_ACCESS_CONTROL_LIST; } @Override public String getDDLFileName() { return DDL_FILE_ACL; } @Override public FieldColumn[] getFieldColumns() { return FIELDS; } @Override public Class<? extends DBOAccessControlList> getDBOClass() { return DBOAccessControlList.class; }}; } private Long id; private String etag; private Long resource; private Long creationDate; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getEtag() { return etag; } public void setEtag(String etag) { this.etag = etag; } public Long getResource() { return resource; } public void setResource(Long resource) { this.resource = resource; } public Long getCreationDate() { return creationDate; } public void setCreationDate(Long creationDate) { this.creationDate = creationDate; } @Override public MigrationType getMigratableTableType() { return MigrationType.ACL; } @Override public MigratableTableTranslation<DBOAccessControlList, DBOAccessControlList> getTranslator() { return new MigratableTableTranslation<DBOAccessControlList, DBOAccessControlList>(){ @Override public DBOAccessControlList createDatabaseObjectFromBackup( DBOAccessControlList backup) { if (backup.getEtag() == null) { backup.setEtag(UUID.randomUUID().toString()); } return backup; } @Override public DBOAccessControlList createBackupFromDatabaseObject( DBOAccessControlList dbo) { return dbo; }}; } @Override public Class<? extends DBOAccessControlList> getBackupClass() { return DBOAccessControlList.class; } @Override public Class<? extends DBOAccessControlList> getDatabaseObjectClass() { return DBOAccessControlList.class; } @Override public List<MigratableDatabaseObject> getSecondaryTypes() { List<MigratableDatabaseObject> list = new LinkedList<MigratableDatabaseObject>(); list.add(new DBOResourceAccess()); list.add(new DBOResourceAccessType()); return list; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((creationDate == null) ? 0 : creationDate.hashCode()); result = prime * result + ((etag == null) ? 0 : etag.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((resource == null) ? 0 : resource.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DBOAccessControlList other = (DBOAccessControlList) obj; if (creationDate == null) { if (other.creationDate != null) return false; } else if (!creationDate.equals(other.creationDate)) return false; if (etag == null) { if (other.etag != null) return false; } else if (!etag.equals(other.etag)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (resource == null) { if (other.resource != null) return false; } else if (!resource.equals(other.resource)) return false; return true; } @Override public String toString() { return "DBOAccessControlList [id=" + id + ", etag=" + etag + ", resource=" + resource + ", creationDate=" + creationDate + "]"; } }
package com.matthewtamlin.avatar.rules.avatar_rule.without_running; import com.matthewtamlin.avatar.rules.AvatarRule; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import javax.tools.JavaFileObject; import java.io.File; import java.lang.annotation.Annotation; import java.util.ArrayList; import java.util.List; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.mockito.Matchers.notNull; import static org.mockito.Mockito.mock; @SuppressWarnings("RedundantArrayCreation") @RunWith(JUnit4.class) public class TestAvatarRule { private static final String DATA_FILE_PATH = "src/test/java/com/matthewtamlin/avatar/rules/avatar_rule/without_running/Data.java"; @BeforeClass public static void setupClass() { assertThat(new File(DATA_FILE_PATH).exists(), is(true)); } @Test public void testWithoutSources_checkNeverReturnsNull() { final AvatarRule rule = AvatarRule.withoutSources(); assertThat(rule, is(notNull())); } @Test(expected = IllegalStateException.class) public void testInstantiateViaBuilder_noSourcesSet() { AvatarRule .builder() .withSuccessfulCompilationRequired(false) .build(); } @Test public void testInstantiateViaBuilder_noSuccessfulCompilationRequiredFlagSet() { AvatarRule .builder() .withSourcesAt(DATA_FILE_PATH) .build(); } @Test(expected = IllegalStateException.class) public void testInstantiateViaBuilder_sourcesSetThenCleared() { AvatarRule .builder() .withSourcesAt(DATA_FILE_PATH) .withSourcesAt((Iterable<String>) null) .build(); } @Test(expected = IllegalStateException.class) public void testInstantiateViaBuilder_sourcesSetUsingWithSourceFileObjects_nullIterable() { AvatarRule .builder() .withSourceFileObjects((Iterable<JavaFileObject>) null) .build(); } @Test public void testInstantiateViaBuilder_sourcesSetUsingWithSourceFileObjects_emptyIterable() { final List<JavaFileObject> sources = new ArrayList<>(); AvatarRule .builder() .withSourceFileObjects(sources) .build(); } @Test(expected = IllegalArgumentException.class) public void testInstantiateViaBuilder_sourcesSetUsingWithSourceFileObjects_iterableContainingNull() { final List<JavaFileObject> sources = new ArrayList<>(); sources.add(null); AvatarRule .builder() .withSourceFileObjects(sources) .build(); } @Test public void testInstantiateViaBuilder_sourcesSetUsingWithSourceFileObjects_iterableContainingOneValidItem() { final List<JavaFileObject> sources = new ArrayList<>(); sources.add(mock(JavaFileObject.class)); AvatarRule .builder() .withSourceFileObjects(sources) .build(); } @Test public void testInstantiateViaBuilder_sourcesSetUsingWithSourceFileObjects_iterableContainingMultipleValidItems() { final List<JavaFileObject> sources = new ArrayList<>(); sources.add(mock(JavaFileObject.class)); sources.add(mock(JavaFileObject.class)); AvatarRule .builder() .withSourceFileObjects(sources) .build(); } @Test(expected = IllegalArgumentException.class) public void testInstantiateViaBuilder_sourcesSetUsingWithSourceFileObjects_nullArray() { AvatarRule .builder() .withSourceFileObjects((JavaFileObject) null) .build(); } @Test public void testInstantiateViaBuilder_sourcesSetUsingWithSourceFileObjects_emptyArray() { AvatarRule .builder() .withSourceFileObjects(new JavaFileObject[]{}) .build(); } @Test(expected = IllegalArgumentException.class) public void testInstantiateViaBuilder_sourcesSetUsingWithSourceFileObjects_arrayContainingNull() { AvatarRule .builder() .withSourceFileObjects(new JavaFileObject[]{null}) .build(); } @Test public void testInstantiateViaBuilder_sourcesSetUsingWithSourceFileObjects_arrayContainingOneValidItem() { AvatarRule.builder().withSourceFileObjects(new JavaFileObject[]{mock(JavaFileObject.class)}).build(); } @Test public void testInstantiateViaBuilder_sourcesSetUsingWithSourceFileObjects_arrayContainingMultipleValidItems() { AvatarRule .builder() .withSourceFileObjects(mock(JavaFileObject.class), mock(JavaFileObject.class)) .build(); } @Test(expected = IllegalStateException.class) public void testInstantiateViaBuilder_sourcesSetUsingWithSourceFiles_nullIterable() { AvatarRule .builder() .withSourceFiles((Iterable<File>) null) .build(); } @Test public void testInstantiateViaBuilder_sourcesSetUsingWithSourceFiles_emptyIterable() { final List<File> sources = new ArrayList<>(); AvatarRule .builder() .withSourceFiles(sources) .build(); } @Test(expected = IllegalArgumentException.class) public void testInstantiateViaBuilder_sourcesSetUsingWithSourceFiles_iterableContainingNull() { final List<File> sources = new ArrayList<>(); sources.add(null); AvatarRule .builder() .withSourceFiles(sources) .build(); } @Test(expected = IllegalArgumentException.class) public void testInstantiateViaBuilder_sourcesSetUsingWithSourceFiles_iterableContainingNonExistentFile() { final List<File> sources = new ArrayList<>(); sources.add(new File("I don't exist")); AvatarRule .builder() .withSourceFiles(sources) .build(); } @Test public void testInstantiateViaBuilder_sourcesSetUsingWithSourceFiles_iterableContainingOneValidItem() { final List<File> sources = new ArrayList<>(); sources.add(new File(DATA_FILE_PATH)); AvatarRule .builder() .withSourceFiles(sources) .build(); } @Test public void testInstantiateViaBuilder_sourcesSetUsingWithSourceFiles_iterableContainingMultipleValidItems() { final List<File> sources = new ArrayList<>(); sources.add(new File(DATA_FILE_PATH)); sources.add(new File(DATA_FILE_PATH)); AvatarRule .builder() .withSourceFiles(sources) .build(); } @Test(expected = IllegalArgumentException.class) public void testInstantiateViaBuilder_sourcesSetUsingWithSourceFiles_nullArray() { AvatarRule .builder() .withSourceFiles((File) null) .build(); } @Test public void testInstantiateViaBuilder_sourcesSetUsingWithSourceFiles_emptyArray() { AvatarRule .builder() .withSourceFiles(new File[]{}) .build(); } @Test(expected = IllegalArgumentException.class) public void testInstantiateViaBuilder_sourcesSetUsingWithSourceFiles_arrayContainingNull() { AvatarRule .builder() .withSourceFiles(new File[]{null}) .build(); } @Test(expected = IllegalArgumentException.class) public void testInstantiateViaBuilder_sourcesSetUsingWithSourceFiles_arrayContainingNonExistentFile() { AvatarRule .builder() .withSourceFiles(new File("I don't exist")) .build(); } @Test public void testInstantiateViaBuilder_sourcesSetUsingWithSourceFiles_arrayContainingOneValidItem() { AvatarRule .builder() .withSourceFiles(new File(DATA_FILE_PATH)) .build(); } @Test public void testInstantiateViaBuilder_sourcesSetUsingWithSourceFiles_arrayContainingMultipleValidItems() { AvatarRule .builder() .withSourceFiles(new File(DATA_FILE_PATH), new File(DATA_FILE_PATH)) .build(); } @Test(expected = IllegalStateException.class) public void testInstantiateViaBuilder_sourcesSetUsingWithSourceFilesAt_nullIterable() { AvatarRule .builder() .withSourcesAt((Iterable<String>) null) .build(); } @Test public void testInstantiateViaBuilder_sourcesSetUsingWithSourceFilesAt_emptyIterable() { final List<String> sources = new ArrayList<>(); AvatarRule .builder() .withSourcesAt(sources) .build(); } @Test(expected = IllegalArgumentException.class) public void testInstantiateViaBuilder_sourcesSetUsingWithSourceFilesAt_iterableContainingNull() { final List<String> sources = new ArrayList<>(); sources.add(null); AvatarRule .builder() .withSourcesAt(sources) .build(); } @Test(expected = IllegalArgumentException.class) public void testInstantiateViaBuilder_sourcesSetUsingWithSourceFilesAt_iterableContainingNonExistentFilePath() { final List<String> sources = new ArrayList<>(); sources.add("I don't exist"); AvatarRule .builder() .withSourcesAt(sources) .build(); } @Test public void testInstantiateViaBuilder_sourcesSetUsingWithSourceFilesAt_iterableContainingOneValidItem() { final List<String> sources = new ArrayList<>(); sources.add(DATA_FILE_PATH); AvatarRule .builder() .withSourcesAt(sources) .build(); } @Test public void testInstantiateViaBuilder_sourcesSetUsingWithSourceFilesAt_iterableContainingMultipleValidItems() { final List<String> sources = new ArrayList<>(); sources.add(DATA_FILE_PATH); sources.add(DATA_FILE_PATH); AvatarRule .builder() .withSourcesAt(sources) .build(); } @Test(expected = IllegalArgumentException.class) public void testInstantiateViaBuilder_sourcesSetUsingWithSourceFilesAt_nullValue() { AvatarRule .builder() .withSourcesAt((String) null) .build(); } @Test public void testInstantiateViaBuilder_sourcesSetUsingWithSourceFilesAt_emptyArray() { AvatarRule .builder() .withSourcesAt(new String[]{}) .build(); } @Test(expected = IllegalArgumentException.class) public void testInstantiateViaBuilder_sourcesSetUsingWithSourceFilesAt_arrayContainingNull() { AvatarRule .builder() .withSourcesAt(new String[]{null}) .build(); } @Test(expected = IllegalArgumentException.class) public void testInstantiateViaBuilder_sourcesSetUsingWithSourceFilesAt_arrayContainingNonExistentFilePath() { AvatarRule .builder() .withSourcesAt(new String[]{"I don't exist"}) .build(); } @Test public void testInstantiateViaBuilder_sourcesSetUsingWithSourceFilesAt_arrayContainingOneValidItem() { AvatarRule .builder() .withSourcesAt(new String[]{DATA_FILE_PATH}) .build(); } @Test public void testInstantiateViaBuilder_sourcesSetUsingWithSourceFilesAt_arrayContainingMultipleValidItems() { AvatarRule .builder() .withSourcesAt(DATA_FILE_PATH, DATA_FILE_PATH) .build(); } @Test(expected = IllegalStateException.class) public void testGetProcessingEnvironment_failsWhenCalledBeforeRuleIsApplied() { final AvatarRule rule = AvatarRule .builder() .withSourcesAt(DATA_FILE_PATH) .build(); rule.getProcessingEnvironment(); } @Test(expected = IllegalStateException.class) public void testGetCompilationResult_failsWhenCalledBeforeRuleIsApplied() { final AvatarRule rule = AvatarRule .builder() .withSourcesAt(DATA_FILE_PATH) .build(); rule.getCompilationResult(); } @Test(expected = IllegalStateException.class) public void testGetRoundEnvironments_failsWhenCalledBeforeRuleIsApplied() { final AvatarRule rule = AvatarRule .builder() .withSourcesAt(DATA_FILE_PATH) .build(); rule.getRoundEnvironments(); } @Test(expected = IllegalStateException.class) public void testGetElementsWithId_failsWhenCalledBeforeRuleIsApplied() { final AvatarRule rule = AvatarRule .builder() .withSourcesAt(DATA_FILE_PATH) .build(); rule.getElementsWithId(""); } @Test(expected = IllegalStateException.class) public void testGetElementsWithUniqueId_failsWhenCalledBeforeRuleIsApplied() { final AvatarRule rule = AvatarRule .builder() .withSourcesAt(DATA_FILE_PATH) .build(); rule.getElementWithUniqueId(""); } @Test(expected = IllegalStateException.class) public void testGetElementsWithAnnotation_failsWhenCalledBeforeRuleIsApplied() { final AvatarRule rule = AvatarRule .builder() .withSourcesAt(DATA_FILE_PATH) .build(); rule.getElementsWithAnnotation(Annotation.class); } @Test(expected = IllegalStateException.class) public void testGetRootElements_failsWhenCalledBeforeRuleIsApplied() { final AvatarRule rule = AvatarRule .builder() .withSourcesAt(DATA_FILE_PATH) .build(); rule.getRootElements(); } }
//FILE: VirtualAcquisitionDisplay.java //PROJECT: Micro-Manager //SUBSYSTEM: mmstudio // This file is distributed in the hope that it will be useful, // of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES. package org.micromanager.acquisition; import org.micromanager.internalinterfaces.DisplayControls; import org.micromanager.internalinterfaces.Histograms; import java.lang.reflect.InvocationTargetException; import ij.ImageStack; import ij.process.LUT; import ij.CompositeImage; import ij.ImagePlus; import ij.WindowManager; import ij.gui.ImageCanvas; import ij.gui.ImageWindow; import ij.gui.ScrollbarWithLabel; import ij.gui.StackWindow; import ij.gui.Toolbar; import ij.io.FileInfo; import ij.measure.Calibration; import ij.plugin.frame.ContrastAdjuster; import java.awt.*; import java.awt.event.*; import java.io.File; import java.io.IOException; import java.util.HashMap; import java.util.TimerTask; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.util.prefs.Preferences; import javax.swing.JMenuItem; import javax.swing.JOptionPane; import javax.swing.JPopupMenu; import javax.swing.SwingUtilities; import javax.swing.Timer; import mmcorej.TaggedImage; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.micromanager.MMStudioMainFrame; import org.micromanager.api.*; import org.micromanager.graph.HistogramControlsState; import org.micromanager.graph.MultiChannelHistograms; import org.micromanager.graph.SingleChannelHistogram; import org.micromanager.utils.*; public final class VirtualAcquisitionDisplay implements AcquisitionDisplay, ImageCacheListener, MMListenerInterface { public static VirtualAcquisitionDisplay getDisplay(ImagePlus imgp) { ImageStack stack = imgp.getStack(); if (stack instanceof AcquisitionVirtualStack) { return ((AcquisitionVirtualStack) stack).getVirtualAcquisitionDisplay(); } else { return null; } } private final static int SLOW_UPDATE_TIME = 1500; private static final int ANIMATION_AND_LOCK_RESTART_DELAY = 800; final static Color[] rgb = {Color.red, Color.green, Color.blue}; final static String[] rgbNames = {"Red", "Blue", "Green"}; final ImageCache imageCache_; final Preferences prefs_ = Preferences.userNodeForPackage(this.getClass()); private static final String SIMPLE_WIN_X = "simple_x"; private static final String SIMPLE_WIN_Y = "simple_y"; private AcquisitionEngine eng_; private boolean finished_ = false; private boolean promptToSave_ = true; private String name_; private long lastDisplayTime_; private int lastFrameShown_ = 0; private int lastSliceShown_ = 0; private int lastPositionShown_ = 0; private int lockedSlice_ = -1, lockedPosition_ = -1, lockedChannel_ = -1, lockedFrame_ = -1;; private int numComponents_; private ImagePlus hyperImage_; private ScrollbarWithLabel pSelector_; private ScrollbarWithLabel tSelector_; private ScrollbarWithLabel zSelector_; private ScrollbarWithLabel cSelector_; private DisplayControls controls_; public AcquisitionVirtualStack virtualStack_; private boolean simple_ = false; private boolean mda_ = false; //flag if display corresponds to MD acquisition private MetadataPanel mdPanel_; private boolean newDisplay_ = true; //used for autostretching on window opening private double framesPerSec_ = 7; private java.util.Timer zAnimationTimer_ = new java.util.Timer(); private java.util.Timer tAnimationTimer_ = new java.util.Timer(); private boolean zAnimated_ = false, tAnimated_ = false; private int animatedSliceIndex_ = -1, animatedFrameIndex_ = -1; private Component zAnimationIcon_, pIcon_, tAnimationIcon_, cIcon_; private Component zLockIcon_, cLockIcon_, pLockIcon_, tLockIcon_; private Timer resetToLockedTimer_; private HashMap<Integer, Integer> zStackMins_; private HashMap<Integer, Integer> zStackMaxes_; private Histograms histograms_; private HistogramControlsState histogramControlsState_; private boolean albumSaved_ = false; private static double snapWinMag_ = -1; private JPopupMenu saveTypePopup_; private int simpleWinImagesReceived_ = 0; private AtomicBoolean updatePixelSize_ = new AtomicBoolean(false); private AtomicLong newPixelSize_ = new AtomicLong(); public void propertiesChangedAlert() { //throw new UnsupportedOperationException("Not supported yet."); } public void propertyChangedAlert(String device, String property, String value) { //throw new UnsupportedOperationException("Not supported yet."); } public void configGroupChangedAlert(String groupName, String newConfig) { //throw new UnsupportedOperationException("Not supported yet."); } public void pixelSizeChangedAlert(double newPixelSizeUm) { // Signal that pixel size has changed so that the next image will update // metadata and scale bar newPixelSize_.set(Double.doubleToLongBits(newPixelSizeUm)); updatePixelSize_.set(true); } public void stagePositionChangedAlert(String deviceName, double pos) { //throw new UnsupportedOperationException("Not supported yet."); } public void xyStagePositionChanged(String deviceName, double xPos, double yPos) { //throw new UnsupportedOperationException("Not supported yet."); } public void exposureChanged(String cameraName, double newExposureTime) { //throw new UnsupportedOperationException("Not supported yet."); } /** * This interface and the following two classes * allow us to manipulate the dimensions * in an ImagePlus without it throwing conniptions. */ public interface IMMImagePlus { public int getNChannelsUnverified(); public int getNSlicesUnverified(); public int getNFramesUnverified(); public void setNChannelsUnverified(int nChannels); public void setNSlicesUnverified(int nSlices); public void setNFramesUnverified(int nFrames); public void drawWithoutUpdate(); public void updateAndDrawWithoutGUIUpdater(); } public class MMCompositeImage extends CompositeImage implements IMMImagePlus { private GUIUpdater updater1 = new GUIUpdater(), updater2 = new GUIUpdater(), updater3 = new GUIUpdater(); MMCompositeImage(ImagePlus imgp, int type) { super(imgp, type); } @Override public String getTitle() { return name_; } @Override public int getImageStackSize() { return super.nChannels * super.nSlices * super.nFrames; } @Override public int getStackSize() { return getImageStackSize(); } @Override public int getNChannelsUnverified() { return super.nChannels; } @Override public int getNSlicesUnverified() { return super.nSlices; } @Override public int getNFramesUnverified() { return super.nFrames; } @Override public void setNChannelsUnverified(int nChannels) { super.nChannels = nChannels; } @Override public void setNSlicesUnverified(int nSlices) { super.nSlices = nSlices; } @Override public void setNFramesUnverified(int nFrames) { super.nFrames = nFrames; } private void superReset() { super.reset(); } @Override public void reset() { if (SwingUtilities.isEventDispatchThread()) { super.reset(); } else { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { superReset(); } }); } } @Override public synchronized void setMode(final int mode) { superSetMode(mode); } private void superSetMode(int mode) { super.setMode(mode); } @Override public synchronized void setChannelLut(final LUT lut) { superSetLut(lut); } private void superSetLut(LUT lut) { super.setChannelLut(lut); } @Override public synchronized void updateImage() { superUpdateImage(); } private void superUpdateImage() { //Need to set this field to null, or else an infintie loop can be entered when //The imageJ contrast adjuster is open try { JavaUtils.setRestrictedFieldValue(null, ContrastAdjuster.class, "instance", null); } catch (NoSuchFieldException ex) { ReportingUtils.logError("ImageJ ContrastAdjuster doesn't have field named instance"); } super.updateImage(); } private Runnable updateAndDrawRunnable() { return new Runnable() { @Override public void run() { superUpdateImage(); imageChangedUpdate(); try { GUIUtils.invokeLater(new Runnable() { @Override public void run() { try { JavaUtils.invokeRestrictedMethod(this, ImagePlus.class, "notifyListeners", 2); } catch (Exception ex) { } superDraw(); MMStudioMainFrame.getInstance().getLiveModeTimer().updateFPS(); } }); } catch (Exception e) { ReportingUtils.logError(e); } } }; } @Override public void updateAndDrawWithoutGUIUpdater() { try { GUIUtils.invokeLater(updateAndDrawRunnable()); } catch (Exception e) { ReportingUtils.logError(e); } } @Override public void updateAndDraw() { updater1.post(updateAndDrawRunnable()); } private void superDraw() { if (super.win != null ) { super.getCanvas().repaint(); } } @Override public void draw() { Runnable runnable = new Runnable() { @Override public void run() { imageChangedUpdate(); superDraw(); MMStudioMainFrame.getInstance().getLiveModeTimer().updateFPS(); } }; updater2.post(runnable); } @Override public void drawWithoutUpdate() { Runnable runnable = new Runnable() { @Override public void run() { getWindow().getCanvas().setImageUpdated(); superDraw(); } }; updater3.post(runnable); } } public class MMImagePlus extends ImagePlus implements IMMImagePlus { private GUIUpdater updater1 = new GUIUpdater(), updater2 = new GUIUpdater(); public VirtualAcquisitionDisplay display_; MMImagePlus(String title, ImageStack stack, VirtualAcquisitionDisplay disp) { super(title, stack); display_ = disp; } @Override public String getTitle() { return name_; } @Override public int getImageStackSize() { return super.nChannels * super.nSlices * super.nFrames; } @Override public int getStackSize() { return getImageStackSize(); } @Override public int getNChannelsUnverified() { return super.nChannels; } @Override public int getNSlicesUnverified() { return super.nSlices; } @Override public int getNFramesUnverified() { return super.nFrames; } @Override public void setNChannelsUnverified(int nChannels) { super.nChannels = nChannels; } @Override public void setNSlicesUnverified(int nSlices) { super.nSlices = nSlices; } @Override public void setNFramesUnverified(int nFrames) { super.nFrames = nFrames; } private void superDraw() { if (super.win != null ) { super.getCanvas().repaint(); } } private Runnable drawRunnable() { return new Runnable() { @Override public void run() { imageChangedUpdate(); getWindow().getCanvas().setImageUpdated(); superDraw(); MMStudioMainFrame.getInstance().getLiveModeTimer().updateFPS(); } }; } @Override public void updateAndDrawWithoutGUIUpdater() { try { GUIUtils.invokeLater(drawRunnable()); } catch (Exception e) { ReportingUtils.logError(e); } } @Override public void draw() { updater1.post(drawRunnable()); } @Override public void drawWithoutUpdate() { Runnable runnable = new Runnable() { @Override public void run() { //ImageJ requires (this getWindow().getCanvas().setImageUpdated(); superDraw(); } }; updater2.post(runnable); } } public VirtualAcquisitionDisplay(ImageCache imageCache, AcquisitionEngine eng) { this(imageCache, eng, WindowManager.getUniqueName("Untitled")); } public VirtualAcquisitionDisplay(ImageCache imageCache, AcquisitionEngine eng, String name) { name_ = name; imageCache_ = imageCache; eng_ = eng; pSelector_ = createPositionScrollbar(); mda_ = eng != null; zStackMins_ = new HashMap<Integer, Integer>(); zStackMaxes_ = new HashMap<Integer, Integer>(); this.albumSaved_ = imageCache.isFinished(); } //used for snap and live public VirtualAcquisitionDisplay(ImageCache imageCache, String name) throws MMScriptException { simple_ = true; imageCache_ = imageCache; name_ = name; mda_ = false; this.albumSaved_ = imageCache.isFinished(); MMStudioMainFrame.getInstance().addMMListener(this); } private void startup(JSONObject firstImageMetadata) { // EDTProfiler edtp = new EDTProfiler(); mdPanel_ = MMStudioMainFrame.getInstance().getMetadataPanel(); JSONObject summaryMetadata = getSummaryMetadata(); int numSlices = 1; int numFrames = 1; int numChannels = 1; int numGrayChannels; int numPositions = 1; int width = 0; int height = 0; int numComponents = 1; try { if (firstImageMetadata != null) { width = MDUtils.getWidth(firstImageMetadata); height = MDUtils.getHeight(firstImageMetadata); } else { width = MDUtils.getWidth(summaryMetadata); height = MDUtils.getHeight(summaryMetadata); } numSlices = Math.max(summaryMetadata.getInt("Slices"), 1); numFrames = Math.max(summaryMetadata.getInt("Frames"), 1); int imageChannelIndex; try { imageChannelIndex = MDUtils.getChannelIndex(firstImageMetadata); } catch (Exception e) { imageChannelIndex = -1; } numChannels = Math.max(1 + imageChannelIndex, Math.max(summaryMetadata.getInt("Channels"), 1)); numPositions = Math.max(summaryMetadata.getInt("Positions"), 1); numComponents = Math.max(MDUtils.getNumberOfComponents(summaryMetadata), 1); } catch (Exception e) { ReportingUtils.showError(e); } numComponents_ = numComponents; numGrayChannels = numComponents_ * numChannels; if (imageCache_.getDisplayAndComments() == null || imageCache_.getDisplayAndComments().isNull("Channels")) { imageCache_.setDisplayAndComments(getDisplaySettingsFromSummary(summaryMetadata)); } int type = 0; try { if (firstImageMetadata != null) { type = MDUtils.getSingleChannelType(firstImageMetadata); } else { type = MDUtils.getSingleChannelType(summaryMetadata); } } catch (Exception ex) { ReportingUtils.showError(ex, "Unable to determine acquisition type."); } virtualStack_ = new AcquisitionVirtualStack(width, height, type, null, imageCache_, numGrayChannels * numSlices * numFrames, this); if (summaryMetadata.has("PositionIndex")) { try { virtualStack_.setPositionIndex(MDUtils.getPositionIndex(summaryMetadata)); } catch (Exception ex) { ReportingUtils.logError(ex); } } if (simple_) { controls_ = new SimpleWindowControls(this); } else { controls_ = new HyperstackControls(this); } hyperImage_ = createHyperImage(createMMImagePlus(virtualStack_), numGrayChannels, numSlices, numFrames, virtualStack_, controls_); applyPixelSizeCalibration(hyperImage_); histogramControlsState_ = mdPanel_.getContrastPanel().createDefaultControlsState(); makeHistograms(); createWindow(); //Make sure contrast panel sets up correctly here windowToFront(); cSelector_ = getSelector("c"); if (!simple_) { tSelector_ = getSelector("t"); zSelector_ = getSelector("z"); if (imageCache_.lastAcquiredFrame() > 0) { setNumFrames(1 + imageCache_.lastAcquiredFrame()); } else { setNumFrames(1); } configureAnimationControls(); setNumPositions(numPositions); } // Load contrast settigns if opening datset if (imageCache_.isFinished()) { } updateAndDraw(false); updateWindowTitleAndStatus(); forcePainting(); } /* * Set display to one of three modes: * ij.CompositeImage.COMPOSITE * ij.CompositeImage.GRAYSCALE * ij.CompositeImage.COLOR */ public void setDisplayMode(int displayMode) { mdPanel_.getContrastPanel().setDisplayMode(displayMode); } /////////////////Scrollbars and animation controls section///////////////////////////////////// private void forcePainting() { Runnable forcePaint = new Runnable() { @Override public void run() { if (zAnimationIcon_ != null) { zAnimationIcon_.repaint(); } if (tAnimationIcon_ != null) { tAnimationIcon_.repaint(); } if (tLockIcon_ != null) { tLockIcon_.repaint(); } if (cIcon_ != null) { cIcon_.repaint(); } if (cLockIcon_ != null) { cLockIcon_.repaint(); } if (zLockIcon_ != null) { zLockIcon_.repaint(); } if (pLockIcon_ != null) { pLockIcon_.repaint(); } if (controls_ != null) { controls_.repaint(); } if (pIcon_ != null && pIcon_.isValid()) { pIcon_.repaint(); } } }; try { GUIUtils.invokeAndWait(forcePaint); } catch (Exception ex) { ReportingUtils.logError(ex); } } private void animateSlices(final boolean animate) { if (!animate) { zAnimationTimer_.cancel(); zAnimated_ = false; refreshScrollbarIcons(); moveScrollBarsToLockedPositions(); return; } else { zAnimationTimer_ = new java.util.Timer(); animateFrames(false); final int slicesPerStep; long interval = (long) (1000.0 / framesPerSec_); if (interval < 33) { interval = 33; slicesPerStep = (int) Math.round(framesPerSec_*33.0/1000.0); } else { slicesPerStep = 1; } TimerTask task = new TimerTask() { @Override public void run() { int slice = hyperImage_.getSlice(); if (slice >= zSelector_.getMaximum() - 1) { hyperImage_.setPosition(hyperImage_.getChannel(), 1, hyperImage_.getFrame()); } else { hyperImage_.setPosition(hyperImage_.getChannel(), slice + slicesPerStep, hyperImage_.getFrame()); } } }; zAnimationTimer_.schedule(task, 0, interval); zAnimated_ = true; refreshScrollbarIcons(); } } private void animateFrames(final boolean animate) { if (!animate) { tAnimationTimer_.cancel(); tAnimated_ = false; refreshScrollbarIcons(); moveScrollBarsToLockedPositions(); return; } else { tAnimationTimer_ = new java.util.Timer(); animateSlices(false); final int framesPerStep; long interval = (long) (1000.0 / framesPerSec_); if (interval < 33) { interval = 33; framesPerStep = (int) Math.round(framesPerSec_*33.0/1000.0); } else { framesPerStep = 1; } TimerTask task = new TimerTask() { @Override public void run() { int frame = hyperImage_.getFrame(); int channel = lockedChannel_ == -1 ? hyperImage_.getChannel() : lockedChannel_; int slice = lockedSlice_ == -1 ? hyperImage_.getSlice() : lockedSlice_; if (frame >= tSelector_.getMaximum() - 1) { hyperImage_.setPosition(channel,slice, 1); } else { hyperImage_.setPosition(channel,slice, frame + framesPerStep); } } }; tAnimationTimer_.schedule(task, 0, interval); tAnimated_ = true; refreshScrollbarIcons(); } } private void refreshScrollbarIcons() { if (zAnimationIcon_ != null) { zAnimationIcon_.repaint(); } if (tAnimationIcon_ != null) { tAnimationIcon_.repaint(); } if (zLockIcon_ != null) { zLockIcon_.repaint(); } if (cLockIcon_ != null) { cLockIcon_.repaint(); } if (pLockIcon_ != null) { pLockIcon_.repaint(); } if (tLockIcon_ != null) { tLockIcon_.repaint(); } } private void configureAnimationControls() { if (zAnimationIcon_ != null) { zAnimationIcon_.addMouseListener(new MouseListener() { public void mousePressed(MouseEvent e) { animateSlices(!zAnimated_); } public void mouseClicked(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} }); } if (tAnimationIcon_ != null) { tAnimationIcon_.addMouseListener(new MouseListener() { @Override public void mousePressed(MouseEvent e) { animateFrames(!tAnimated_); } public void mouseClicked(MouseEvent e) {} public void mouseReleased(MouseEvent e) {} public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} }); } } private void setNumPositions(int n) { if (simple_) { return; } pSelector_.setMinimum(0); pSelector_.setMaximum(n); ImageWindow win = hyperImage_.getWindow(); if (n > 1 && pSelector_.getParent() == null) { win.add(pSelector_, win.getComponentCount() - 1); } else if (n <= 1 && pSelector_.getParent() != null) { win.remove(pSelector_); } win.pack(); } private void setNumFrames(int n) { if (simple_) { return; } if (tSelector_ != null) { //ImageWindow win = hyperImage_.getWindow(); ((IMMImagePlus) hyperImage_).setNFramesUnverified(n); tSelector_.setMaximum(n + 1); // JavaUtils.setRestrictedFieldValue(win, StackWindow.class, "nFrames", n); } } private void setNumSlices(int n) { if (simple_) { return; } if (zSelector_ != null) { ((IMMImagePlus) hyperImage_).setNSlicesUnverified(n); zSelector_.setMaximum(n + 1); } } private void setNumChannels(int n) { if (cSelector_ != null) { ((IMMImagePlus) hyperImage_).setNChannelsUnverified(n); cSelector_.setMaximum(1 + n); } } /** * If animation was running prior to showImage, restarts it with sliders at * appropriate positions */ private void restartAnimation(int frame, int slice, boolean framesAnimated, boolean slicesAnimated) { if (framesAnimated) { hyperImage_.setPosition(hyperImage_.getChannel(), hyperImage_.getSlice(), frame+1); animateFrames(true); } else if (slicesAnimated) { hyperImage_.setPosition(hyperImage_.getChannel(), slice+1, hyperImage_.getFrame()); animateSlices(true); } animatedSliceIndex_ = -1; animatedFrameIndex_ = -1; } private void moveScrollBarsToLockedPositions() { int c = lockedChannel_ == -1 ? hyperImage_.getChannel() : lockedChannel_; int s = lockedSlice_ == -1 ? hyperImage_.getSlice() : lockedSlice_; int f = lockedFrame_ == -1 ? hyperImage_.getFrame() : lockedFrame_; hyperImage_.setPosition(c, zAnimated_ ? hyperImage_.getSlice() : s, tAnimated_ ? hyperImage_.getFrame() : f); if (pSelector_ != null && lockedPosition_ > -1) { setPosition(lockedPosition_); } } private void resumeLocksAndAnimationAfterImageArrival() { //if no locks activated or previous animation running, dont execute if (lockedFrame_ == -1 && lockedChannel_ == -1 && lockedSlice_ == -1 && lockedPosition_ == -1 && animatedSliceIndex_ == -1 && animatedFrameIndex_ == -1) { return; } //If no new images have arrived for 500 ms, reset to locked positions if (resetToLockedTimer_ == null) { resetToLockedTimer_ = new Timer(ANIMATION_AND_LOCK_RESTART_DELAY, new ActionListener() { @Override public void actionPerformed(ActionEvent e) { moveScrollBarsToLockedPositions(); restartAnimation(animatedFrameIndex_,animatedSliceIndex_,animatedFrameIndex_ > -1, animatedSliceIndex_ > -1); resetToLockedTimer_.stop(); } }); } if (resetToLockedTimer_.isRunning()) { resetToLockedTimer_.restart(); } else { resetToLockedTimer_.start(); } } private ScrollbarWithLabel getSelector(String label) { // label should be "t", "z", or "c" ScrollbarWithLabel selector = null; ImageWindow win = hyperImage_.getWindow(); int slices = ((IMMImagePlus) hyperImage_).getNSlicesUnverified(); int frames = ((IMMImagePlus) hyperImage_).getNFramesUnverified(); int channels = ((IMMImagePlus) hyperImage_).getNChannelsUnverified(); if (win instanceof StackWindow) { try { //ImageJ bug workaround if (frames > 1 && slices == 1 && channels == 1 && label.equals("t")) { selector = (ScrollbarWithLabel) JavaUtils.getRestrictedFieldValue((StackWindow) win, StackWindow.class, "zSelector"); } else { selector = (ScrollbarWithLabel) JavaUtils.getRestrictedFieldValue((StackWindow) win, StackWindow.class, label + "Selector"); } } catch (NoSuchFieldException ex) { selector = null; ReportingUtils.logError(ex); } } //replace default icon with custom one if (selector != null) { try { Component icon = (Component) JavaUtils.getRestrictedFieldValue( selector, ScrollbarWithLabel.class, "icon"); selector.remove(icon); } catch (NoSuchFieldException ex) { ReportingUtils.logError(ex); } ScrollbarAnimateIcon newIcon = new ScrollbarAnimateIcon(label.charAt(0), this); if (label.equals("z")) { zAnimationIcon_ = newIcon; } else if (label.equals("t")) { tAnimationIcon_ = newIcon; } else if (label.equals("c")) { cIcon_ = newIcon; } selector.add(newIcon, BorderLayout.WEST); addSelectorLockIcon(selector, label); //add adjustment so locks respond to mouse input selector.addAdjustmentListener(new AdjustmentListener() { @Override public void adjustmentValueChanged(AdjustmentEvent e) { if (lockedSlice_ != -1) { lockedSlice_ = zSelector_.getValue(); } if (lockedChannel_ != -1) { lockedChannel_ = cSelector_.getValue(); } } }); selector.invalidate(); selector.validate(); } return selector; } private void addSelectorLockIcon(ScrollbarWithLabel selector, final String label) { final ScrollbarLockIcon icon = new ScrollbarLockIcon(this, label); selector.add(icon, BorderLayout.EAST); if (label.equals("p")) { pLockIcon_ = icon; } else if (label.equals("z")) { zLockIcon_ = icon; } else if (label.equals("c")) { cLockIcon_ = icon; } else if (label.equals("t")) { tLockIcon_ = icon; } icon.addMouseListener(new MouseListener() { public void mouseClicked(MouseEvent e) { if (label.equals("p")) { if (lockedPosition_ == -1) { lockedPosition_ = pSelector_.getValue(); } else { lockedPosition_ = -1; } } else if (label.equals("z")) { if (lockedSlice_ == -1) { if (isZAnimated()) { animateSlices(false); } lockedSlice_ = zSelector_.getValue(); } else { lockedSlice_ = -1; } } else if (label.equals("c")) { if (lockedChannel_ == -1) { lockedChannel_ = cSelector_.getValue(); } else { lockedChannel_ = -1; } } else if (label.equals("t")) { if (lockedFrame_ == -1) { lockedFrame_ = tSelector_.getValue(); } else { lockedFrame_ = -1; } } resumeLocksAndAnimationAfterImageArrival(); refreshScrollbarIcons(); } public void mousePressed(MouseEvent e) {} public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) {} public void mouseExited(MouseEvent e) {} }); } //Used by icon to know hoe to paint itself boolean isScrollbarLocked(String label) { if (label.equals("z")) { return lockedSlice_ > -1; } else if (label.equals("c")) { return lockedChannel_ > -1; } else if (label.equals("p")) { return lockedPosition_ > -1; } else { return lockedFrame_ > -1; } } private ScrollbarWithLabel createPositionScrollbar() { final ScrollbarWithLabel pSelector = new ScrollbarWithLabel(null, 1, 1, 1, 2, 'p') { @Override public void setValue(int v) { if (this.getValue() != v) { super.setValue(v); updatePosition(v); } } }; // prevents scroll bar from blinking on Windows: pSelector.setFocusable(false); pSelector.setUnitIncrement(1); pSelector.setBlockIncrement(1); pSelector.addAdjustmentListener(new AdjustmentListener() { @Override public void adjustmentValueChanged(AdjustmentEvent e) { if (lockedPosition_ != -1) { lockedPosition_ = pSelector_.getValue(); } updatePosition(pSelector.getValue()); } }); if (pSelector != null) { try { Component icon = (Component) JavaUtils.getRestrictedFieldValue( pSelector, ScrollbarWithLabel.class, "icon"); pSelector.remove(icon); } catch (NoSuchFieldException ex) { ReportingUtils.logError(ex); } pIcon_ = new ScrollbarAnimateIcon('p', this); pSelector.add(pIcon_, BorderLayout.WEST); addSelectorLockIcon(pSelector, "p"); pSelector.invalidate(); pSelector.validate(); } return pSelector; } ////////End of animation controls and scrollbars section/////////////////////// /** * Allows bypassing the prompt to Save * @param promptToSave boolean flag */ public void promptToSave(boolean promptToSave) { promptToSave_ = promptToSave; } /* * Method required by ImageCacheListener */ @Override public synchronized void imageReceived(final TaggedImage taggedImage) { updateDisplay(taggedImage, false); } /* * Method required by ImageCacheListener */ @Override public void imagingFinished(String path) { updateDisplay(null, true); updateAndDraw(); if (!(eng_ != null && eng_.abortRequested())) { updateWindowTitleAndStatus(); } } private void updateDisplay(TaggedImage taggedImage, boolean finalUpdate) { try { long t = System.currentTimeMillis(); JSONObject tags; if (taggedImage != null) { tags = taggedImage.tags; } else { tags = imageCache_.getLastImageTags(); } if (tags == null) { return; } int frame = MDUtils.getFrameIndex(tags); int ch = MDUtils.getChannelIndex(tags); int slice = MDUtils.getSliceIndex(tags); int position = MDUtils.getPositionIndex(tags); boolean slowUpdates; if (histogramControlsState_ == null) { slowUpdates = false; } else { slowUpdates = histogramControlsState_.slowDisplayUpdates; } int updateTime = slowUpdates ? SLOW_UPDATE_TIME : 30; //update display if: final update, frame is 0, more than 30 ms since last update, //last channel for given frame/slice/position, or final slice and channel for first frame and position boolean show = finalUpdate || frame == 0 || (Math.abs(t - lastDisplayTime_) > updateTime) || (!slowUpdates && ch == getNumChannels() - 1 && lastFrameShown_ == frame && lastSliceShown_ == slice && lastPositionShown_ == position) || (slice == getNumSlices() - 1 && frame == 0 && position == 0 && ch == getNumChannels() - 1); if (slowUpdates && ch != getNumChannels() - 1) { //only do slowupdates when all channels present show = false; } if (show) { showImage(tags, true); lastFrameShown_ = frame; lastSliceShown_ = slice; lastPositionShown_ = position; lastDisplayTime_ = t; forceImagePaint(); } } catch (Exception e) { ReportingUtils.logError(e); } } private void forceImagePaint() { hyperImage_.getWindow().getCanvas().repaint(); } public int rgbToGrayChannel(int channelIndex) { try { if (MDUtils.getNumberOfComponents(imageCache_.getSummaryMetadata()) == 3) { return channelIndex * 3; } return channelIndex; } catch (Exception ex) { ReportingUtils.logError(ex); return 0; } } public int grayToRGBChannel(int grayIndex) { try { if (imageCache_ != null) { if (imageCache_.getSummaryMetadata() != null) if (MDUtils.getNumberOfComponents(imageCache_.getSummaryMetadata()) == 3) { return grayIndex / 3; } } return grayIndex; } catch (Exception ex) { ReportingUtils.logError(ex); return 0; } } public static JSONObject getDisplaySettingsFromSummary(JSONObject summaryMetadata) { try { JSONObject displaySettings = new JSONObject(); JSONArray chColors = MDUtils.getJSONArrayMember(summaryMetadata, "ChColors"); JSONArray chNames = MDUtils.getJSONArrayMember(summaryMetadata, "ChNames"); JSONArray chMaxes, chMins; if ( summaryMetadata.has("ChContrastMin")) { chMins = MDUtils.getJSONArrayMember(summaryMetadata, "ChContrastMin"); } else { chMins = new JSONArray(); for (int i = 0; i < chNames.length(); i++) chMins.put(0); } if ( summaryMetadata.has("ChContrastMax")) { chMaxes = MDUtils.getJSONArrayMember(summaryMetadata, "ChContrastMax"); } else { int max = 65536; if (summaryMetadata.has("BitDepth")) max = (int) (Math.pow(2, summaryMetadata.getInt("BitDepth"))-1); chMaxes = new JSONArray(); for (int i = 0; i < chNames.length(); i++) chMaxes.put(max); } int numComponents = MDUtils.getNumberOfComponents(summaryMetadata); JSONArray channels = new JSONArray(); if (numComponents > 1) //RGB { int rgbChannelBitDepth; try { rgbChannelBitDepth = MDUtils.getBitDepth(summaryMetadata); } catch (Exception e) { rgbChannelBitDepth = summaryMetadata.getString("PixelType").endsWith("32") ? 8 : 16; } for (int k = 0; k < 3; k++) { JSONObject channelObject = new JSONObject(); channelObject.put("Color", rgb[k].getRGB()); channelObject.put("Name", rgbNames[k]); channelObject.put("Gamma", 1.0); channelObject.put("Min", 0); channelObject.put("Max", Math.pow(2, rgbChannelBitDepth) - 1); channels.put(channelObject); } } else { for (int k = 0; k < chNames.length(); ++k) { String name = (String) chNames.get(k); int color = 0; if (k < chColors.length()) color = chColors.getInt(k); int min = 0; if (k < chMins.length()) min = chMins.getInt(k); int max = chMaxes.getInt(0); if (k < chMaxes.length()) max = chMaxes.getInt(k); JSONObject channelObject = new JSONObject(); channelObject.put("Color", color); channelObject.put("Name", name); channelObject.put("Gamma", 1.0); channelObject.put("Min", min); channelObject.put("Max", max); channels.put(channelObject); } } displaySettings.put("Channels", channels); JSONObject comments = new JSONObject(); String summary = ""; try { summary = summaryMetadata.getString("Comment"); } catch (JSONException ex) { summaryMetadata.put("Comment", ""); } comments.put("Summary", summary); displaySettings.put("Comments", comments); return displaySettings; } catch (Exception e) { ReportingUtils.showError("Summary metadata not found or corrupt. Is this a Micro-Manager dataset?"); return null; } } /** * Sets ImageJ pixel size calibration * @param hyperImage */ private void applyPixelSizeCalibration(final ImagePlus hyperImage) { try { JSONObject summary = getSummaryMetadata(); double pixSizeUm = summary.getDouble("PixelSize_um"); if (pixSizeUm > 0) { Calibration cal = new Calibration(); cal.setUnit("um"); cal.pixelWidth = pixSizeUm; cal.pixelHeight = pixSizeUm; String intMs = "Interval_ms"; if (summary.has(intMs)) cal.frameInterval = summary.getDouble(intMs) / 1000.0; String zStepUm = "z-step_um"; if (summary.has(zStepUm)) cal.pixelDepth = summary.getDouble(zStepUm); hyperImage.setCalibration(cal); } } catch (JSONException ex) { // no pixelsize defined. Nothing to do } } public ImagePlus getHyperImage() { return hyperImage_; } public int getStackSize() { if (hyperImage_ == null) { return -1; } int s = hyperImage_.getNSlices(); int c = hyperImage_.getNChannels(); int f = hyperImage_.getNFrames(); if ((s > 1 && c > 1) || (c > 1 && f > 1) || (f > 1 && s > 1)) { return s * c * f; } return Math.max(Math.max(s, c), f); } private void imageChangedWindowUpdate() { if (hyperImage_ != null && hyperImage_.isVisible()) { TaggedImage ti = virtualStack_.getTaggedImage(hyperImage_.getCurrentSlice()); if (ti != null) { controls_.newImageUpdate(ti.tags); } } } public void updateAndDraw() { updateAndDraw(true); } public void updateAndDraw(boolean useGUIUpdater) { if (hyperImage_ != null && hyperImage_.isVisible()) { if (!useGUIUpdater) { ((IMMImagePlus) hyperImage_).updateAndDrawWithoutGUIUpdater(); } else { hyperImage_.updateAndDraw(); } } } public void updateWindowTitleAndStatus() { if (simple_) { int mag = (int) (100 * hyperImage_.getCanvas().getMagnification()); String title = hyperImage_.getTitle() + " ("+mag+"%)"; hyperImage_.getWindow().setTitle(title); return; } if (controls_ == null) { return; } String status = ""; final AcquisitionEngine eng = eng_; if (eng != null) { if (acquisitionIsRunning()) { if (!abortRequested()) { controls_.acquiringImagesUpdate(true); if (isPaused()) { status = "paused"; } else { status = "running"; } } else { controls_.acquiringImagesUpdate(false); status = "interrupted"; } } else { controls_.acquiringImagesUpdate(false); if (!status.contentEquals("interrupted")) { if (eng.isFinished()) { status = "finished"; eng_ = null; } } } status += ", "; if (eng.isFinished()) { eng_ = null; finished_ = true; } } else { if (finished_ == true) { status = "finished, "; } controls_.acquiringImagesUpdate(false); } if (isDiskCached() || albumSaved_) { status += "on disk"; } else { status += "not yet saved"; } controls_.imagesOnDiskUpdate(imageCache_.getDiskLocation() != null); String path = isDiskCached() ? new File(imageCache_.getDiskLocation()).getName() : name_; if (hyperImage_.isVisible()) { int mag = (int) (100 * hyperImage_.getCanvas().getMagnification()); hyperImage_.getWindow().setTitle(path + " (" + status + ") (" + mag + "%)" ); } } private void windowToFront() { if (hyperImage_ == null || hyperImage_.getWindow() == null) { return; } hyperImage_.getWindow().toFront(); } /** * Displays tagged image in the multi-D viewer * Will wait for the screen update * * @param taggedImg * @throws Exception */ public void showImage(TaggedImage taggedImg) throws Exception { showImage(taggedImg, true); } /** * Displays tagged image in the multi-D viewer * Optionally waits for the display to draw the image * * * @param taggedImg * @throws Exception */ public void showImage(TaggedImage taggedImg, boolean waitForDisplay) throws InterruptedException, InvocationTargetException { showImage(taggedImg.tags, waitForDisplay); } public void showImage(final JSONObject tags, boolean waitForDisplay) throws InterruptedException, InvocationTargetException { updateWindowTitleAndStatus(); if (tags == null) { return; } if (hyperImage_ == null) { GUIUtils.invokeAndWait(new Runnable() { @Override public void run() { try { startup(tags); } catch (Exception e) { ReportingUtils.logError(e); } } }); } int channel = 0, frame = 0, slice = 0, position = 0, superChannel = 0; try { frame = MDUtils.getFrameIndex(tags); slice = MDUtils.getSliceIndex(tags); channel = MDUtils.getChannelIndex(tags); position = MDUtils.getPositionIndex(tags); superChannel = this.rgbToGrayChannel(MDUtils.getChannelIndex(tags)); } catch (Exception ex) { ReportingUtils.logError(ex); } //This block allows animation to be reset to where it was before images were added if (isTAnimated()) { animatedFrameIndex_ = hyperImage_.getFrame(); animateFrames(false); } if (isZAnimated()) { animatedSliceIndex_ = hyperImage_.getSlice(); animateSlices(false); } //make sure pixels get properly set if (hyperImage_ != null && frame == 0) { IMMImagePlus img = (IMMImagePlus) hyperImage_; if (img.getNChannelsUnverified() == 1) { if (img.getNSlicesUnverified() == 1) { hyperImage_.getProcessor().setPixels(virtualStack_.getPixels(1)); } } else if (hyperImage_ instanceof MMCompositeImage) { //reset rebuilds each of the channel ImageProcessors with the correct pixels //from AcquisitionVirtualStack MMCompositeImage ci = ((MMCompositeImage) hyperImage_); ci.reset(); //This line is neccessary for image processor to have correct pixels in grayscale mode ci.getProcessor().setPixels(virtualStack_.getPixels(ci.getCurrentSlice())); } } else if (hyperImage_ instanceof MMCompositeImage) { MMCompositeImage ci = ((MMCompositeImage) hyperImage_); ci.reset(); } if (cSelector_ != null) { if (cSelector_.getMaximum() <= (1 + superChannel)) { this.setNumChannels(1 + superChannel); ((CompositeImage) hyperImage_).reset(); //JavaUtils.invokeRestrictedMethod(hyperImage_, CompositeImage.class, // "setupLuts", 1 + superChannel, Integer.TYPE); } } initializeContrast(channel, slice); if (!simple_) { if (tSelector_ != null) { if (tSelector_.getMaximum() <= (1 + frame)) { this.setNumFrames(1 + frame); } } if (position + 1 > getNumPositions()) { setNumPositions(position + 1); } setPosition(position); hyperImage_.setPosition(1 + superChannel, 1 + slice, 1 + frame); } boolean useGUIUpdater = frame != 0 || simple_; if (simple_) { simpleWinImagesReceived_++; //Make sure update and draw gets called without GUI updater to initilze new snap win correctly int numChannels; try { numChannels = MDUtils.getNumChannels(getSummaryMetadata()); } catch (Exception e) { numChannels = 7; } if ( simpleWinImagesReceived_ <= numChannels) { useGUIUpdater = false; } } updateAndDraw(useGUIUpdater); resumeLocksAndAnimationAfterImageArrival(); if (cSelector_ != null) { if (histograms_.getNumberOfChannels() < (1 + superChannel)) { if (histograms_ != null) { histograms_.setupChannelControls(imageCache_); } } } } /* * Live/snap should load window contrast settings * MDA should autoscale on first image * Not called when opening a dataset because stored settings are loaded automatically */ private void initializeContrast(final int channel, final int slice) { Runnable autoscaleOrLoadContrast = new Runnable() { @Override public void run() { if (!newDisplay_) { return; } if (simple_) { //Snap/live if (hyperImage_ instanceof MMCompositeImage && ((MMCompositeImage) hyperImage_).getNChannelsUnverified() - 1 != channel) { return; } loadSimpleWinContrastWithoutDraw(); } else if (mda_) { //Multi D acquisition IMMImagePlus immImg = ((IMMImagePlus) hyperImage_); if (immImg.getNSlicesUnverified() > 1) { //Z stacks autoscaleOverStackWithoutDraw(hyperImage_, channel, slice, zStackMins_, zStackMaxes_); if (channel != immImg.getNChannelsUnverified() - 1 || slice != immImg.getNSlicesUnverified() - 1) { return; //don't set new display to false until all channels autoscaled } } else { //No z stacks if (channel +1 != getNumChannels()) return; autoscaleWithoutDraw(); } } else //Acquire button if (hyperImage_ instanceof MMCompositeImage) { if (((MMCompositeImage) hyperImage_).getNChannelsUnverified() - 1 != channel) { return; } autoscaleWithoutDraw(); } else { autoscaleWithoutDraw(); // else do nothing because contrast automatically loaded from cache } newDisplay_ = false; } }; if (!SwingUtilities.isEventDispatchThread()) { SwingUtilities.invokeLater(autoscaleOrLoadContrast); } else { autoscaleOrLoadContrast.run(); } } private void loadSimpleWinContrastWithoutDraw() { int n = getImageCache().getNumChannels(); ContrastSettings c; for (int i = 0; i < n; i++) { c = MMStudioMainFrame.getInstance().loadSimpleContrastSettigns(getImageCache().getPixelType(), i); histograms_.setChannelContrast(i, c.min, c.max, c.gamma); } histograms_.applyLUTToImage(); } private void autoscaleWithoutDraw() { if (histograms_ != null) { histograms_.calcAndDisplayHistAndStats(true); histograms_.autostretch(); histograms_.applyLUTToImage(); } } private void autoscaleOverStackWithoutDraw(ImagePlus img, int channel, int slice, HashMap<Integer, Integer> mins, HashMap<Integer, Integer> maxes) { int nChannels = ((VirtualAcquisitionDisplay.IMMImagePlus) img).getNChannelsUnverified(); int bytes = img.getBytesPerPixel(); int pixMin, pixMax; if (mins.containsKey(channel)) { pixMin = mins.get(channel); pixMax = maxes.get(channel); } else { pixMax = 0; pixMin = (int) (Math.pow(2, 8 * bytes) - 1); } int flatIndex = 1 + channel + slice * nChannels; if (bytes == 2) { short[] pixels = (short[]) img.getStack().getPixels(flatIndex); for (short value : pixels) { //unsign short int val = value & 0xffff; if (val < pixMin) { pixMin = val; } if (val > pixMax) { pixMax = val; } } } else if (bytes == 1) { byte[] pixels = (byte[]) img.getStack().getPixels(flatIndex); for (byte value : pixels) { //unsign byte int val = value & 0xff; if (val < pixMin) { pixMin = val; } if (val > pixMax) { pixMax = val; } } } //autoscale the channel histograms_.setChannelContrast(channel, pixMin, pixMax, 1.0); histograms_.applyLUTToImage(); mins.put(channel, pixMin); maxes.put(channel, pixMax); } private void updatePosition(int p) { if (simple_) { return; } virtualStack_.setPositionIndex(p); if (!hyperImage_.isComposite()) { Object pixels = virtualStack_.getPixels(hyperImage_.getCurrentSlice()); hyperImage_.getProcessor().setPixels(pixels); } else { CompositeImage ci = (CompositeImage) hyperImage_; if (ci.getMode() == CompositeImage.COMPOSITE) { for (int i = 0; i < ((MMCompositeImage) ci).getNChannelsUnverified(); i++) { //Dont need to set pixels if processor is null because it will get them from stack automatically if (ci.getProcessor(i + 1) != null) ci.getProcessor(i + 1).setPixels(virtualStack_.getPixels(ci.getCurrentSlice() - ci.getChannel() + i + 1)); } } ci.getProcessor().setPixels(virtualStack_.getPixels(hyperImage_.getCurrentSlice())); } //need to call this even though updateAndDraw also calls it to get autostretch to work properly imageChangedUpdate(); updateAndDraw(); } public void setPosition(int p) { if (simple_) { return; } pSelector_.setValue(p); } public void setSliceIndex(int i) { if (simple_) { return; } final int f = hyperImage_.getFrame(); final int c = hyperImage_.getChannel(); hyperImage_.setPosition(c, i + 1, f); } public int getSliceIndex() { return hyperImage_.getSlice() - 1; } boolean pause() { if (eng_ != null) { if (eng_.isPaused()) { eng_.setPause(false); } else { eng_.setPause(true); } updateWindowTitleAndStatus(); return (eng_.isPaused()); } return false; } boolean abort() { if (eng_ != null) { if (eng_.abortRequest()) { updateWindowTitleAndStatus(); return true; } } return false; } public boolean acquisitionIsRunning() { if (eng_ != null) { return eng_.isAcquisitionRunning(); } else { return false; } } public long getNextWakeTime() { return eng_.getNextWakeTime(); } public boolean abortRequested() { if (eng_ != null) { return eng_.abortRequested(); } else { return false; } } private boolean isPaused() { if (eng_ != null) { return eng_.isPaused(); } else { return false; } } public void albumChanged() { albumSaved_ = false; } private Class createSaveTypePopup() { if (saveTypePopup_ != null) { saveTypePopup_.setVisible(false); saveTypePopup_ = null; } final JPopupMenu menu = new JPopupMenu(); saveTypePopup_ = menu; JMenuItem single = new JMenuItem("Save as separate image files"); JMenuItem multi = new JMenuItem("Save as image stack file"); JMenuItem cancel = new JMenuItem("Cancel"); menu.add(single); menu.add(multi); menu.addSeparator(); menu.add(cancel); final AtomicInteger ai = new AtomicInteger(-1); cancel.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ai.set(0); } }); single.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ai.set(1); } }); multi.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { ai.set(2); } }); MouseListener highlighter = new MouseListener() { @Override public void mouseClicked(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) {} @Override public void mouseReleased(MouseEvent e) {} @Override public void mouseEntered(MouseEvent e) { ((JMenuItem) e.getComponent()).setArmed(true); } @Override public void mouseExited(MouseEvent e) { ((JMenuItem) e.getComponent()).setArmed(false); } }; single.addMouseListener(highlighter); multi.addMouseListener(highlighter); cancel.addMouseListener(highlighter); Point mouseLocation = MouseInfo.getPointerInfo().getLocation(); menu.show(null, mouseLocation.x, mouseLocation.y); while (ai.get() == -1) { try { Thread.sleep(10); } catch (InterruptedException ex) {} if (!menu.isVisible()) { return null; } } menu.setVisible(false); saveTypePopup_ = null; if (ai.get() == 0) { return null; } else if (ai.get() == 1) { return TaggedImageStorageDiskDefault.class; } else { return TaggedImageStorageMultipageTiff.class; } } boolean saveAs() { return saveAs(null,true); } boolean saveAs(boolean pointToNewStorage) { return saveAs(null, pointToNewStorage); } private boolean saveAs(Class storageClass, boolean pointToNewStorage) { if (eng_ != null && eng_.isAcquisitionRunning()) { JOptionPane.showMessageDialog(null, "Data can not be saved while acquisition is running."); return false; } if (storageClass == null) { storageClass = createSaveTypePopup(); } if (storageClass == null) { return false; } String prefix; String root; for (;;) { File f = FileDialogs.save(hyperImage_.getWindow(), "Please choose a location for the data set", MMStudioMainFrame.MM_DATA_SET); if (f == null) // Canceled. { return false; } prefix = f.getName(); root = new File(f.getParent()).getAbsolutePath(); if (f.exists()) { ReportingUtils.showMessage(prefix + " is write only! Please choose another name."); } else { break; } } try { if (getSummaryMetadata() != null) { getSummaryMetadata().put("Prefix", prefix); } TaggedImageStorage newFileManager = (TaggedImageStorage) storageClass.getConstructor( String.class, Boolean.class, JSONObject.class).newInstance( root + "/" + prefix, true, getSummaryMetadata()); if (pointToNewStorage) { albumSaved_ = true; } imageCache_.saveAs(newFileManager, pointToNewStorage); } catch (Exception ex) { ReportingUtils.showError(ex, "Failed to save file"); } MMStudioMainFrame.getInstance().setAcqDirectory(root); updateWindowTitleAndStatus(); return true; } final public MMImagePlus createMMImagePlus(AcquisitionVirtualStack virtualStack) { MMImagePlus img = new MMImagePlus(imageCache_.getDiskLocation(), virtualStack, this); FileInfo fi = new FileInfo(); fi.width = virtualStack.getWidth(); fi.height = virtualStack.getHeight(); fi.fileName = virtualStack.getDirectory(); fi.url = null; img.setFileInfo(fi); return img; } final public ImagePlus createHyperImage(MMImagePlus mmIP, int channels, int slices, int frames, final AcquisitionVirtualStack virtualStack, DisplayControls hc) { final ImagePlus hyperImage; mmIP.setNChannelsUnverified(channels); mmIP.setNFramesUnverified(frames); mmIP.setNSlicesUnverified(slices); if (channels > 1) { hyperImage = new MMCompositeImage(mmIP, imageCache_.getDisplayMode()); hyperImage.setOpenAsHyperStack(true); } else { hyperImage = mmIP; mmIP.setOpenAsHyperStack(true); } return hyperImage; } public void liveModeEnabled(boolean enabled) { if (simple_) { controls_.acquiringImagesUpdate(enabled); } } private void createWindow() { final DisplayWindow win = new DisplayWindow(hyperImage_); win.getCanvas().addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent me) { } //used to store preferred zoom @Override public void mousePressed(MouseEvent me) { if (Toolbar.getToolId() == 11) {//zoom tool selected storeWindowSizeAfterZoom(win); } updateWindowTitleAndStatus(); } //updates the histogram after an ROI is drawn @Override public void mouseReleased(MouseEvent me) { hyperImage_.updateAndDraw(); } @Override public void mouseEntered(MouseEvent me) { } @Override public void mouseExited(MouseEvent me) { } }); win.setBackground(MMStudioMainFrame.getInstance().getBackgroundColor()); MMStudioMainFrame.getInstance().addMMBackgroundListener(win); win.add(controls_); win.pack(); if (simple_) { win.setLocation(prefs_.getInt(SIMPLE_WIN_X, 0), prefs_.getInt(SIMPLE_WIN_Y, 0)); } //Set magnification zoomToPreferredSize(win); mdPanel_.displayChanged(win); imageChangedUpdate(); } public void storeWindowSizeAfterZoom(ImageWindow win) { if (simple_) { snapWinMag_ = win.getCanvas().getMagnification(); } } private void zoomToPreferredSize(DisplayWindow win) { Point location = win.getLocation(); win.setLocation(new Point(0,0)); double mag; if (simple_ && snapWinMag_ != -1) { mag = snapWinMag_; } else { mag = MMStudioMainFrame.getInstance().getPreferredWindowMag(); } ImageCanvas canvas = win.getCanvas(); if (mag < canvas.getMagnification()) { while (mag < canvas.getMagnification()) { canvas.zoomOut(canvas.getWidth() / 2, canvas.getHeight() / 2); } } else if (mag > canvas.getMagnification()) { while (mag > canvas.getMagnification()) { canvas.zoomIn(canvas.getWidth() / 2, canvas.getHeight() / 2); } } //Make sure the window is fully on the screen Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Point newLocation = new Point(location.x,location.y); if (newLocation.x + win.getWidth() > screenSize.width && win.getWidth() < screenSize.width) { newLocation.x = screenSize.width - win.getWidth(); } if (newLocation.y + win.getHeight() > screenSize.height && win.getHeight() < screenSize.height) { newLocation.y = screenSize.height - win.getHeight(); } win.setLocation(newLocation); } public JSONObject getCurrentMetadata() { try { if (hyperImage_ != null) { TaggedImage image = virtualStack_.getTaggedImage(hyperImage_.getChannel()-1, hyperImage_.getSlice()-1, hyperImage_.getFrame()-1); if (image != null) { return image.tags; } else { return null; } } else { return null; } } catch (NullPointerException ex) { return null; } } public int getCurrentPosition() { return virtualStack_.getPositionIndex(); } public int getNumSlices() { if (simple_) { return 1; } return ((IMMImagePlus) hyperImage_).getNSlicesUnverified(); } public int getNumFrames() { if (simple_) { return 1; } return ((IMMImagePlus) hyperImage_).getNFramesUnverified(); } public int getNumPositions() { if (simple_) { return 1; } return pSelector_.getMaximum(); } public ImagePlus getImagePlus() { return hyperImage_; } public ImageCache getImageCache() { return imageCache_; } public ImagePlus getImagePlus(int position) { ImagePlus iP = new ImagePlus(); iP.setStack(virtualStack_); iP.setDimensions(numComponents_ * getNumChannels(), getNumSlices(), getNumFrames()); iP.setFileInfo(hyperImage_.getFileInfo()); return iP; } public void setComment(String comment) throws MMScriptException { try { getSummaryMetadata().put("Comment", comment); } catch (Exception ex) { ReportingUtils.logError(ex); } } public final JSONObject getSummaryMetadata() { return imageCache_.getSummaryMetadata(); } /* public final JSONObject getImageMetadata(int channel, int slice, int frame, int position) { return imageCache_.getImageTags(channel, slice, frame, position); } */ public void close() { if (hyperImage_ != null) { hyperImage_.getWindow().windowClosing(null); hyperImage_.close(); } } public synchronized boolean windowClosed() { if (hyperImage_ != null) { ImageWindow win = hyperImage_.getWindow(); return (win == null || win.isClosed()); } return true; } public void showFolder() { if (isDiskCached()) { try { File location = new File(imageCache_.getDiskLocation()); if (JavaUtils.isWindows()) { Runtime.getRuntime().exec("Explorer /n,/select," + location.getAbsolutePath()); } else if (JavaUtils.isMac()) { if (!location.isDirectory()) { location = location.getParentFile(); } Runtime.getRuntime().exec("open " + location.getAbsolutePath()); } } catch (IOException ex) { ReportingUtils.logError(ex); } } } public void setPlaybackFPS(double fps) { framesPerSec_ = fps; if (zAnimated_) { animateSlices(false); animateSlices(true); } else if (tAnimated_) { animateFrames(false); animateFrames(true); } } public double getPlaybackFPS() { return framesPerSec_; } public boolean isZAnimated() { return zAnimated_; } public boolean isTAnimated() { return tAnimated_; } public boolean isAnimated() { return isTAnimated() || isZAnimated(); } public String getSummaryComment() { return imageCache_.getComment(); } public void setSummaryComment(String comment) { imageCache_.setComment(comment); } void setImageComment(String comment) { imageCache_.setImageComment(comment, getCurrentMetadata()); } String getImageComment() { try { return imageCache_.getImageComment(getCurrentMetadata()); } catch (NullPointerException ex) { return ""; } } public boolean isDiskCached() { ImageCache imageCache = imageCache_; if (imageCache == null) { return false; } else { return imageCache.getDiskLocation() != null; } } public void show() { if (hyperImage_ == null) { try { GUIUtils.invokeAndWait(new Runnable() { @Override public void run() { startup(null); } }); } catch (Exception ex) { ReportingUtils.logError(ex); } } hyperImage_.show(); hyperImage_.getWindow().toFront(); } public int getNumChannels() { return ((IMMImagePlus) hyperImage_).getNChannelsUnverified(); } public int getNumGrayChannels() { return getNumChannels(); } public void setWindowTitle(String name) { name_ = name; updateWindowTitleAndStatus(); } public boolean isSimpleDisplay() { return simple_; } public void displayStatusLine(String status) { controls_.setStatusLabel(status); } public void setChannelContrast(int channelIndex, int min, int max, double gamma) { histograms_.setChannelContrast(channelIndex, min, max, gamma); histograms_.applyLUTToImage(); drawWithoutUpdate(); } public void updateChannelNamesAndColors() { if (histograms_ != null && histograms_ instanceof MultiChannelHistograms) { ((MultiChannelHistograms) histograms_).updateChannelNamesAndColors(); } } public void setChannelHistogramDisplayMax(int channelIndex, int histMax) { histograms_.setChannelHistogramDisplayMax(channelIndex, histMax); } /* * called just before image is drawn. Notifies metadata panel to update * metadata or comments if this display is the active window. Notifies histograms * that image is change to create appropriate LUTs and to draw themselves if this * is the active window */ private void imageChangedUpdate() { if (updatePixelSize_.get()) { try { JSONObject summary = getSummaryMetadata(); if (summary != null) { summary.put("PixelSize_um", Double.longBitsToDouble(newPixelSize_.get())); } if (hyperImage_ != null) { applyPixelSizeCalibration(hyperImage_); } } catch (JSONException ex) { ReportingUtils.logError("Error in imageCHangedUpdate in VirtualAcquisitionDisplay.java"); } updatePixelSize_.set(false); } if (histograms_ != null) { histograms_.imageChanged(); } if (isActiveDisplay()) { mdPanel_.imageChangedUpdate(this); mdPanel_.redrawSizeBar(); } imageChangedWindowUpdate(); //used to update status line } public boolean isActiveDisplay() { if (hyperImage_ == null || hyperImage_.getWindow() == null) return false; if (hyperImage_.getWindow() == mdPanel_.getCurrentWindow() ) return true; return false; } public void drawWithoutUpdate() { if (hyperImage_ != null) { ((IMMImagePlus) hyperImage_).drawWithoutUpdate(); } } private void makeHistograms() { if (getNumChannels() == 1 ) histograms_ = new SingleChannelHistogram(this); else histograms_ = new MultiChannelHistograms(this); } public Histograms getHistograms() { return histograms_; } public HistogramControlsState getHistogramControlsState() { return histogramControlsState_; } public void disableAutoStretchCheckBox() { if (isActiveDisplay() ) { mdPanel_.getContrastPanel().disableAutostretch(); } else { histogramControlsState_.autostretch = false; } } /* * used to store contrast settings for snap live window */ private void saveSimpleWinSettings() { ImageCache cache = getImageCache(); String pixelType = cache.getPixelType(); int numCh = cache.getNumChannels(); for (int i = 0; i < numCh; i++) { int min = cache.getChannelMin(i); int max = cache.getChannelMax(i); double gamma = cache.getChannelGamma(i); MMStudioMainFrame.getInstance().saveSimpleContrastSettings(new ContrastSettings(min, max, gamma), i, pixelType); } } public ContrastSettings getChannelContrastSettings(int channel) { return histograms_.getChannelContrastSettings(channel); } public class DisplayWindow extends StackWindow { private boolean windowClosingDone_ = false; private boolean closed_ = false; public DisplayWindow(ImagePlus ip) { super(ip); } @Override public boolean close() { windowClosing(null); return closed_; } @Override public void windowClosing(WindowEvent e) { if (windowClosingDone_) { return; } if (eng_ != null && eng_.isAcquisitionRunning()) { if (!abort()) { return; } } if (imageCache_.getDiskLocation() == null && promptToSave_ && !albumSaved_) { String[] options = {"Save single","Save multi","No","Cancel"}; int result = JOptionPane.showOptionDialog(this, "This data set has not yet been saved. " + "Do you want to save it?\nData can be saved as single-image files or multi-image files.", "Micro-Manager",JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0]); if (result == 0) { if (!saveAs(TaggedImageStorageDiskDefault.class, true)) { return; } } else if (result == 1) { if (!saveAs(TaggedImageStorageMultipageTiff.class, true)) { return; } } else if (result == 3) { return; } } if (simple_ && hyperImage_ != null && hyperImage_.getWindow() != null && hyperImage_.getWindow().getLocation() != null) { Point loc = hyperImage_.getWindow().getLocation(); prefs_.putInt(SIMPLE_WIN_X, loc.x); prefs_.putInt(SIMPLE_WIN_Y, loc.y); saveSimpleWinSettings(); } if (imageCache_ != null) { imageCache_.close(); } removeMeFromAcquisitionManager(MMStudioMainFrame.getInstance()); if (!closed_) { try { super.close(); } catch (NullPointerException ex) { ReportingUtils.showError(ex, "Null pointer error in ImageJ code while closing window"); } } //Call this because for some reason WindowManager doesnt always fire mdPanel_.displayChanged(null); zAnimationTimer_.cancel(); tAnimationTimer_.cancel(); super.windowClosing(e); MMStudioMainFrame.getInstance().removeMMBackgroundListener(this); windowClosingDone_ = true; closed_ = true; } /* * Removes the VirtualAcquisitionDisplay from the Acquisition Manager. */ private void removeMeFromAcquisitionManager(MMStudioMainFrame gui) { for (String name : gui.getAcquisitionNames()) { try { if (gui.getAcquisition(name).getAcquisitionWindow() == VirtualAcquisitionDisplay.this) { gui.closeAcquisition(name); } } catch (Exception ex) { ReportingUtils.logError(ex); } } } @Override public void windowClosed(WindowEvent E) { try { // NS: I do not know why this line was here. It causes problems since the windowClosing // function now will often run twice //this.windowClosing(E); super.windowClosed(E); } catch (NullPointerException ex) { ReportingUtils.showError(ex, "Null pointer error in ImageJ code while closing window"); } } @Override public void windowActivated(WindowEvent e) { if (!isClosed()) { super.windowActivated(e); } } @Override public void setAnimate(boolean b) { if (((IMMImagePlus) hyperImage_).getNFramesUnverified() > 1) { animateFrames(b); } else { animateSlices(b); } } @Override public boolean getAnimate() { return isAnimated(); } }; }
package org.micromanager.acquisition; import org.micromanager.api.ImageCacheListener; import ij.ImageStack; import ij.process.LUT; import java.awt.event.AdjustmentEvent; import ij.CompositeImage; import ij.ImagePlus; import ij.gui.ImageWindow; import ij.gui.ScrollbarWithLabel; import ij.gui.StackWindow; import ij.io.FileInfo; import ij.measure.Calibration; import ij.plugin.Animator; import ij.process.ImageProcessor; import java.awt.Color; import java.awt.Point; import java.awt.event.AdjustmentListener; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import java.util.prefs.Preferences; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import mmcorej.TaggedImage; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.micromanager.MMStudioMainFrame; import org.micromanager.api.AcquisitionEngine; import org.micromanager.api.ImageCache; import org.micromanager.utils.FileDialogs; import org.micromanager.utils.ImageUtils; import org.micromanager.utils.JavaUtils; import org.micromanager.utils.MDUtils; import org.micromanager.utils.MMException; import org.micromanager.utils.MMScriptException; import org.micromanager.utils.ReportingUtils; /** * * @author arthur */ public final class VirtualAcquisitionDisplay implements ImageCacheListener { public static VirtualAcquisitionDisplay getDisplay(ImagePlus imgp) { ImageStack stack = imgp.getStack(); if (stack instanceof AcquisitionVirtualStack) { return ((AcquisitionVirtualStack) stack).getVirtualAcquisitionDisplay(); } else { return null; } } final static Color[] rgb = {Color.red, Color.green, Color.blue}; final ImageCache imageCache_; final Preferences prefs_ = Preferences.userNodeForPackage(this.getClass()); private static final String SIMPLE_WIN_X = "simple_x"; private static final String SIMPLE_WIN_Y = "simple_y"; private AcquisitionEngine eng_; private boolean finished_ = false; private boolean promptToSave_ = true; private String name_; private long lastDisplayTime_; private JSONObject lastDisplayTags_; private boolean updating_ = false; private int[] channelInitiated_; private int preferredSlice_ = -1; private int numComponents_; private ImagePlus hyperImage_; private ScrollbarWithLabel pSelector_; private ScrollbarWithLabel tSelector_; private ScrollbarWithLabel zSelector_; private ScrollbarWithLabel cSelector_; private DisplayControls controls_; public AcquisitionVirtualStack virtualStack_; private final Preferences displayPrefs_; private boolean simple_ = false; private MetadataPanel mdPanel_; private boolean newDisplay_ = false; //used for autostretching on window opening /* This interface and the following two classes * allow us to manipulate the dimensions * in an ImagePlus without it throwing conniptions. */ public interface IMMImagePlus { public int getNChannelsUnverified(); public int getNSlicesUnverified(); public int getNFramesUnverified(); public void setNChannelsUnverified(int nChannels); public void setNSlicesUnverified(int nSlices); public void setNFramesUnverified(int nFrames); } public class MMCompositeImage extends CompositeImage implements IMMImagePlus { public VirtualAcquisitionDisplay display_; MMCompositeImage(ImagePlus imgp, int type, VirtualAcquisitionDisplay disp) { super(imgp, type); display_ = disp; } @Override public ImageProcessor getProcessor() { if (super.getMode() == CompositeImage.COMPOSITE ) return super.getProcessor(); ImageProcessor ip = super.getProcessor(); ip.setPixels( getImageStack().getProcessor( getStackIndex(getChannel(),getSlice(),getFrame()) ).getPixels()); return ip; } @Override public int getImageStackSize() { return super.nChannels * super.nSlices * super.nFrames; } @Override public int getStackSize() { return getImageStackSize(); } @Override public int getNChannelsUnverified() { return super.nChannels; } @Override public int getNSlicesUnverified() { return super.nSlices; } @Override public int getNFramesUnverified() { return super.nFrames; } @Override public void setNChannelsUnverified(int nChannels) { super.nChannels = nChannels; } @Override public void setNSlicesUnverified(int nSlices) { super.nSlices = nSlices; } @Override public void setNFramesUnverified(int nFrames) { super.nFrames = nFrames; } @Override public void draw() { imageChangedUpdate(); super.draw(); } } public class MMImagePlus extends ImagePlus implements IMMImagePlus { public VirtualAcquisitionDisplay display_; MMImagePlus(String title, ImageStack stack, VirtualAcquisitionDisplay disp) { super(title, stack); display_ = disp; } @Override public int getImageStackSize() { return super.nChannels * super.nSlices * super.nFrames; } @Override public int getStackSize() { return getImageStackSize(); } @Override public int getNChannelsUnverified() { return super.nChannels; } @Override public int getNSlicesUnverified() { return super.nSlices; } @Override public int getNFramesUnverified() { return super.nFrames; } @Override public void setNChannelsUnverified(int nChannels) { super.nChannels = nChannels; } @Override public void setNSlicesUnverified(int nSlices) { super.nSlices = nSlices; } @Override public void setNFramesUnverified(int nFrames) { super.nFrames = nFrames; } @Override public void draw() { imageChangedUpdate(); super.draw(); } } public VirtualAcquisitionDisplay(ImageCache imageCache, AcquisitionEngine eng) { this(imageCache, eng, "Untitled"); } public VirtualAcquisitionDisplay(ImageCache imageCache, AcquisitionEngine eng, String name) { name_ = name; imageCache_ = imageCache; eng_ = eng; pSelector_ = createPositionScrollbar(); displayPrefs_ = Preferences.userNodeForPackage(this.getClass()); } //used for snap and live public VirtualAcquisitionDisplay(ImageCache imageCache, String name) throws MMScriptException { simple_ = true; imageCache_ = imageCache; displayPrefs_ = Preferences.userNodeForPackage(this.getClass()); name_ = name; newDisplay_ = true; } private void startup(JSONObject firstImageMetadata) { mdPanel_ = MMStudioMainFrame.getInstance().getMetadataPanel(); JSONObject summaryMetadata = getSummaryMetadata(); int numSlices = 1; int numFrames = 1; int numChannels = 1; int numGrayChannels; int numPositions = 0; int width = 0; int height = 0; int numComponents = 1; try { if (firstImageMetadata != null) { width = MDUtils.getWidth(firstImageMetadata); height = MDUtils.getHeight(firstImageMetadata); } else { width = MDUtils.getWidth(summaryMetadata); height = MDUtils.getHeight(summaryMetadata); } numSlices = Math.max(summaryMetadata.getInt("Slices"), 1); numFrames = Math.max(summaryMetadata.getInt("Frames"), 1); int imageChannelIndex; try { imageChannelIndex = MDUtils.getChannelIndex(firstImageMetadata); } catch (Exception e) { imageChannelIndex = -1; } numChannels = Math.max(1 + imageChannelIndex, Math.max(summaryMetadata.getInt("Channels"), 1)); numPositions = Math.max(summaryMetadata.getInt("Positions"), 0); numComponents = Math.max(MDUtils.getNumberOfComponents(summaryMetadata), 1); } catch (Exception e) { ReportingUtils.showError(e); } numComponents_ = numComponents; numGrayChannels = numComponents_ * numChannels; channelInitiated_ = new int[numGrayChannels]; if (imageCache_.getDisplayAndComments() == null || imageCache_.getDisplayAndComments().isNull("Channels")) { imageCache_.setDisplayAndComments(getDisplaySettingsFromSummary(summaryMetadata)); } int type = 0; try { if (firstImageMetadata != null) { type = MDUtils.getSingleChannelType(firstImageMetadata); } else { type = MDUtils.getSingleChannelType(summaryMetadata); } } catch (Exception ex) { ReportingUtils.showError(ex, "Unable to determine acquisition type."); } virtualStack_ = new AcquisitionVirtualStack(width, height, type, null, imageCache_, numGrayChannels * numSlices * numFrames, this); if (summaryMetadata.has("PositionIndex")) { try { virtualStack_.setPositionIndex(MDUtils.getPositionIndex(summaryMetadata)); } catch (Exception ex) { ReportingUtils.logError(ex); } } if (simple_) { controls_ = new SimpleWindowControls(this); } else { controls_ = new HyperstackControls(this); } hyperImage_ = createHyperImage(createMMImagePlus(virtualStack_), numGrayChannels, numSlices, numFrames, virtualStack_, controls_); applyPixelSizeCalibration(hyperImage_); createWindow(hyperImage_, controls_); cSelector_ = getSelector("c"); if (!simple_) { tSelector_ = getSelector("t"); zSelector_ = getSelector("z"); if (numFrames > 1 && numSlices == 1) // in this scenario zselector mistakenly gets set to the tselector zSelector_ = null; if (zSelector_ != null) { zSelector_.addAdjustmentListener(new AdjustmentListener() { public void adjustmentValueChanged(AdjustmentEvent e) { preferredSlice_ = zSelector_.getValue(); } }); } if (imageCache_.lastAcquiredFrame() > 1) { setNumFrames(1 + imageCache_.lastAcquiredFrame()); } else { setNumFrames(1); } setNumSlices(numSlices); setNumPositions(numPositions); } for (int i = 0; i < numGrayChannels; ++i) { updateChannelLUT(i); updateChannelContrast(i); } updateAndDraw(); updateWindow(); } /** * Allows bypassing the prompt to Save * @param promptToSave boolean flag */ public void promptToSave(boolean promptToSave) { promptToSave_ = promptToSave; } /* * Method required by ImageCacheListener */ @Override public void imageReceived(final TaggedImage taggedImage) { updateDisplay(taggedImage, false); updateAndDraw(); } /* * Method required by ImageCacheListener */ @Override public void imagingFinished(String path) { updateDisplay(null, true); updateAndDraw(); updateWindow(); } private void updateDisplay(TaggedImage taggedImage, boolean finalUpdate) { try { long t = System.currentTimeMillis(); JSONObject tags; if (taggedImage != null) { tags = taggedImage.tags; } else { tags = imageCache_.getLastImageTags(); } if (finalUpdate || (MDUtils.getFrameIndex(tags) == 0) || (Math.abs(t - lastDisplayTime_) > 30)) { if (tags != null /*&& tags != lastDisplayTags_*/) { showImage(tags, true); lastDisplayTags_ = tags; } lastDisplayTime_ = t; } } catch (Exception e) { ReportingUtils.logError(e); } } private ScrollbarWithLabel getSelector(String label) { // label should be "t", "z", or "c" ScrollbarWithLabel selector = null; ImageWindow win = hyperImage_.getWindow(); if (win instanceof StackWindow) { try { selector = (ScrollbarWithLabel) JavaUtils.getRestrictedFieldValue((StackWindow) win, StackWindow.class, label + "Selector"); } catch (NoSuchFieldException ex) { selector = null; ReportingUtils.logError(ex); } } if (selector == null && label.contentEquals("t") || label.contentEquals("z")) { try { selector = (ScrollbarWithLabel) JavaUtils.getRestrictedFieldValue((StackWindow) win, StackWindow.class, "animationSelector"); } catch (NoSuchFieldException ex) { selector = null; ReportingUtils.logError(ex); } } return selector; } public int rgbToGrayChannel(int channelIndex) { try { if (MDUtils.getNumberOfComponents(imageCache_.getSummaryMetadata()) == 3) { return channelIndex * 3; } return channelIndex; } catch (Exception ex) { ReportingUtils.logError(ex); return 0; } } public int grayToRGBChannel(int grayIndex) { try { if (MDUtils.getNumberOfComponents(imageCache_.getSummaryMetadata()) == 3) { return grayIndex / 3; } return grayIndex; } catch (Exception ex) { ReportingUtils.logError(ex); return 0; } } public static JSONObject getDisplaySettingsFromSummary(JSONObject summaryMetadata) { try { JSONObject displaySettings = new JSONObject(); JSONArray chColors; JSONArray chNames = MDUtils.getJSONArrayMember(summaryMetadata, "ChNames"); try { chColors = MDUtils.getJSONArrayMember(summaryMetadata, "ChColors"); } catch (JSONException ex) { int[] defaultColors = {Color.RED.getRGB(), Color.GREEN.getRGB(), Color.BLUE.getRGB()}; chColors = new JSONArray(); for (int i = 0; i < chNames.length(); i++) { chColors.put(defaultColors[i % defaultColors.length]); } summaryMetadata.put("ChColors", chColors); } JSONArray chMaxes; try { chMaxes = MDUtils.getJSONArrayMember(summaryMetadata, "ChContrastMax"); } catch (JSONException ex) { chMaxes = new JSONArray(); for (int i = 0; i < chNames.length(); i++) { chMaxes.put(256); } summaryMetadata.put("ChContrastMax", chMaxes); } JSONArray chMins; try { chMins = MDUtils.getJSONArrayMember(summaryMetadata, "ChContrastMin"); } catch (JSONException ex) { chMins = new JSONArray(); for (int i = 0; i < chNames.length(); i++) { chMins.put(0); } summaryMetadata.put("ChContrastMin", chMins); } int numComponents = 1; try { numComponents = MDUtils.getNumberOfComponents(summaryMetadata); } catch (JSONException ex) { } JSONArray channels = new JSONArray(); for (int k = 0; k < chNames.length(); ++k) { String name = (String) chNames.get(k); int color = chColors.getInt(k); int min = chMins.getInt(k); int max = chMaxes.getInt(k); for (int component = 0; component < numComponents; ++component) { JSONObject channelObject = new JSONObject(); if (numComponents == 1) { channelObject.put("Color", color); } else { channelObject.put("Color", rgb[component].getRGB()); } channelObject.put("Name", name); channelObject.put("Gamma", 1.0); channelObject.put("Min", min); channelObject.put("Max", max); channels.put(channelObject); } } if (chNames.length() == 0) { for (int component = 0; component < numComponents; ++component) { JSONObject channelObject = new JSONObject(); if (numComponents == 1) { channelObject.put("Color", Color.white); } else { channelObject.put("Color", rgb[component].getRGB()); } channelObject.put("Name", "Default"); channelObject.put("Gamma", 1.0); channels.put(channelObject); } } displaySettings.put("Channels", channels); JSONObject comments = new JSONObject(); String summary = ""; try { summary = summaryMetadata.getString("Comment"); } catch (JSONException ex) { summaryMetadata.put("Comment", ""); } comments.put("Summary", summary); displaySettings.put("Comments", comments); return displaySettings; } catch (Exception e) { ReportingUtils.logError(e); return null; } } /** * Sets ImageJ pixel size calibration * @param hyperImage */ private void applyPixelSizeCalibration(final ImagePlus hyperImage) { try { double pixSizeUm = getSummaryMetadata().getDouble("PixelSize_um"); if (pixSizeUm > 0) { Calibration cal = new Calibration(); cal.setUnit("um"); cal.pixelWidth = pixSizeUm; cal.pixelHeight = pixSizeUm; hyperImage.setCalibration(cal); } } catch (JSONException ex) { // no pixelsize defined. Nothing to do } } private void setNumPositions(int n) { if (simple_) return; pSelector_.setMinimum(0); pSelector_.setMaximum(n); ImageWindow win = hyperImage_.getWindow(); if (n > 1 && pSelector_.getParent() == null) { win.add(pSelector_, win.getComponentCount() - 1); } else if (n <= 1 && pSelector_.getParent() != null) { win.remove(pSelector_); } win.pack(); } private void setNumFrames(int n) { if (simple_) return; if (tSelector_ != null) { //ImageWindow win = hyperImage_.getWindow(); ((IMMImagePlus) hyperImage_).setNFramesUnverified(n); tSelector_.setMaximum(n + 1); // JavaUtils.setRestrictedFieldValue(win, StackWindow.class, "nFrames", n); } } private void setNumSlices(int n) { if (simple_) return; if (zSelector_ != null) { ((IMMImagePlus) hyperImage_).setNSlicesUnverified(n); zSelector_.setMaximum(n + 1); } } private void setNumChannels(int n) { if (cSelector_ != null) { ((IMMImagePlus) hyperImage_).setNChannelsUnverified(n); cSelector_.setMaximum(n + 1); } } public ImagePlus getHyperImage() { return hyperImage_; } public int getStackSize() { if (hyperImage_ == null ) return -1; int s = hyperImage_.getNSlices(); int c = hyperImage_.getNChannels(); int f = hyperImage_.getNFrames(); if ( (s > 1 && c > 1) || (c > 1 && f > 1) || (f > 1 && s > 1) ) return s * c * f; return Math.max(Math.max(s, c), f); } private void imageChangedWindowUpdate() { if (hyperImage_ != null && hyperImage_.isVisible()) { TaggedImage ti = virtualStack_.getTaggedImage(hyperImage_.getCurrentSlice()); if (ti != null) controls_.newImageUpdate(ti.tags); } } public void updateAndDraw() { if (!updating_) { updating_ = true; if (hyperImage_ instanceof CompositeImage) { ((CompositeImage) hyperImage_).setChannelsUpdated(); } if (hyperImage_ != null && hyperImage_.isVisible()) { hyperImage_.updateAndDraw(); imageChangedWindowUpdate(); } updating_ = false; } } public void updateWindow() { if(simple_) { hyperImage_.getWindow().setTitle(name_); return; } if (controls_ == null) { return; } String status = ""; final AcquisitionEngine eng = eng_; if (eng != null) { if (acquisitionIsRunning()) { if (!abortRequested()) { controls_.acquiringImagesUpdate(true); if (isPaused()) { status = "paused"; } else { status = "running"; } } else { controls_.acquiringImagesUpdate(false); status = "interrupted"; } } else { controls_.acquiringImagesUpdate(false); if (!status.contentEquals("interrupted")) { if (eng.isFinished()) { status = "finished"; eng_ = null; } } } status += ", "; if (eng.isFinished()) { eng_ = null; finished_ = true; } } else { if (finished_ == true) { status = "finished, "; } controls_.acquiringImagesUpdate(false); } if (isDiskCached()) { status += "on disk"; } else { status += "not yet saved"; } controls_.imagesOnDiskUpdate(imageCache_.getDiskLocation() != null); String path = isDiskCached() ? new File(imageCache_.getDiskLocation()).getName() : name_; if (hyperImage_.isVisible()) hyperImage_.getWindow().setTitle(path + " (" + status + ")"); } /** * Displays tagged image in the multi-D viewer * Will wait for the screen update * * @param taggedImg * @throws Exception */ public void showImage(TaggedImage taggedImg) throws Exception { showImage(taggedImg, true); } /** * Displays tagged image in the multi-D viewer * Optionally waits for the display to draw the image * * * @param taggedImg * @throws Exception */ public void showImage(TaggedImage taggedImg, boolean waitForDisplay) throws Exception { showImage(taggedImg.tags, waitForDisplay); } public void showImage(JSONObject md, boolean waitForDisplay) throws Exception { showImage(md,waitForDisplay,true); } public void showImage(JSONObject tags, boolean waitForDisplay, boolean allowContrastToChange) throws Exception { updateWindow(); if (tags == null) { return; } if (hyperImage_ == null) { startup(tags); } int channel = MDUtils.getChannelIndex(tags); int frame = MDUtils.getFrameIndex(tags); int position = MDUtils.getPositionIndex(tags); String channelName = MDUtils.getChannelName(tags); Color channelColor = null; try { new Color(MDUtils.getChannelColor(tags)); } catch (Exception e) {} int slice; if (this.acquisitionIsRunning() && this.getNextWakeTime() > System.currentTimeMillis() && preferredSlice_ > -1) { slice = preferredSlice_; } else { slice = MDUtils.getSliceIndex(tags); } int superChannel = this.rgbToGrayChannel(MDUtils.getChannelIndex(tags)); if (hyperImage_.getClass().equals(MMCompositeImage.class)) { boolean[] active = ((MMCompositeImage) hyperImage_ ).getActiveChannels(); for (int k = 0; k < active.length; k++) { if (active[k]) { superChannel += k; //allows selected channel to persist in break; //Composite or Grayscale display modes in RGB live mode } } } if (frame == 0 && allowContrastToChange) { //Autoscale contrast if this is first image try { TaggedImage image = imageCache_.getImage(superChannel, slice, frame, position); if (image != null) { Object pix = image.pix; int pixelMin = ImageUtils.getMin(pix); int pixelMax = ImageUtils.getMax(pix); if (slice > 0 ) { pixelMin = Math.min(this.getChannelMin(superChannel), pixelMin); pixelMax = Math.max(this.getChannelMax(superChannel), pixelMax); } if (!MDUtils.isRGB(tags)) { setChannelDisplayRange(superChannel, pixelMin, pixelMax); } else for (int i = 0; i < 3; ++i) setChannelDisplayRange(superChannel + i, pixelMin, pixelMax); } } catch (Exception ex) { ReportingUtils.logError(ex); throw(ex); } } if (cSelector_ != null) { if (cSelector_.getMaximum() <= (1 + superChannel)) { this.setNumChannels(1 + superChannel); ((CompositeImage) hyperImage_).reset(); //JavaUtils.invokeRestrictedMethod(hyperImage_, CompositeImage.class, // "setupLuts", 1 + superChannel, Integer.TYPE); } } if (channelName != null) setChannelName(channel, channelName); if (channelColor != null) setChannelColor(superChannel, channelColor.getRGB()); if (!simple_) { if (tSelector_ != null) { if (tSelector_.getMaximum() <= (1 + frame)) { this.setNumFrames(1 + frame); } } try { int p = 1 + MDUtils.getPositionIndex(tags); if (p >= getNumPositions()) { setNumPositions(p); } setPosition(MDUtils.getPositionIndex(tags)); if (MDUtils.isRGB(tags)) { hyperImage_.setPosition(1 + superChannel, 1 + MDUtils.getSliceIndex(tags), 1 + MDUtils.getFrameIndex(tags)); } else { hyperImage_.setPositionWithoutUpdate(1 + channel, 1 + MDUtils.getSliceIndex(tags), 1 + MDUtils.getFrameIndex(tags)); } } catch (Exception e) { ReportingUtils.logError(e); } } // Make sure image is shown if it is a single plane: if (hyperImage_.getStackSize() == 1) { hyperImage_.getProcessor().setPixels( hyperImage_.getStack().getPixels(1)); } Runnable updateAndDraw = new Runnable() { public void run() { updateAndDraw(); } }; if (!SwingUtilities.isEventDispatchThread()) { if (waitForDisplay) { SwingUtilities.invokeAndWait(updateAndDraw); } else { SwingUtilities.invokeLater(updateAndDraw); } } else { updateAndDraw(); } } public boolean firstImage() { if (newDisplay_) { newDisplay_ = false; return true; } return false; } private void updatePosition(int p) { if (simple_) return; virtualStack_.setPositionIndex(p); if (!hyperImage_.isComposite()) { Object pixels = virtualStack_.getPixels(hyperImage_.getCurrentSlice()); hyperImage_.getProcessor().setPixels(pixels); } updateAndDraw(); } public void setPosition(int p) { if (simple_) return; pSelector_.setValue(p); } public void setSliceIndex(int i) { if (simple_) return; final int f = hyperImage_.getFrame(); final int c = hyperImage_.getChannel(); hyperImage_.setPosition(c, i+1, f); } public int getSliceIndex() { return hyperImage_.getSlice() - 1; } boolean pause() { if (eng_ != null) { if (eng_.isPaused()) { eng_.setPause(false); } else { eng_.setPause(true); } updateWindow(); return (eng_.isPaused()); } return false; } boolean abort() { if (eng_ != null) { if (eng_.abortRequest()) { updateWindow(); return true; } } return false; } public boolean acquisitionIsRunning() { if (eng_ != null) { return eng_.isAcquisitionRunning(); } else { return false; } } public long getNextWakeTime() { return eng_.getNextWakeTime(); } public boolean abortRequested() { if (eng_ != null) { return eng_.abortRequested(); } else { return false; } } private boolean isPaused() { if (eng_ != null) { return eng_.isPaused(); } else { return false; } } boolean saveAs() { String prefix; String root; for (;;) { File f = FileDialogs.save(hyperImage_.getWindow(), "Please choose a location for the data set", MMStudioMainFrame.MM_DATA_SET); if (f == null) // Canceled. { return false; } prefix = f.getName(); root = new File(f.getParent()).getAbsolutePath(); if (f.exists()) { ReportingUtils.showMessage(prefix + " is write only! Please choose another name."); } else { break; } } TaggedImageStorageDiskDefault newFileManager = new TaggedImageStorageDiskDefault(root + "/" + prefix, true, getSummaryMetadata()); imageCache_.saveAs(newFileManager); MMStudioMainFrame.getInstance().setAcqDirectory(root); updateWindow(); return true; } final public MMImagePlus createMMImagePlus(AcquisitionVirtualStack virtualStack) { MMImagePlus img = new MMImagePlus(imageCache_.getDiskLocation(), virtualStack,this); FileInfo fi = new FileInfo(); fi.width = virtualStack.getWidth(); fi.height = virtualStack.getHeight(); fi.fileName = virtualStack.getDirectory(); fi.url = null; img.setFileInfo(fi); return img; } final public ImagePlus createHyperImage(MMImagePlus mmIP, int channels, int slices, int frames, final AcquisitionVirtualStack virtualStack, DisplayControls hc) { final ImagePlus hyperImage; mmIP.setNChannelsUnverified(channels); mmIP.setNFramesUnverified(frames); mmIP.setNSlicesUnverified(slices); if (channels > 1) { hyperImage = new MMCompositeImage(mmIP, CompositeImage.COMPOSITE,this); hyperImage.setOpenAsHyperStack(true); } else { hyperImage = mmIP; mmIP.setOpenAsHyperStack(true); } return hyperImage; } public void liveModeEnabled(boolean enabled) { if (simple_) { controls_.acquiringImagesUpdate(enabled); // Set window title??? } } private void createWindow(final ImagePlus hyperImage, DisplayControls hc) { final ImageWindow win = new StackWindow(hyperImage) { private boolean windowClosingDone_ = false; private boolean closed_ = false; @Override public void windowClosing(WindowEvent e) { if (windowClosingDone_) { return; } if (eng_ != null && eng_.isAcquisitionRunning()) { if (!abort()) { return; } } if (imageCache_.getDiskLocation() == null && promptToSave_) { int result = JOptionPane.showConfirmDialog(this, "This data set has not yet been saved.\n" + "Do you want to save it?", "Micro-Manager", JOptionPane.YES_NO_CANCEL_OPTION); if (result == JOptionPane.YES_OPTION) { if (!saveAs()) { return; } } else if (result == JOptionPane.CANCEL_OPTION) { return; } } // push current display settings to cache if (imageCache_ != null) { imageCache_.close(); } Point loc = hyperImage.getWindow().getLocation(); prefs_.putInt(SIMPLE_WIN_X, loc.x); prefs_.putInt(SIMPLE_WIN_Y, loc.y); if (!closed_) { try { close(); } catch (NullPointerException ex) { ReportingUtils.logError("Null pointer error in ImageJ code while closing window"); } } super.windowClosing(e); MMStudioMainFrame.getInstance().removeMMBackgroundListener(this); windowClosingDone_ = true; closed_ = true; } @Override public void windowClosed(WindowEvent E) { this.windowClosing(E); super.windowClosed(E); } @Override public void windowActivated(WindowEvent e) { if (!isClosed()) { super.windowActivated(e); } } }; win.setBackground(MMStudioMainFrame.getInstance().getBackgroundColor()); MMStudioMainFrame.getInstance().addMMBackgroundListener(win); win.add(hc); win.pack(); if (simple_ ) win.setLocation(prefs_.getInt(SIMPLE_WIN_X, 0),prefs_.getInt(SIMPLE_WIN_Y, 0)); } private ScrollbarWithLabel createPositionScrollbar() { final ScrollbarWithLabel pSelector = new ScrollbarWithLabel(null, 1, 1, 1, 2, 'p') { @Override public void setValue(int v) { if (this.getValue() != v) { super.setValue(v); updatePosition(v); } } }; // prevents scroll bar from blinking on Windows: pSelector.setFocusable(false); pSelector.setUnitIncrement(1); pSelector.setBlockIncrement(1); pSelector.addAdjustmentListener(new AdjustmentListener() { @Override public void adjustmentValueChanged(AdjustmentEvent e) { updatePosition(pSelector.getValue()); // ReportingUtils.logMessage("" + pSelector.getValue()); } }); return pSelector; } public JSONObject getCurrentMetadata() { try { if (hyperImage_ != null) { TaggedImage image = virtualStack_.getTaggedImage(hyperImage_.getCurrentSlice()); if (image != null) { return image.tags; } else { return null; } } else { return null; } } catch (NullPointerException ex) { return null; } } public int getCurrentPosition() { return virtualStack_.getPositionIndex(); } public int getNumSlices() { if (simple_) return 1; return ((IMMImagePlus) hyperImage_).getNSlicesUnverified(); } public int getNumFrames() { if (simple_) return 1; return ((IMMImagePlus) hyperImage_).getNFramesUnverified(); } public int getNumPositions() { if (simple_) return 1; return pSelector_.getMaximum(); } public ImagePlus getImagePlus() { return hyperImage_; } public ImageCache getImageCache() { return imageCache_; } public ImagePlus getImagePlus(int position) { ImagePlus iP = new ImagePlus(); iP.setStack(virtualStack_); iP.setDimensions(numComponents_ * getNumChannels(), getNumSlices(), getNumFrames()); iP.setFileInfo(hyperImage_.getFileInfo()); return iP; } public void setComment(String comment) throws MMScriptException { try { getSummaryMetadata().put("Comment", comment); } catch (Exception ex) { ReportingUtils.logError(ex); } } public final JSONObject getSummaryMetadata() { return imageCache_.getSummaryMetadata(); } public void close() { if (hyperImage_ != null) { hyperImage_.close(); } } public synchronized boolean windowClosed() { ImageWindow win = hyperImage_.getWindow(); return (win == null || win.isClosed()); } public void showFolder() { if (isDiskCached()) { try { File location = new File(imageCache_.getDiskLocation()); if (JavaUtils.isWindows()) { Runtime.getRuntime().exec("Explorer /n,/select," + location.getAbsolutePath()); } else if (JavaUtils.isMac()) { if (!location.isDirectory()) { location = location.getParentFile(); } Runtime.getRuntime().exec("open " + location.getAbsolutePath()); } } catch (IOException ex) { ReportingUtils.logError(ex); } } } public void setPlaybackFPS(double fps) { if (hyperImage_ != null) { try { JavaUtils.setRestrictedFieldValue(null, Animator.class, "animationRate", (double) fps); } catch (NoSuchFieldException ex) { ReportingUtils.showError(ex); } } } public void setPlaybackLimits(int firstFrame, int lastFrame) { if (hyperImage_ != null) { try { JavaUtils.setRestrictedFieldValue(null, Animator.class, "firstFrame", firstFrame); JavaUtils.setRestrictedFieldValue(null, Animator.class, "lastFrame", lastFrame); } catch (NoSuchFieldException ex) { ReportingUtils.showError(ex); } } } public double getPlaybackFPS() { return Animator.getFrameRate(); } public String getSummaryComment() { return imageCache_.getComment(); } public void setSummaryComment(String comment) { imageCache_.setComment(comment); } void setImageComment(String comment) { imageCache_.setImageComment(comment, getCurrentMetadata()); } String getImageComment() { try { return imageCache_.getImageComment(getCurrentMetadata()); } catch (NullPointerException ex) { return ""; } } public boolean isDiskCached() { ImageCache imageCache = imageCache_; if (imageCache == null) { return false; } else { return imageCache.getDiskLocation() != null; } } public void show() { if (hyperImage_ == null) { startup(null); } hyperImage_.show(); hyperImage_.getWindow().toFront(); } // CHANNEL SECTION //////////// public int getNumChannels() { return ((IMMImagePlus) hyperImage_).getNChannelsUnverified(); } public int getNumGrayChannels() { return getNumChannels(); } public String[] getChannelNames() { if (hyperImage_.isComposite()) { int nChannels = getNumGrayChannels(); String[] chanNames = new String[nChannels]; for (int i = 0; i < nChannels; ++i) { try { chanNames[i] = imageCache_.getDisplayAndComments().getJSONArray("Channels").getJSONObject(i).getString("Name"); } catch (Exception ex) { chanNames[i] = null; } } return chanNames; } else { return null; } } private void setChannelName(int channel, String channelName) { try { JSONObject displayAndComments = imageCache_.getDisplayAndComments(); JSONArray channelArray; if (displayAndComments.has("Channels")) { channelArray = displayAndComments.getJSONArray("Channels"); } else { channelArray = new JSONArray(); displayAndComments.put("Channels",channelArray); } if (channelArray.isNull(channel)) { channelArray.put(channel, new JSONObject().put("Name",channelName)); updateChannelLUT(channel); } } catch (JSONException ex) { ReportingUtils.logError(ex); } } public void setChannelVisibility(int channelIndex, boolean visible) { if (!hyperImage_.isComposite()) { return; } CompositeImage ci = (CompositeImage) hyperImage_; ci.getActiveChannels()[channelIndex] = visible; } public int[] getChannelHistogram(int channelIndex) { if (hyperImage_ == null || hyperImage_.getProcessor() == null) { return null; } if (hyperImage_.isComposite() && ((CompositeImage) hyperImage_).getMode() == CompositeImage.COMPOSITE) { ImageProcessor ip = ((CompositeImage) hyperImage_).getProcessor(channelIndex + 1); if (ip == null) { return null; } return ip.getHistogram(); } else { if (hyperImage_.getChannel() == (channelIndex + 1)) { return hyperImage_.getProcessor().getHistogram(); } else { return null; } } } private void updateChannelContrast(int channel) { if (hyperImage_ == null) { return; } if (hyperImage_.isComposite()) { setChannelWithoutMovingSlider(channel); CompositeImage ci = (CompositeImage) hyperImage_; setChannelDisplayRange(channel, ci); } else { hyperImage_.setDisplayRange(getChannelMin(channel), getChannelMax(channel)); } } private void setChannelDisplayRange(int channel, CompositeImage ci) { int min = getChannelMin(channel); int max = getChannelMax(channel); // ImageJ WORKAROUND // The following two lines of code are both necessary for a correct update. // Otherwise min and max get inconsistent in ImageJ. if (ci.getProcessor(channel+1) != null) { ci.getProcessor(channel + 1).setMinAndMax(min, max); } ci.setDisplayRange(min, max); } private void updateChannelLUT(int channel) { if (hyperImage_ == null) { return; } LUT lut = ImageUtils.makeLUT(getChannelColor(channel), getChannelGamma(channel), 8); if (hyperImage_.isComposite()) { setChannelWithoutMovingSlider(channel); CompositeImage ci = (CompositeImage) hyperImage_; ci.setChannelLut(lut); } else { hyperImage_.getProcessor().setColorModel(lut); updateChannelContrast(channel); } } private void setChannelWithoutMovingSlider(int channel) { if (hyperImage_ != null) { int z = hyperImage_.getSlice(); int t = hyperImage_.getFrame(); hyperImage_.updatePosition(channel + 1, z, t); } } public int getChannelMin(int channelIndex) { try { return getChannelSetting(channelIndex).getInt("Min"); } catch (Exception ex) { return Integer.MAX_VALUE; } } public int getChannelMax(int channelIndex) { try { return getChannelSetting(channelIndex).getInt("Max"); } catch (Exception ex) { return Integer.MIN_VALUE; } } public double getChannelGamma(int channelIndex) { try { return getChannelSetting(channelIndex).getDouble("Gamma"); } catch (Exception ex) { //ReportingUtils.logError(ex); return 1.0; } } public Color getChannelColor(int channelIndex) { try { return new Color(getChannelSetting(channelIndex).getInt("Color")); } catch (Exception ex) { try { String[] channelNames = getChannelNames(); return new Color(displayPrefs_.node("ChColors").getInt(channelNames[channelIndex], 0xFFFFFF)); } catch (Exception e) { return Color.WHITE; } } } public void setChannelColor(int channel, int rgb) throws MMScriptException { JSONObject chan = getChannelSetting(channel); try { chan.put("Color", rgb); } catch (JSONException ex) { ReportingUtils.logError(ex); } String[] chNames = getChannelNames(); if (chNames != null && chNames[channel] != null) { displayPrefs_.node("ChColors").putInt(chNames[channel], rgb); } updateChannelLUT(channel); } public void setChannelGamma(int channel, double gamma) { JSONObject chan = getChannelSetting(channel); try { chan.put("Gamma", gamma); } catch (Exception e) { ReportingUtils.logError(e); } updateChannelLUT(channel); } public void setChannelDisplayRange(int channel, int min, int max) { JSONObject chan = getChannelSetting(channel); try { chan.put("Min", min); chan.put("Max", max); } catch (Exception e) { ReportingUtils.logError(e); } updateChannelContrast(channel); } private JSONObject getChannelSetting(int channel) { try { JSONArray array = imageCache_.getDisplayAndComments().getJSONArray("Channels"); if (array != null && !array.isNull(channel)) { return array.getJSONObject(channel); } else { return null; } } catch (Exception ex) { ReportingUtils.logError(ex); return null; } } public void setWindowTitle(String name) { name_ = name; updateWindow(); } public boolean isSimpleDisplay() { return simple_; } public void displayStatusLine(String status) { controls_.setStatusLabel(status); } private void imageChangedUpdate() { mdPanel_.update(hyperImage_); imageChangedWindowUpdate(); //used to update status line } public void storeSingleChannelDisplaySettings(int min, int max, double gamma) { try { JSONArray array = imageCache_.getDisplayAndComments().getJSONArray("Channels"); if (array == null && !array.isNull(0)) return; JSONObject settings = array.getJSONObject(0); settings.put("Max", max); settings.put("Min", min); settings.put("Gamma", gamma); } catch (Exception ex) { ReportingUtils.logError(ex); } } }
package org.micromanager.acquisition; import org.micromanager.api.ImageCacheListener; import ij.ImageStack; import ij.process.LUT; import java.awt.event.AdjustmentEvent; import ij.CompositeImage; import ij.ImagePlus; import ij.gui.ImageWindow; import ij.gui.ScrollbarWithLabel; import ij.gui.StackWindow; import ij.io.FileInfo; import ij.measure.Calibration; import ij.plugin.Animator; import ij.process.ImageProcessor; import java.awt.Color; import java.awt.event.AdjustmentListener; import java.awt.event.WindowEvent; import java.io.File; import java.io.IOException; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import mmcorej.TaggedImage; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.micromanager.MMStudioMainFrame; import org.micromanager.api.AcquisitionEngine; import org.micromanager.api.ImageCache; import org.micromanager.utils.FileDialogs; import org.micromanager.utils.ImageUtils; import org.micromanager.utils.JavaUtils; import org.micromanager.utils.MDUtils; import org.micromanager.utils.MMScriptException; import org.micromanager.utils.ReportingUtils; /** * * @author arthur */ public final class VirtualAcquisitionDisplay implements ImageCacheListener { public static VirtualAcquisitionDisplay getDisplay(ImagePlus imgp) { ImageStack stack = imgp.getStack(); if (stack instanceof AcquisitionVirtualStack) { return ((AcquisitionVirtualStack) stack).getVirtualAcquisitionDisplay(); } else { return null; } } final static Color[] rgb = {Color.red, Color.green, Color.blue}; final ImageCache imageCache_; final private ImagePlus hyperImage_; final private HyperstackControls hc_; final AcquisitionVirtualStack virtualStack_; final private ScrollbarWithLabel pSelector_; final private ScrollbarWithLabel tSelector_; final private ScrollbarWithLabel zSelector_; final private MMImagePlus mmImagePlus_; final private int numComponents_; private AcquisitionEngine eng_; private boolean finished_ = false; private boolean promptToSave_ = true; private final String name_; private long lastDisplayTime_; private JSONObject lastDisplayTags_; private boolean updating_ = false; private int[] channelInitiated_; /* This interface and the following two classes * allow us to manipulate the dimensions * in an ImagePlus without it throwing conniptions. */ public interface IMMImagePlus { public int getNChannelsUnverified(); public int getNSlicesUnverified(); public int getNFramesUnverified(); public void setNChannelsUnverified(int nChannels); public void setNSlicesUnverified(int nSlices); public void setNFramesUnverified(int nFrames); } public class MMCompositeImage extends CompositeImage implements IMMImagePlus { MMCompositeImage(ImagePlus imgp, int type) { super(imgp, type); } @Override public int getImageStackSize() { return super.nChannels * super.nSlices * super.nFrames; } @Override public int getStackSize() { return getImageStackSize(); } @Override public int getNChannelsUnverified() { return super.nChannels; } @Override public int getNSlicesUnverified() { return super.nSlices; } @Override public int getNFramesUnverified() { return super.nFrames; } @Override public void setNChannelsUnverified(int nChannels) { super.nChannels = nChannels; } @Override public void setNSlicesUnverified(int nSlices) { super.nSlices = nSlices; } @Override public void setNFramesUnverified(int nFrames) { super.nFrames = nFrames; } } public class MMImagePlus extends ImagePlus implements IMMImagePlus { MMImagePlus(String title, ImageStack stack) { super(title, stack); } @Override public int getImageStackSize() { return super.nChannels * super.nSlices * super.nFrames; } @Override public int getStackSize() { return getImageStackSize(); } @Override public int getNChannelsUnverified() { return super.nChannels; } @Override public int getNSlicesUnverified() { return super.nSlices; } @Override public int getNFramesUnverified() { return super.nFrames; } @Override public void setNChannelsUnverified(int nChannels) { super.nChannels = nChannels; } @Override public void setNSlicesUnverified(int nSlices) { super.nSlices = nSlices; } @Override public void setNFramesUnverified(int nFrames) { super.nFrames = nFrames; } } public VirtualAcquisitionDisplay(ImageCache imageCache, AcquisitionEngine eng) { this(imageCache, eng, "Untitled"); } public VirtualAcquisitionDisplay(ImageCache imageCache, AcquisitionEngine eng, String name) { name_ = name; imageCache_ = imageCache; eng_ = eng; pSelector_ = createPositionScrollbar(); JSONObject summaryMetadata = getSummaryMetadata(); int numSlices = 1; int numFrames = 1; int numChannels = 1; int numGrayChannels; int numPositions = 0; int width = 0; int height = 0; int numComponents = 1; try { width = MDUtils.getWidth(summaryMetadata); height = MDUtils.getHeight(summaryMetadata); numSlices = Math.max(summaryMetadata.getInt("Slices"), 1); numFrames = Math.max(summaryMetadata.getInt("Frames"), 1); //numFrames = Math.max(Math.min(2,summaryMetadata.getInt("Frames")), 1); numChannels = Math.max(summaryMetadata.getInt("Channels"), 1); numPositions = Math.max(summaryMetadata.getInt("Positions"), 0); numComponents = Math.max(MDUtils.getNumberOfComponents(summaryMetadata), 1); } catch (Exception e) { ReportingUtils.showError(e); } numComponents_ = numComponents; numGrayChannels = numComponents_ * numChannels; channelInitiated_ = new int[numGrayChannels]; if (imageCache_.getDisplayAndComments() == null || imageCache_.getDisplayAndComments().isNull("Channels")) { imageCache_.setDisplayAndComments(getDisplaySettingsFromSummary(summaryMetadata)); } int type = 0; try { type = MDUtils.getSingleChannelType(summaryMetadata); } catch (Exception ex) { ReportingUtils.showError(ex, "Unable to determine acquisition type."); } virtualStack_ = new AcquisitionVirtualStack(width, height, type, null, imageCache, 1 /* numGrayChannels * numSlices * numFrames */, this); if (summaryMetadata.has("PositionIndex")) { try { virtualStack_.setPositionIndex(MDUtils.getPositionIndex(summaryMetadata)); } catch (Exception ex) { ReportingUtils.logError(ex); } } hc_ = new HyperstackControls(this); mmImagePlus_ = createMMImagePlus(virtualStack_); hyperImage_ = createHyperImage(numGrayChannels, numSlices, numFrames, virtualStack_, hc_); applyPixelSizeCalibration(hyperImage_); createWindow(hyperImage_, hc_); tSelector_ = getTSelector(); zSelector_ = getZSelector(); if (imageCache_.lastAcquiredFrame() > 1) { setNumFrames(1 + imageCache_.lastAcquiredFrame()); } else { setNumFrames(1); } setNumSlices(numSlices); setNumPositions(numPositions); for (int i = 0; i < numGrayChannels; ++i) { updateChannelLUT(i); updateChannelContrast(i); } updateAndDraw(); updateWindow(); } /** * Allows bypassing the prompt to Save * @param promptToSave boolean flag */ public void promptToSave(boolean promptToSave) { promptToSave_ = promptToSave; } /* * Method required by ImageCacheListener */ @Override public void imageReceived(final TaggedImage taggedImage) { updateDisplay(taggedImage, false); updateAndDraw(); } /* * Method required by ImageCacheListener */ @Override public void imagingFinished(String path) { updateDisplay(null, true); updateAndDraw(); updateWindow(); } private void updateDisplay(TaggedImage taggedImage, boolean finalUpdate) { try { long t = System.currentTimeMillis(); JSONObject tags; if (taggedImage != null) { tags = taggedImage.tags; } else { tags = imageCache_.getLastImageTags(); } if (finalUpdate || (MDUtils.getFrameIndex(tags) == 0) || (Math.abs(t - lastDisplayTime_) > 30)) { if (tags != null /*&& tags != lastDisplayTags_*/) { showImage(tags, true); lastDisplayTags_ = tags; } lastDisplayTime_ = t; } } catch (Exception e) { ReportingUtils.logError(e); } } private ScrollbarWithLabel getTSelector() { ScrollbarWithLabel tSelector = null; ImageWindow win = hyperImage_.getWindow(); if (win instanceof StackWindow) { try { tSelector = (ScrollbarWithLabel) JavaUtils.getRestrictedFieldValue((StackWindow) win, StackWindow.class, "tSelector"); } catch (NoSuchFieldException ex) { tSelector = null; ReportingUtils.logError(ex); } } if (tSelector == null) { try { tSelector = (ScrollbarWithLabel) JavaUtils.getRestrictedFieldValue((StackWindow) win, StackWindow.class, "animationSelector"); } catch (NoSuchFieldException ex) { tSelector = null; ReportingUtils.logError(ex); } } return tSelector; } private ScrollbarWithLabel getZSelector() { ScrollbarWithLabel zSelector = null; ImageWindow win = hyperImage_.getWindow(); if (win instanceof StackWindow) { try { zSelector = (ScrollbarWithLabel) JavaUtils.getRestrictedFieldValue((StackWindow) win, StackWindow.class, "zSelector"); } catch (NoSuchFieldException ex) { zSelector = null; ReportingUtils.logError(ex); } } if (zSelector == null) { try { zSelector = (ScrollbarWithLabel) JavaUtils.getRestrictedFieldValue((StackWindow) win, StackWindow.class, "animationSelector"); } catch (NoSuchFieldException ex) { zSelector = null; ReportingUtils.logError(ex); } } return zSelector; } public int rgbToGrayChannel(int channelIndex) { try { if (MDUtils.getNumberOfComponents(imageCache_.getSummaryMetadata()) == 3) { return channelIndex * 3; } return channelIndex; } catch (Exception ex) { ReportingUtils.logError(ex); return 0; } } public int grayToRGBChannel(int grayIndex) { try { if (MDUtils.getNumberOfComponents(imageCache_.getSummaryMetadata()) == 3) { return grayIndex / 3; } return grayIndex; } catch (Exception ex) { ReportingUtils.logError(ex); return 0; } } public static JSONObject getDisplaySettingsFromSummary(JSONObject summaryMetadata) { try { JSONObject displaySettings = new JSONObject(); JSONArray chColors; JSONArray chNames = MDUtils.getJSONArrayMember(summaryMetadata, "ChNames"); try { chColors = MDUtils.getJSONArrayMember(summaryMetadata, "ChColors"); } catch (JSONException ex) { int[] defaultColors = {Color.RED.getRGB(), Color.GREEN.getRGB(), Color.BLUE.getRGB()}; chColors = new JSONArray(); for (int i = 0; i < chNames.length(); i++) { chColors.put(defaultColors[i % defaultColors.length]); } summaryMetadata.put("ChColors", chColors); } JSONArray chMaxes; try { chMaxes = MDUtils.getJSONArrayMember(summaryMetadata, "ChContrastMax"); } catch (JSONException ex) { chMaxes = new JSONArray(); for (int i = 0; i < chNames.length(); i++) { chMaxes.put(256); } summaryMetadata.put("ChContrastMax", chMaxes); } JSONArray chMins; try { chMins = MDUtils.getJSONArrayMember(summaryMetadata, "ChContrastMin"); } catch (JSONException ex) { chMins = new JSONArray(); for (int i = 0; i < chNames.length(); i++) { chMins.put(0); } summaryMetadata.put("ChContrastMin", chMins); } int numComponents = 1; try { numComponents = MDUtils.getNumberOfComponents(summaryMetadata); } catch (JSONException ex) { } JSONArray channels = new JSONArray(); for (int k = 0; k < chNames.length(); ++k) { String name = (String) chNames.get(k); int color = chColors.getInt(k); int min = chMins.getInt(k); int max = chMaxes.getInt(k); for (int component = 0; component < numComponents; ++component) { JSONObject channelObject = new JSONObject(); if (numComponents == 1) { channelObject.put("Color", color); } else { channelObject.put("Color", rgb[component].getRGB()); } channelObject.put("Name", name); channelObject.put("Gamma", 1.0); channelObject.put("Min", min); channelObject.put("Max", max); channels.put(channelObject); } } if (chNames.length() == 0) { for (int component = 0; component < numComponents; ++component) { JSONObject channelObject = new JSONObject(); if (numComponents == 1) { channelObject.put("Color", Color.white); } else { channelObject.put("Color", rgb[component].getRGB()); } channelObject.put("Name", "Default"); channelObject.put("Gamma", 1.0); channels.put(channelObject); } } displaySettings.put("Channels", channels); JSONObject comments = new JSONObject(); String summary = ""; try { summary = summaryMetadata.getString("Comment"); } catch (JSONException ex) { summaryMetadata.put("Comment", ""); } comments.put("Summary", summary); displaySettings.put("Comments", comments); return displaySettings; } catch (Exception e) { ReportingUtils.logError(e); return null; } } /** * Sets ImageJ pixel size calibration * @param hyperImage */ private void applyPixelSizeCalibration(final ImagePlus hyperImage) { try { double pixSizeUm = getSummaryMetadata().getDouble("PixelSize_um"); if (pixSizeUm > 0) { Calibration cal = new Calibration(); cal.setUnit("um"); cal.pixelWidth = pixSizeUm; cal.pixelHeight = pixSizeUm; hyperImage.setCalibration(cal); } } catch (JSONException ex) { // no pixelsize defined. Nothing to do } } private void setNumPositions(int n) { pSelector_.setMinimum(0); pSelector_.setMaximum(n); ImageWindow win = hyperImage_.getWindow(); if (n > 1 && pSelector_.getParent() == null) { win.add(pSelector_, win.getComponentCount() - 1); } else if (n <= 1 && pSelector_.getParent() != null) { win.remove(pSelector_); } win.pack(); } private void setNumFrames(int n) { if (tSelector_ != null) { //ImageWindow win = hyperImage_.getWindow(); ((IMMImagePlus) hyperImage_).setNFramesUnverified(n); tSelector_.setMaximum(n + 1); // JavaUtils.setRestrictedFieldValue(win, StackWindow.class, "nFrames", n); } } private void setNumSlices(int n) { if (zSelector_ != null) { ((IMMImagePlus) hyperImage_).setNSlicesUnverified(n); zSelector_.setMaximum(n + 1); } } public ImagePlus getHyperImage() { return hyperImage_; } public int getStackSize() { if (hyperImage_ != null) { return getNumChannels() * getNumSlices() * getNumFrames(); } else if (mmImagePlus_ != null) { return mmImagePlus_.getStackSize(); } else { return 2; } } public void updateAndDraw() { if (!updating_) { updating_ = true; if (hyperImage_ instanceof CompositeImage) { ((CompositeImage) hyperImage_).setChannelsUpdated(); } hyperImage_.updateAndDraw(); updating_ = false; } } public void updateWindow() { if (hc_ == null) { return; } String status = ""; final AcquisitionEngine eng = eng_; if (eng != null) { if (acquisitionIsRunning()) { if (!abortRequested()) { hc_.enableAcquisitionControls(true); if (isPaused()) { status = "paused"; } else { status = "running"; } } else { hc_.enableAcquisitionControls(false); status = "interrupted"; } } else { hc_.enableAcquisitionControls(false); if (!status.contentEquals("interrupted")) { if (eng.isFinished()) { status = "finished"; eng_ = null; } } } status += ", "; if (eng.isFinished()) { eng_ = null; finished_ = true; } } else { if (finished_ == true) { status = "finished, "; } hc_.enableAcquisitionControls(false); } if (isDiskCached()) { status += "on disk"; } else { status += "not yet saved"; } hc_.enableShowFolderButton(imageCache_.getDiskLocation() != null); String path = isDiskCached() ? new File(imageCache_.getDiskLocation()).getName() : name_; if (hyperImage_.isVisible()) { hyperImage_.getWindow().setTitle(path + " (" + status + ")"); } } /** * Displays tagged image in the multi-D viewer * Will wait for the screen update * * @param taggedImg * @throws Exception */ public void showImage(TaggedImage taggedImg) throws Exception { showImage(taggedImg, true); } /** * Displays tagged image in the multi-D viewer * Optionally waits for the display to draw the image * * * @param taggedImg * @throws Exception */ public void showImage(TaggedImage taggedImg, boolean waitForDisplay) throws Exception { showImage(taggedImg.tags, waitForDisplay); } public void showImage(JSONObject md, boolean waitForDisplay) throws Exception { updateWindow(); if (md == null) { return; } int channel = MDUtils.getChannelIndex(md); int superChannel = this.rgbToGrayChannel(MDUtils.getChannelIndex(md)); int frame = MDUtils.getFrameIndex(md); int position = MDUtils.getPositionIndex(md); int slice = MDUtils.getSliceIndex(md); if (frame == 0) { try { TaggedImage image = imageCache_.getImage(superChannel, slice, frame, position); if (image != null) { Object pix = image.pix; int pixelMin = ImageUtils.getMin(pix); int pixelMax = ImageUtils.getMax(pix); if (slice > 0) { pixelMin = Math.min(this.getChannelMin(superChannel), pixelMin); pixelMax = Math.max(this.getChannelMax(superChannel), pixelMax); } if (MDUtils.isRGB(md)) { for (int i = 0; i < 3; ++i) { setChannelDisplayRange(superChannel + i, pixelMin, pixelMax); } } else { setChannelDisplayRange(superChannel, pixelMin, pixelMax); } } } catch (Exception ex) { ReportingUtils.logError(ex); throw(ex); } } if (tSelector_ != null) { if (tSelector_.getMaximum() <= (1 + frame)) { this.setNumFrames(1 + frame); } } try { int p = 1 + MDUtils.getPositionIndex(md); if (p >= getNumPositions()) { setNumPositions(p); } setPosition(MDUtils.getPositionIndex(md)); if (MDUtils.isRGB(md)) { hyperImage_.setPosition(1 + superChannel, 1 + MDUtils.getSliceIndex(md), 1 + MDUtils.getFrameIndex(md)); } else { hyperImage_.setPositionWithoutUpdate(1 + channel, 1 + MDUtils.getSliceIndex(md), 1 + MDUtils.getFrameIndex(md)); } } catch (Exception e) { ReportingUtils.logError(e); } // Make sure image is shown if it is a single plane: if (hyperImage_.getStackSize() == 1) { hyperImage_.getProcessor().setPixels( hyperImage_.getStack().getPixels(1)); } Runnable updateAndDraw = new Runnable() { public void run() { if (hyperImage_ instanceof CompositeImage) { ((CompositeImage) hyperImage_).setChannelsUpdated(); } if (hyperImage_ != null && hyperImage_.isVisible()) hyperImage_.updateAndDraw(); } }; if (!SwingUtilities.isEventDispatchThread()) { if (waitForDisplay) { SwingUtilities.invokeAndWait(updateAndDraw); } else { SwingUtilities.invokeLater(updateAndDraw); } } else { updateAndDraw(); } } private void updatePosition(int p) { virtualStack_.setPositionIndex(p); if (!hyperImage_.isComposite()) { Object pixels = virtualStack_.getPixels(hyperImage_.getCurrentSlice()); hyperImage_.getProcessor().setPixels(pixels); } updateAndDraw(); } public void setPosition(int p) { pSelector_.setValue(p); } boolean pause() { if (eng_ != null) { if (eng_.isPaused()) { eng_.setPause(false); } else { eng_.setPause(true); } updateWindow(); return (eng_.isPaused()); } return false; } boolean abort() { if (eng_ != null) { if (eng_.abortRequest()) { updateWindow(); return true; } } return false; } public boolean acquisitionIsRunning() { if (eng_ != null) { return eng_.isAcquisitionRunning(); } else { return false; } } public long getNextWakeTime() { return eng_.getNextWakeTime(); } public boolean abortRequested() { if (eng_ != null) { return eng_.abortRequested(); } else { return false; } } private boolean isPaused() { if (eng_ != null) { return eng_.isPaused(); } else { return false; } } boolean saveAs() { String prefix; String root; for (;;) { File f = FileDialogs.save(hyperImage_.getWindow(), "Please choose a location for the data set", MMStudioMainFrame.MM_DATA_SET); if (f == null) // Canceled. { return false; } prefix = f.getName(); root = new File(f.getParent()).getAbsolutePath(); if (f.exists()) { ReportingUtils.showMessage(prefix + " is write only! Please choose another name."); } else { break; } } TaggedImageStorageDiskDefault newFileManager = new TaggedImageStorageDiskDefault(root + "/" + prefix, true, getSummaryMetadata()); imageCache_.saveAs(newFileManager); MMStudioMainFrame.getInstance().setAcqDirectory(root); updateWindow(); return true; } final public MMImagePlus createMMImagePlus(AcquisitionVirtualStack virtualStack) { MMImagePlus img = new MMImagePlus(imageCache_.getDiskLocation(), virtualStack); FileInfo fi = new FileInfo(); fi.width = virtualStack.getWidth(); fi.height = virtualStack.getHeight(); fi.fileName = virtualStack.getDirectory(); fi.url = null; img.setFileInfo(fi); return img; } final public ImagePlus createHyperImage(int channels, int slices, int frames, final AcquisitionVirtualStack virtualStack, HyperstackControls hc) { final ImagePlus hyperImage; mmImagePlus_.setNChannelsUnverified(channels); mmImagePlus_.setNFramesUnverified(frames); mmImagePlus_.setNSlicesUnverified(slices); if (channels > 1) { hyperImage = new MMCompositeImage(mmImagePlus_, CompositeImage.COMPOSITE); } else { hyperImage = mmImagePlus_; mmImagePlus_.setOpenAsHyperStack(true); } return hyperImage; } private void createWindow(ImagePlus hyperImage, HyperstackControls hc) { final ImageWindow win = new StackWindow(hyperImage) { private boolean windowClosingDone_ = false; private boolean closed_ = false; @Override public void windowClosing(WindowEvent e) { if (windowClosingDone_) { return; } if (eng_ != null && eng_.isAcquisitionRunning()) { if (!abort()) { return; } } if (imageCache_.getDiskLocation() == null && promptToSave_) { int result = JOptionPane.showConfirmDialog(this, "This data set has not yet been saved.\n" + "Do you want to save it?", "Micro-Manager", JOptionPane.YES_NO_CANCEL_OPTION); if (result == JOptionPane.YES_OPTION) { if (!saveAs()) { return; } } else if (result == JOptionPane.CANCEL_OPTION) { return; } } // push current display settings to cache if (imageCache_ != null) { imageCache_.close(); } if (!closed_) { close(); } super.windowClosing(e); MMStudioMainFrame.getInstance().removeMMBackgroundListener(this); ImagePlus.removeImageListener(hc_); windowClosingDone_ = true; closed_ = true; } @Override public void windowClosed(WindowEvent E) { this.windowClosing(E); super.windowClosed(E); } @Override public void windowActivated(WindowEvent e) { if (!isClosed()) { super.windowActivated(e); } } }; win.setBackground(MMStudioMainFrame.getInstance().getBackgroundColor()); MMStudioMainFrame.getInstance().addMMBackgroundListener(win); win.add(hc); ImagePlus.addImageListener(hc); win.pack(); } private ScrollbarWithLabel createPositionScrollbar() { final ScrollbarWithLabel pSelector = new ScrollbarWithLabel(null, 1, 1, 1, 2, 'p') { @Override public void setValue(int v) { if (this.getValue() != v) { super.setValue(v); updatePosition(v); } } }; // prevents scroll bar from blinking on Windows: pSelector.setFocusable(false); pSelector.setUnitIncrement(1); pSelector.setBlockIncrement(1); pSelector.addAdjustmentListener(new AdjustmentListener() { @Override public void adjustmentValueChanged(AdjustmentEvent e) { updatePosition(pSelector.getValue()); // ReportingUtils.logMessage("" + pSelector.getValue()); } }); return pSelector; } public JSONObject getCurrentMetadata() { try { if (hyperImage_ != null) { TaggedImage image = virtualStack_.getTaggedImage(hyperImage_.getCurrentSlice()); if (image != null) { return image.tags; } else { return null; } } else { return null; } } catch (NullPointerException ex) { return null; } } public int getCurrentPosition() { return virtualStack_.getPositionIndex(); } public int getNumSlices() { return ((IMMImagePlus) hyperImage_).getNSlicesUnverified(); } public int getNumFrames() { return ((IMMImagePlus) hyperImage_).getNFramesUnverified(); } public int getNumPositions() { return pSelector_.getMaximum(); } public ImagePlus getImagePlus() { return hyperImage_; } public ImageCache getImageCache() { return imageCache_; } public ImagePlus getImagePlus(int position) { ImagePlus iP = new ImagePlus(); iP.setStack(virtualStack_); iP.setDimensions(numComponents_ * getNumChannels(), getNumSlices(), getNumFrames()); iP.setFileInfo(hyperImage_.getFileInfo()); return iP; } public void setComment(String comment) throws MMScriptException { try { getSummaryMetadata().put("Comment", comment); } catch (Exception ex) { ReportingUtils.logError(ex); } } public final JSONObject getSummaryMetadata() { return imageCache_.getSummaryMetadata(); } public void close() { if (hyperImage_ != null) { hyperImage_.close(); } } public synchronized boolean windowClosed() { ImageWindow win = hyperImage_.getWindow(); return (win == null || win.isClosed()); } public void showFolder() { if (isDiskCached()) { try { File location = new File(imageCache_.getDiskLocation()); if (JavaUtils.isWindows()) { Runtime.getRuntime().exec("Explorer /n,/select," + location.getAbsolutePath()); } else if (JavaUtils.isMac()) { if (!location.isDirectory()) { location = location.getParentFile(); } Runtime.getRuntime().exec("open " + location.getAbsolutePath()); } } catch (IOException ex) { ReportingUtils.logError(ex); } } } public void setPlaybackFPS(double fps) { if (hyperImage_ != null) { try { JavaUtils.setRestrictedFieldValue(null, Animator.class, "animationRate", (double) fps); } catch (NoSuchFieldException ex) { ReportingUtils.showError(ex); } } } public void setPlaybackLimits(int firstFrame, int lastFrame) { if (hyperImage_ != null) { try { JavaUtils.setRestrictedFieldValue(null, Animator.class, "firstFrame", firstFrame); JavaUtils.setRestrictedFieldValue(null, Animator.class, "lastFrame", lastFrame); } catch (NoSuchFieldException ex) { ReportingUtils.showError(ex); } } } public double getPlaybackFPS() { return Animator.getFrameRate(); } public String getSummaryComment() { return imageCache_.getComment(); } public void setSummaryComment(String comment) { imageCache_.setComment(comment); } void setImageComment(String comment) { imageCache_.setImageComment(comment, getCurrentMetadata()); } String getImageComment() { try { return imageCache_.getImageComment(getCurrentMetadata()); } catch (NullPointerException ex) { return ""; } } public boolean isDiskCached() { ImageCache imageCache = imageCache_; if (imageCache == null) { return false; } else { return imageCache.getDiskLocation() != null; } } public void show() { hyperImage_.show(); hyperImage_.getWindow().toFront(); } // CHANNEL SECTION //////////// public int getNumChannels() { return ((IMMImagePlus) hyperImage_).getNChannelsUnverified(); } public int getNumGrayChannels() { return getNumChannels(); } public String[] getChannelNames() { if (hyperImage_.isComposite()) { int nChannels = getNumGrayChannels(); String[] chanNames = new String[nChannels]; for (int i = 0; i < nChannels; ++i) { try { chanNames[i] = imageCache_.getDisplayAndComments().getJSONArray("Channels").getJSONObject(i).getString("Name"); } catch (Exception ex) { ReportingUtils.logError(ex); } } return chanNames; } else { return null; } } public void setChannelVisibility(int channelIndex, boolean visible) { if (!hyperImage_.isComposite()) { return; } CompositeImage ci = (CompositeImage) hyperImage_; ci.getActiveChannels()[channelIndex] = visible; } public int[] getChannelHistogram(int channelIndex) { if (hyperImage_ == null || hyperImage_.getProcessor() == null) { return null; } if (hyperImage_.isComposite() && ((CompositeImage) hyperImage_).getMode() == CompositeImage.COMPOSITE) { ImageProcessor ip = ((CompositeImage) hyperImage_).getProcessor(channelIndex + 1); if (ip == null) { return null; } return ip.getHistogram(); } else { if (hyperImage_.getChannel() == (channelIndex + 1)) { return hyperImage_.getProcessor().getHistogram(); } else { return null; } } } private void updateChannelContrast(int channel) { if (hyperImage_ == null) { return; } if (hyperImage_.isComposite()) { setChannelWithoutMovingSlider(channel); CompositeImage ci = (CompositeImage) hyperImage_; setChannelDisplayRange(channel, ci); } else { hyperImage_.setDisplayRange(getChannelMin(channel), getChannelMax(channel)); } } private void setChannelDisplayRange(int channel, CompositeImage ci) { int min = getChannelMin(channel); int max = getChannelMax(channel); // ImageJ WORKAROUND // The following two lines of code are both necessary for a correct update. // Otherwise min and max get inconsistent in ImageJ. if (ci.getProcessor(channel+1) != null) { ci.getProcessor(channel + 1).setMinAndMax(min, max); } ci.setDisplayRange(min, max); } private void updateChannelLUT(int channel) { if (hyperImage_ == null) { return; } LUT lut = ImageUtils.makeLUT(getChannelColor(channel), getChannelGamma(channel), 8); if (hyperImage_.isComposite()) { setChannelWithoutMovingSlider(channel); CompositeImage ci = (CompositeImage) hyperImage_; ci.setChannelLut(lut); } else { hyperImage_.getProcessor().setColorModel(lut); updateChannelContrast(channel); } } private void setChannelWithoutMovingSlider(int channel) { if (hyperImage_ != null) { int z = hyperImage_.getSlice(); int t = hyperImage_.getFrame(); hyperImage_.updatePosition(channel + 1, z, t); } } public int getChannelMin(int channelIndex) { try { return getChannelSetting(channelIndex).getInt("Min"); } catch (Exception ex) { return Integer.MAX_VALUE; } } public int getChannelMax(int channelIndex) { try { return getChannelSetting(channelIndex).getInt("Max"); } catch (Exception ex) { return Integer.MIN_VALUE; } } public double getChannelGamma(int channelIndex) { try { return getChannelSetting(channelIndex).getDouble("Gamma"); } catch (Exception ex) { ReportingUtils.logError(ex); return 1.0; } } public Color getChannelColor(int channelIndex) { try { return new Color(getChannelSetting(channelIndex).getInt("Color")); } catch (Exception ex) { return Color.WHITE; } } public void setChannelColor(int channel, int rgb) throws MMScriptException { JSONObject chan = getChannelSetting(channel); try { chan.put("Color", rgb); } catch (JSONException ex) { ReportingUtils.logError(ex); } updateChannelLUT(channel); String[] chNames = getChannelNames(); if (chNames != null && chNames.length > channel) MMStudioMainFrame.getInstance().saveChannelColor(getChannelNames()[channel], rgb); } public void setChannelGamma(int channel, double gamma) { JSONObject chan = getChannelSetting(channel); try { chan.put("Gamma", gamma); } catch (Exception e) { ReportingUtils.logError(e); } updateChannelLUT(channel); } public void setChannelDisplayRange(int channel, int min, int max) { JSONObject chan = getChannelSetting(channel); try { chan.put("Min", min); chan.put("Max", max); } catch (Exception e) { ReportingUtils.logError(e); } updateChannelContrast(channel); } private JSONObject getChannelSetting(int channel) { try { JSONArray array = imageCache_.getDisplayAndComments().getJSONArray("Channels"); if (array != null) { return array.getJSONObject(channel); } else { return null; } } catch (Exception ex) { ReportingUtils.logError(ex); return null; } } }
package ie.yesequality.yesequality; import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; public class InformationFragment extends Fragment { private PageAdapter pageAdapter; private ViewPager viewPager; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_information, container, false); List<Fragment> fragments = getFragmentList(); pageAdapter = new PageAdapter(getFragmentManager(), fragments); viewPager = (ViewPager) rootView.findViewById(R.id.information_viewpager); if (viewPager != null) { viewPager.setAdapter(pageAdapter); viewPager.setPageTransformer(true, new DepthPageTransformer()); } return rootView; } private List<Fragment> getFragmentList() { List<Fragment> fragments = new ArrayList<Fragment>(); fragments.add(InformationPagesFragment.newInstance(R.drawable.infoicon1, R.string.information_page_string_two, R.string.information_page_string_three, R.color.lilac, "", R.color.white)); fragments.add(InformationPagesFragment.newInstance(R.drawable.infoicon2, R.string.information_page_string_two, R.string.information_page_string_four, R.color.dark_cyan, "", R.color.white)); fragments.add(InformationPagesFragment.newInstance(R.drawable.infoicon3, R.string.information_page_string_two, R.string.information_page_string_five, R.color.navy, "", R.color.white)); fragments.add(InformationPagesFragment.newInstance(R.drawable.infoicon4, R.string.information_page_string_two, R.string.information_page_string_six, R.color.dark_lilac, "", R.color.white)); fragments.add(InformationPagesFragment.newInstance(R.drawable.infoicon5, R.string.information_page_string_seven, R.string.information_page_string_eight, R.color.dark_navy, "http: fragments.add(InformationPagesFragment.newInstance(R.drawable.infoicon6, R.string.information_page_string_nine, R.string.information_page_string_ten, R.color.dark_green, "", R.color.white)); fragments.add(InformationPagesFragment.newInstance(R.drawable.infoicon7, R.string.information_page_string_nine, R.string.information_page_string_eleven, R.color.dark_magenta, "", R.color.white)); fragments.add(InformationPagesFragment.newInstance(R.drawable.infoicon8, R.string.information_page_string_nine, R.string.information_page_string_twelve, R.color.dark_red, "", R.color.white)); fragments.add(InformationPagesFragment.newInstance(R.drawable.infoicon9, R.string.information_page_string_thirteen, R.string.information_page_string_fourteen, R.color.green, "", R.color.white)); fragments.add(InformationPagesFragment.newInstance(R.drawable.ic_yes_color, R.string.information_page_string_seventeen, R.string.information_page_string_eighteen, R.color.white, "http: return fragments; } public class DepthPageTransformer implements ViewPager.PageTransformer { private static final float MIN_SCALE = 0.75f; public void transformPage(View view, float position) { int pageWidth = view.getWidth(); if (position < -1) { // [-Infinity,-1) // This page is way off-screen to the left. view.setAlpha(0); } else if (position <= 0) { // Use the default slide transition when moving to the left page view.setAlpha(1); view.setTranslationX(0); view.setScaleX(1); view.setScaleY(1); } else if (position <= 1) { // Fade the page out. view.setAlpha(1 - position); // Counteract the default slide transition view.setTranslationX(pageWidth * -position); // Scale the page down (between MIN_SCALE and 1) float scaleFactor = MIN_SCALE + (1 - MIN_SCALE) * (1 - Math.abs(position)); view.setScaleX(scaleFactor); view.setScaleY(scaleFactor); } else { // (1,+Infinity] // This page is way off-screen to the right. view.setAlpha(0); } } } }
package com.haulmont.cuba.gui.components; import com.haulmont.chile.core.model.Instance; import com.haulmont.chile.core.model.MetaProperty; import com.haulmont.cuba.core.entity.Entity; import com.haulmont.cuba.core.entity.SoftDelete; import com.haulmont.cuba.gui.WindowManager; import com.haulmont.cuba.gui.data.CollectionDatasource; import com.haulmont.cuba.gui.data.impl.DatasourceImplementation; import java.util.Collection; import java.util.Collections; import java.util.Map; public class ActionsFieldHelper { private ActionsField component; private String entityName; public ActionsFieldHelper(ActionsField component) { this.component = component; MetaProperty metaProperty = component.getMetaProperty(); entityName = metaProperty.getRange().asClass().getName(); } public void createLookupAction() { createLookupAction(entityName + ".browse", WindowManager.OpenType.THIS_TAB, Collections.<String, Object>emptyMap()); } public void createLookupAction(WindowManager.OpenType openType) { createLookupAction(entityName + ".browse", openType, Collections.<String, Object>emptyMap()); } public void createLookupAction(String windowAlias) { createLookupAction(windowAlias, WindowManager.OpenType.THIS_TAB, Collections.<String, Object>emptyMap()); } public void createLookupAction(final String windowAlias, final WindowManager.OpenType openType, final Map<String, Object> params) { Action action = new AbstractAction(ActionsField.LOOKUP) { public void actionPerform(Component componend) { component.getFrame().openLookup(windowAlias, new Window.Lookup.Handler() { public void handleLookup(Collection items) { if (items != null && items.size() > 0) { component.setValue(items.iterator().next()); } } }, openType, params); } @Override public String getCaption() { return ""; } }; component.addAction(action); } public void createOpenAction() { createOpenAction(WindowManager.OpenType.THIS_TAB); } public void createOpenAction(final WindowManager.OpenType openType) { Action action = new AbstractAction(ActionsField.OPEN) { public void actionPerform(Component componend) { Entity entity = component.getValue(); if (entity instanceof SoftDelete && ((SoftDelete) entity).isDeleted()) { return; } if (entity != null) { String windowAlias = ((Instance) entity).getMetaClass().getName() + ".edit"; final Window.Editor editor = component.getFrame().openEditor(windowAlias, entity, openType); editor.addListener(new Window.CloseListener() { public void windowClosed(String actionId) { if (Window.COMMIT_ACTION_ID.equals(actionId)) { Entity item = editor.getItem(); CollectionDatasource optionsDatasource = component.getOptionsDatasource(); if (optionsDatasource != null && optionsDatasource.containsItem(item.getId())) { optionsDatasource.updateItem(item); } boolean modified = component.getDatasource().isModified(); component.setValue(null); component.setValue(item); ((DatasourceImplementation) component.getDatasource()).setModified(modified); } } }); } } @Override public String getCaption() { return ""; } }; component.addAction(action); } }
// modification, are permitted provided that the following conditions are met: // and/or other materials provided with the distribution. // 3. Neither the name of protostuff nor the names of its contributors may be used // to endorse or promote products derived from this software without // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. package com.dyuproject.protostuff.model; import java.util.ArrayList; import java.util.List; import junit.framework.TestCase; /** * @author David Yu * @created Aug 25, 2009 */ public class V22Test extends TestCase { public void testLite() throws Exception { Model taskModel = Model.get(V22Lite.Task.class); Model personModel = Model.get(V22Lite.Person.class); System.err.println(taskModel.getModelMeta()); assertTrue(taskModel.getModelMeta().getPropertyCount()==4); assertTrue(taskModel.getModelMeta().getMinNumber()==1); assertTrue(taskModel.getModelMeta().getMaxNumber()==4); System.err.println(personModel.getModelMeta()); assertTrue(personModel.getModelMeta().getPropertyCount()==7); assertTrue(personModel.getModelMeta().getMinNumber()==1); assertTrue(personModel.getModelMeta().getMaxNumber()==7); V22Lite.Task task = V22Lite.Task.newBuilder() .setId(1) .build(); V22Lite.Task.Builder taskBuilder = task.toBuilder(); V22Lite.Person person = V22Lite.Person.newBuilder() .setId(2) .build(); V22Lite.Person.Builder personBuilder = person.toBuilder(); taskModel.getProperty("name").setValue(task, "foo"); taskModel.getProperty("description").setValue(task, "bar"); taskModel.getProperty("status").setValue(task, V22Lite.Task.Status.STARTED); assertTrue(task.getName().equals("foo")); assertTrue(task.getDescription().equals("bar")); assertTrue(task.getStatus() == V22Lite.Task.Status.STARTED); taskModel.getProperty("name").replaceValueIfNone(task, "foo1"); taskModel.getProperty("description").removeValue(task); assertTrue(task.getName().equals("foo")); assertTrue(!task.hasDescription()); assertTrue(taskModel.getProperty("description").getValue(task)==null); taskModel.getProperty("name").replaceValueIfAny(task, "food"); taskModel.getProperty("description").replaceValueIfAny(task, "bar"); assertTrue(task.getName().equals("food")); assertTrue(!task.hasDescription()); assertTrue(taskModel.getProperty("description").getValue(task)==null); taskModel.getProperty("id").setValue(taskBuilder, 3); taskModel.getProperty("name").setValue(taskBuilder, "foo1"); taskModel.getProperty("description").setValue(taskBuilder, "bar1"); taskModel.getProperty("status").setValue(taskBuilder, V22Lite.Task.Status.COMPLETED); assertTrue(taskBuilder.getId()==3); assertTrue(taskBuilder.getName().equals("foo1")); assertTrue(taskBuilder.getDescription().equals("bar1")); assertTrue(taskBuilder.getStatus() == V22Lite.Task.Status.COMPLETED); personModel.getProperty("firstName").setValue(person, "John"); personModel.getProperty("lastName").setValue(person, "Doe"); personModel.getProperty("aGe").setValue(person, 20); personModel.getProperty("priorityTask").setValue(person, task); assertTrue(person.getFirstName().equals("John")); assertTrue(person.getLastName().equals("Doe")); assertTrue(person.getAGe()==20); assertTrue(person.getPriorityTask(0).getId()==1); personModel.getProperty("id").setValue(personBuilder, 4); personModel.getProperty("priorityTask").setValue(personBuilder, task); personModel.getProperty("delegatedTask").setValue(personBuilder, taskBuilder); taskBuilder = task.toBuilder(); assertTrue(personBuilder.getId()==4); assertTrue(personBuilder.getPriorityTask(0).getId()==task.getId()); assertTrue(personBuilder.getDelegatedTask(0).getId()==3); List<V22Lite.Task> taskList = new ArrayList<V22Lite.Task>(); taskList.add(task); personModel.getProperty("delegatedTask").setValue(personBuilder, taskList); assertTrue(personBuilder.getDelegatedTaskCount()==2); assertTrue(personBuilder.getDelegatedTask(1).getId()==taskList.get(0).getId()); personModel.getProperty("delegatedTask").replaceValueIfNone(personBuilder, task.toBuilder().setId(0)); assertTrue(personBuilder.getDelegatedTaskCount()==2); assertTrue(personBuilder.getDelegatedTask(0).getId()!=0); // this will not replace (but add) if the field is repeated personModel.getProperty("delegatedTask").replaceValueIfAny(personBuilder, task.toBuilder().setId(5)); assertTrue(personBuilder.getDelegatedTaskCount()==3); assertTrue(personBuilder.getDelegatedTask(2).getId()==5); // this will not replace (but add) if the field is repeated personModel.getProperty("delegatedTask").replaceValueIfAny(personBuilder, taskList); assertTrue(personBuilder.getDelegatedTaskCount()==4); assertTrue(personBuilder.getDelegatedTask(3).getId()==taskList.get(0).getId()); personModel.getProperty("priorityTask").replaceValueIfNone(person, task.toBuilder().setId(0).build()); assertTrue(person.getPriorityTask(0).getId()!=0); personModel.getProperty("priorityTask").replaceValueIfAny(person, task.toBuilder().setId(6).build()); assertTrue(person.getPriorityTask(0).getId()==6); Model taskModelR = Model.get(taskModel.getModelMeta(), true); Model personModelR = Model.get(personModel.getModelMeta(), true); assertEquals(task.getName(), taskModelR.getProperty("name").getValue(task)); assertEquals(task.getStatus(), taskModelR.getProperty("status").getValue(task)); assertEquals(person.getFirstName(), "John"); assertEquals(person.getLastName(), "Doe"); assertEquals(person.getFirstName(), personModelR.getProperty("firstName").getValue(person)); assertEquals(person.getLastName(), personModelR.getProperty("lastName").getValue(person)); assertEquals("J", personBuilder.setFirstName("J").getFirstName()); assertEquals("D", personBuilder.setLastName("D").getLastName()); assertEquals(personBuilder.getFirstName(), personModelR.getProperty("firstName").getValue(personBuilder)); assertEquals(personBuilder.getLastName(), personModelR.getProperty("lastName").getValue(personBuilder)); } public void testSpeed() throws Exception { Model taskModel = Model.get(V22Speed.Task.class); Model personModel = Model.get(V22Speed.Person.class); System.err.println(taskModel.getModelMeta()); assertTrue(taskModel.getModelMeta().getPropertyCount()==4); assertTrue(taskModel.getModelMeta().getMinNumber()==1); assertTrue(taskModel.getModelMeta().getMaxNumber()==4); System.err.println(personModel.getModelMeta()); assertTrue(personModel.getModelMeta().getPropertyCount()==7); assertTrue(personModel.getModelMeta().getMinNumber()==1); assertTrue(personModel.getModelMeta().getMaxNumber()==7); V22Speed.Task task = V22Speed.Task.newBuilder() .setId(1) .build(); V22Speed.Task.Builder taskBuilder = task.toBuilder(); V22Speed.Person person = V22Speed.Person.newBuilder() .setId(2) .build(); V22Speed.Person.Builder personBuilder = person.toBuilder(); taskModel.getProperty("name").setValue(task, "foo"); taskModel.getProperty("description").setValue(task, "bar"); taskModel.getProperty("status").setValue(task, V22Speed.Task.Status.STARTED); assertTrue(task.getName().equals("foo")); assertTrue(task.getDescription().equals("bar")); assertTrue(task.getStatus() == V22Speed.Task.Status.STARTED); taskModel.getProperty("name").replaceValueIfNone(task, "foo1"); taskModel.getProperty("description").removeValue(task); assertTrue(task.getName().equals("foo")); assertTrue(!task.hasDescription()); assertTrue(taskModel.getProperty("description").getValue(task)==null); taskModel.getProperty("name").replaceValueIfAny(task, "food"); taskModel.getProperty("description").replaceValueIfAny(task, "bar"); assertTrue(task.getName().equals("food")); assertTrue(!task.hasDescription()); assertTrue(taskModel.getProperty("description").getValue(task)==null); taskModel.getProperty("id").setValue(taskBuilder, 3); taskModel.getProperty("name").setValue(taskBuilder, "foo1"); taskModel.getProperty("description").setValue(taskBuilder, "bar1"); taskModel.getProperty("status").setValue(taskBuilder, V22Speed.Task.Status.COMPLETED); assertTrue(taskBuilder.getId()==3); assertTrue(taskBuilder.getName().equals("foo1")); assertTrue(taskBuilder.getDescription().equals("bar1")); assertTrue(taskBuilder.getStatus() == V22Speed.Task.Status.COMPLETED); personModel.getProperty("firstName").setValue(person, "John"); personModel.getProperty("lastName").setValue(person, "Doe"); personModel.getProperty("aGe").setValue(person, 20); personModel.getProperty("priorityTask").setValue(person, task); assertTrue(person.getFirstName().equals("John")); assertTrue(person.getLastName().equals("Doe")); assertTrue(person.getAGe()==20); assertTrue(person.getPriorityTask(0).getId()==1); personModel.getProperty("id").setValue(personBuilder, 4); personModel.getProperty("priorityTask").setValue(personBuilder, task); personModel.getProperty("delegatedTask").setValue(personBuilder, taskBuilder); taskBuilder = task.toBuilder(); assertTrue(personBuilder.getId()==4); assertTrue(personBuilder.getPriorityTask(0).getId()==task.getId()); assertTrue(personBuilder.getDelegatedTask(0).getId()==3); List<V22Speed.Task> taskList = new ArrayList<V22Speed.Task>(); taskList.add(task); personModel.getProperty("delegatedTask").setValue(personBuilder, taskList); assertTrue(personBuilder.getDelegatedTaskCount()==2); assertTrue(personBuilder.getDelegatedTask(1).getId()==taskList.get(0).getId()); personModel.getProperty("delegatedTask").replaceValueIfNone(personBuilder, task.toBuilder().setId(0)); assertTrue(personBuilder.getDelegatedTaskCount()==2); assertTrue(personBuilder.getDelegatedTask(0).getId()!=0); // this will not replace (but add) if the field is repeated personModel.getProperty("delegatedTask").replaceValueIfAny(personBuilder, task.toBuilder().setId(5)); assertTrue(personBuilder.getDelegatedTaskCount()==3); assertTrue(personBuilder.getDelegatedTask(2).getId()==5); // this will not replace (but add) if the field is repeated personModel.getProperty("delegatedTask").replaceValueIfAny(personBuilder, taskList); assertTrue(personBuilder.getDelegatedTaskCount()==4); assertTrue(personBuilder.getDelegatedTask(3).getId()==taskList.get(0).getId()); personModel.getProperty("priorityTask").replaceValueIfNone(person, task.toBuilder().setId(0).build()); assertTrue(person.getPriorityTask(0).getId()!=0); personModel.getProperty("priorityTask").replaceValueIfAny(person, task.toBuilder().setId(6).build()); assertTrue(person.getPriorityTask(0).getId()==6); Model taskModelR = Model.get(taskModel.getModelMeta(), true); Model personModelR = Model.get(personModel.getModelMeta(), true); assertEquals(task.getName(), taskModelR.getProperty("name").getValue(task)); assertEquals(task.getStatus(), taskModelR.getProperty("status").getValue(task)); assertEquals(person.getFirstName(), "John"); assertEquals(person.getLastName(), "Doe"); assertEquals(person.getFirstName(), personModelR.getProperty("firstName").getValue(person)); assertEquals(person.getLastName(), personModelR.getProperty("lastName").getValue(person)); assertEquals("J", personBuilder.setFirstName("J").getFirstName()); assertEquals("D", personBuilder.setLastName("D").getLastName()); assertEquals(personBuilder.getFirstName(), personModelR.getProperty("firstName").getValue(personBuilder)); assertEquals(personBuilder.getLastName(), personModelR.getProperty("lastName").getValue(personBuilder)); } }
package com.jme3.monkeyzone; import com.jme3.monkeyzone.controls.UserCommandControl; import com.jme3.app.SimpleApplication; import com.jme3.bullet.BulletAppState; import com.jme3.monkeyzone.controls.DefaultHUDControl; import com.jme3.monkeyzone.controls.UserInputControl; import com.jme3.monkeyzone.messages.ActionMessage; import com.jme3.monkeyzone.messages.AutoControlMessage; import com.jme3.monkeyzone.messages.ChatMessage; import com.jme3.monkeyzone.messages.ManualControlMessage; import com.jme3.monkeyzone.messages.ServerAddEntityMessage; import com.jme3.monkeyzone.messages.ServerAddPlayerMessage; import com.jme3.monkeyzone.messages.ServerDisableEntityMessage; import com.jme3.monkeyzone.messages.ServerEffectMessage; import com.jme3.monkeyzone.messages.ServerEnableEntityMessage; import com.jme3.monkeyzone.messages.ServerEnterEntityMessage; import com.jme3.monkeyzone.messages.ServerEntityDataMessage; import com.jme3.monkeyzone.messages.ServerRemoveEntityMessage; import com.jme3.monkeyzone.messages.ServerRemovePlayerMessage; import com.jme3.monkeyzone.messages.StartGameMessage; import com.jme3.network.Network; import com.jme3.network.NetworkClient; import com.jme3.network.physicssync.PhysicsSyncManager; import com.jme3.network.physicssync.SyncCharacterMessage; import com.jme3.network.physicssync.SyncRigidBodyMessage; import com.jme3.niftygui.NiftyJmeDisplay; import com.jme3.renderer.RenderManager; import com.jme3.system.AppSettings; import de.lessvoid.nifty.Nifty; import de.lessvoid.nifty.controls.Label; import de.lessvoid.nifty.controls.ListBox; import de.lessvoid.nifty.controls.TextField; import de.lessvoid.nifty.screen.Screen; import de.lessvoid.nifty.screen.ScreenController; import java.io.IOException; import java.util.concurrent.Callable; import java.util.logging.Level; import java.util.logging.Logger; /** * The client Main class, also the screen controller for most parts of the * login and lobby GUI * @author normenhansen */ public class ClientMain extends SimpleApplication implements ScreenController { private static ClientMain app; public static void main(String[] args) { for (int i = 0; i < args.length; i++) { String string = args[i]; if ("-server".equals(string)) { ServerMain.main(args); return; } } AppSettings settings = new AppSettings(true); settings.setFrameRate(Globals.SCENE_FPS); settings.setSettingsDialogImage("/Interface/Images/splash-small.jpg"); settings.setTitle("MonkeyZone"); Util.registerSerializers(); Util.setLogLevels(true); app = new ClientMain(); app.setSettings(settings); app.setPauseOnLostFocus(false); app.start(); } private WorldManager worldManager; private PhysicsSyncManager syncManager; private ClientEffectsManager effectsManager; private UserCommandControl commandControl; private Nifty nifty; private NiftyJmeDisplay niftyDisplay; private Label statusText; private NetworkClient client; private ClientNetListener listenerManager; private BulletAppState bulletState; // private ChaseCamera chaseCam; @Override public void simpleInitApp() { startNifty(); client = Network.createClient(); bulletState = new BulletAppState(); if (Globals.PHYSICS_THREADED) { bulletState.setThreadingType(BulletAppState.ThreadingType.PARALLEL); } getStateManager().attach(bulletState); bulletState.getPhysicsSpace().setAccuracy(Globals.PHYSICS_FPS); if(Globals.PHYSICS_DEBUG){ bulletState.setDebugEnabled(true); } inputManager.setCursorVisible(true); flyCam.setEnabled(false); // chaseCam = new ChaseCamera(cam, inputManager); // chaseCam.setSmoothMotion(true); // chaseCam.setChasingSensitivity(100); // chaseCam.setTrailingEnabled(true); syncManager = new PhysicsSyncManager(app, client); syncManager.setMaxDelay(Globals.NETWORK_MAX_PHYSICS_DELAY); syncManager.setMessageTypes(AutoControlMessage.class, ManualControlMessage.class, ActionMessage.class, SyncCharacterMessage.class, SyncRigidBodyMessage.class, ServerEntityDataMessage.class, ServerEnterEntityMessage.class, ServerAddEntityMessage.class, ServerAddPlayerMessage.class, ServerEffectMessage.class, ServerEnableEntityMessage.class, ServerDisableEntityMessage.class, ServerRemoveEntityMessage.class, ServerRemovePlayerMessage.class); stateManager.attach(syncManager); //ai manager for controlling units commandControl = new UserCommandControl(nifty.getScreen("default_hud"), inputManager); //world manager, manages entites and server commands worldManager = new WorldManager(this, rootNode, commandControl); //adding/creating controls later attached to user controlled spatial worldManager.addUserControl(new UserInputControl(inputManager, cam)); worldManager.addUserControl(commandControl); worldManager.addUserControl(new DefaultHUDControl(nifty.getScreen("default_hud"))); stateManager.attach(worldManager); //effects manager for playing effects effectsManager = new ClientEffectsManager(); stateManager.attach(effectsManager); //register effects manager and world manager with sync manager so that messages can apply their data syncManager.addObject(-2, effectsManager); syncManager.addObject(-1, worldManager); listenerManager = new ClientNetListener(this, client, worldManager, effectsManager); } /** * starts the nifty gui system */ private void startNifty() { setDisplayStatView(false); niftyDisplay = new NiftyJmeDisplay(assetManager, inputManager, audioRenderer, guiViewPort); nifty = niftyDisplay.getNifty(); try { nifty.fromXml("Interface/ClientUI.xml", "load_game", this); } catch (Exception ex) { ex.printStackTrace(); } statusText = nifty.getScreen("load_game").findNiftyControl("status_text", Label.class); guiViewPort.addProcessor(niftyDisplay); } /** * sets the status text of the main login view, threadsafe * @param text */ public void setStatusText(final String text) { enqueue(new Callable<Void>() { public Void call() throws Exception { statusText.setText(text); return null; } }); } /** * updates the list of players in the lobby gui, threadsafe */ public void updatePlayerData() { Logger.getLogger(ClientMain.class.getName()).log(Level.INFO, "Updating player data"); enqueue(new Callable<Void>() { public Void call() throws Exception { Screen screen = nifty.getScreen("lobby"); ListBox playerList = screen.findNiftyControl("players_list", ListBox.class); playerList.clear(); for(PlayerData data : PlayerData.getHumanPlayers()) { Logger.getLogger(ClientMain.class.getName()).log(Level.INFO, "List player {0}", data); playerList.addItem(data.getStringData("name")); } return null; } }); } /** * add text to chat window, threadsafe * @param text */ public void addChat(final String text) { enqueue(new Callable<Void>() { public Void call() throws Exception { Screen screen = nifty.getScreen("loby"); ListBox chatList = screen.findNiftyControl("chat_list", ListBox.class); chatList.addItem(text); return null; } }); } /** * gets the text currently entered in the textbox and sends it as a chat message */ public void sendChat() { Logger.getLogger(ClientMain.class.getName()).log(Level.INFO, "Send chat message"); enqueue(new Callable<Void>() { public Void call() throws Exception { Screen screen = nifty.getScreen("lobby"); TextField control = screen.findNiftyControl("", TextField.class); String text = control.getRealText(); sendMessage(text); control.setText(""); return null; } }); } //FIXME: nifty cannot find sendChat() when sendChat(String text) is existing too public void sendMessage(String text) { client.send(new ChatMessage(text)); } /** * connect to server (called from gui) */ public void connect() { //TODO: not connect when already trying.. final String userName = nifty.getScreen("load_game").findNiftyControl("username_text", TextField.class).getRealText(); if (userName.trim().length() == 0) { setStatusText("Username invalid"); return; } listenerManager.setName(userName); statusText.setText("Connecting.."); try { client.connectToServer(Globals.DEFAULT_SERVER, Globals.DEFAULT_PORT_TCP, Globals.DEFAULT_PORT_UDP); client.start(); } catch (IOException ex) { setStatusText(ex.getMessage()); Logger.getLogger(ClientMain.class.getName()).log(Level.SEVERE, null, ex); } } /** * brings up the lobby display */ public void lobby() { // chaseCam.setDragToRotate(false); inputManager.setCursorVisible(true); nifty.gotoScreen("lobby"); } /** * send message to start selected game */ public void startGame() { //TODO: map selection client.send(new StartGameMessage("Scenes/MonkeyZone.j3o")); } /** * loads a level, basically does everything on a seprate thread except * updating the UI and attaching the level * @param name * @param modelNames */ public void loadLevel(final String name, final String[] modelNames) { final Label statusText = nifty.getScreen("load_level").findNiftyControl("status_text", Label.class); if (name.equals("null")) { enqueue(new Callable<Void>() { public Void call() throws Exception { worldManager.closeLevel(); lobby(); return null; } }); return; } new Thread(new Runnable() { public void run() { try { enqueue(new Callable<Void>() { public Void call() throws Exception { nifty.gotoScreen("load_level"); statusText.setText("Loading Terrain.."); return null; } }).get(); worldManager.loadLevel(name); enqueue(new Callable<Void>() { public Void call() throws Exception { statusText.setText("Creating NavMesh.."); return null; } }).get(); worldManager.createNavMesh(); enqueue(new Callable<Void>() { public Void call() throws Exception { statusText.setText("Loading Models.."); return null; } }).get(); worldManager.preloadModels(modelNames); enqueue(new Callable<Void>() { public Void call() throws Exception { worldManager.attachLevel(); statusText.setText("Done Loading!"); nifty.gotoScreen("default_hud"); inputManager.setCursorVisible(false); // chaseCam.setDragToRotate(false); return null; } }).get(); } catch (Exception e) { e.printStackTrace(); } } }).start(); } @Override public void bind(Nifty nifty, Screen screen) { } @Override public void onStartScreen() { } @Override public void onEndScreen() { } @Override public void simpleUpdate(float tpf) { } @Override public void simpleRender(RenderManager rm) { } @Override public void destroy() { try { client.close(); } catch (Exception ex) { Logger.getLogger(ClientMain.class.getName()).log(Level.SEVERE, null, ex); } super.destroy(); } }
package com.cinnober.msgcodec.blink; import com.cinnober.msgcodec.ByteSink; import com.cinnober.msgcodec.ByteSource; import com.cinnober.msgcodec.DecodeException; import com.cinnober.msgcodec.ProtocolDictionary; import com.cinnober.msgcodec.StreamCodec; import com.cinnober.msgcodec.StreamCodecInstantiationException; import com.cinnober.msgcodec.util.ConcurrentBufferPool; import com.cinnober.msgcodec.util.InputStreamSource; import com.cinnober.msgcodec.util.LimitInputStream; import com.cinnober.msgcodec.util.OutputStreamSink; import com.cinnober.msgcodec.util.Pool; import com.cinnober.msgcodec.util.TempOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Constructor; import java.util.Objects; import java.util.Stack; import java.util.logging.Level; import java.util.logging.Logger; public class BlinkCodec implements StreamCodec { private static final Logger log = Logger.getLogger(BlinkCodec.class.getName()); private final GeneratedCodec generatedCodec; private final ProtocolDictionary dictionary; private final Pool<byte[]> bufferPool; private final int maxBinarySize; private final int maxSequenceLength; /** * Create a Blink codec, with an internal buffer pool of 8192 bytes. * * @param dictionary the definition of the messages to be understood by the codec. */ BlinkCodec(ProtocolDictionary dictionary) throws StreamCodecInstantiationException { this(dictionary, new ConcurrentBufferPool(8192, 1)); } /** * Create a Blink codec. * * @param dictionary the definition of the messages to be understood by the codec. * @param bufferPool the buffer pool, needed for temporary storage while <em>encoding</em>. */ public BlinkCodec(ProtocolDictionary dictionary, Pool<byte[]> bufferPool) throws StreamCodecInstantiationException { this(dictionary, bufferPool, 10 * 1048576, 1_000_000, CodecOption.AUTOMATIC); } /** * Create a Blink codec. * * @param dictionary the definition of the messages to be understood by the codec. * @param bufferPool the buffer pool, needed for temporary storage while <em>encoding</em>. * @param maxBinarySize the maximum binary size (including strings) allowed while decoding, or -1 for no limit. * @param maxSequenceLength the maximum sequence length allowed while decoding, or -1 for no limit. * @param codecOption controls which kind of underlying codec to use, not null. */ BlinkCodec(ProtocolDictionary dictionary, Pool<byte[]> bufferPool, int maxBinarySize, int maxSequenceLength, CodecOption codecOption) throws StreamCodecInstantiationException { if (!dictionary.isBound()) { throw new IllegalArgumentException("ProtocolDictionary not bound"); } this.bufferPool = bufferPool; Objects.requireNonNull(codecOption); this.maxBinarySize = maxBinarySize; this.maxSequenceLength = maxSequenceLength; this.dictionary = dictionary; GeneratedCodec generatedCodecTmp = null; if (codecOption != CodecOption.INSTRUCTION_CODEC_ONLY) { try { Class<GeneratedCodec> generatedCodecClass = GeneratedCodecClassLoader.getInstance().getGeneratedCodecClass(dictionary); Constructor<GeneratedCodec> constructor = generatedCodecClass.getConstructor(new Class<?>[]{ BlinkCodec.class, ProtocolDictionary.class }); generatedCodecTmp = constructor.newInstance(this, dictionary); } catch (Exception e) { log.log(Level.WARNING, "Could instantiate generated codec for dictionary UID " + dictionary.getUID(), e); if (codecOption == CodecOption.DYNAMIC_BYTECODE_CODEC_ONLY) { throw new StreamCodecInstantiationException(e); } log.log(Level.INFO, "Fallback to (slower) instruction based codec for dictionary UID {0}", dictionary.getUID()); } } if (generatedCodecTmp == null) { generatedCodecTmp = new InstructionCodec(this, dictionary); } generatedCodec = generatedCodecTmp; } Pool<byte[]> bufferPool() { return bufferPool; } // PENDING: this method should be package private. For some reason the generated codec cannot access package private stuff... public int getMaxBinarySize() { return maxBinarySize; } int getMaxSequenceLength() { return maxSequenceLength; } ProtocolDictionary getDictionary() { return dictionary; } @Override public void encode(Object group, OutputStream out) throws IOException { encode(group, new OutputStreamSink(out)); } public void encode(Object group, ByteSink out) throws IOException { generatedCodec.writeDynamicGroup(out, group); } @Override public Object decode(InputStream in) throws IOException { return decode(new InputStreamSource(in)); } public Object decode(ByteSource in) throws IOException { try { return generatedCodec.readDynamicGroupNull(in); } catch(GroupDecodeException|FieldDecodeException e) { Throwable t = e; StringBuilder str = new StringBuilder(); for (;;) { if (t instanceof GroupDecodeException) { str.append('(').append(((GroupDecodeException)t).getGroupName()).append(')'); t = t.getCause(); } else if(t instanceof FieldDecodeException) { str.append('.').append(((FieldDecodeException)t).getFieldName()); t = t.getCause(); } else { throw new DecodeException("Could not decode field "+str.toString(), t); } } } } }
package org.torquebox.web.component; import java.io.IOException; import java.util.List; import org.jboss.as.server.deployment.Attachments; import org.jboss.as.server.deployment.DeploymentPhaseContext; import org.jboss.as.server.deployment.DeploymentUnit; import org.jboss.as.server.deployment.DeploymentUnitProcessingException; import org.jboss.as.server.deployment.module.ResourceRoot; import org.jboss.logging.Logger; import org.jboss.msc.service.ServiceBuilder; import org.jboss.msc.service.ServiceController.Mode; import org.jboss.msc.service.ServiceName; import org.jboss.vfs.VirtualFile; import org.torquebox.core.as.DeploymentNotifier; import org.torquebox.core.component.BaseRubyComponentDeployer; import org.torquebox.core.component.ComponentEval; import org.torquebox.core.component.ComponentResolver; import org.torquebox.core.component.ComponentResolverService; import org.torquebox.web.as.WebServices; import org.torquebox.web.rack.RackApplicationMetaData; public class RackApplicationComponentResolverInstaller extends BaseRubyComponentDeployer { @Override public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException { DeploymentUnit unit = phaseContext.getDeploymentUnit(); RackApplicationMetaData rackAppMetaData = unit.getAttachment( RackApplicationMetaData.ATTACHMENT_KEY ); if (rackAppMetaData == null) { return; } ResourceRoot resourceRoot = unit.getAttachment( Attachments.DEPLOYMENT_ROOT ); VirtualFile root = resourceRoot.getRoot(); ComponentEval instantiator = new ComponentEval(); try { instantiator.setCode( getCode( rackAppMetaData.getRackUpScript( root ) ) ); instantiator.setLocation( rackAppMetaData.getRackUpScriptFile( root ).toURL().toString() ); } catch (IOException e) { throw new DeploymentUnitProcessingException( e ); } ServiceName serviceName = WebServices.rackApplicationComponentResolver( unit ); ComponentResolver resolver = createComponentResolver( unit ); resolver.setComponentInstantiator( instantiator ); resolver.setComponentName( serviceName.getCanonicalName() ); resolver.setComponentWrapperClass( RackApplicationComponent.class ); log.info( "Installing Rack app component resolver: " + serviceName ); ComponentResolverService service = new ComponentResolverService( resolver ); ServiceBuilder<ComponentResolver> builder = phaseContext.getServiceTarget().addService( serviceName, service ); builder.setInitialMode( Mode.ON_DEMAND ); addInjections( phaseContext, resolver, getInjectionPathPrefixes( phaseContext ), builder ); builder.install(); // Add to our notifier's watch list unit.addToAttachmentList( DeploymentNotifier.SERVICES_ATTACHMENT_KEY, serviceName ); } protected List<String> getInjectionPathPrefixes(DeploymentPhaseContext phaseContext) { DeploymentUnit unit = phaseContext.getDeploymentUnit(); RackApplicationMetaData rackAppMetaData = unit.getAttachment( RackApplicationMetaData.ATTACHMENT_KEY ); List<String> prefixes = defaultInjectionPathPrefixes(); prefixes.add( rackAppMetaData.getRackUpScriptLocation() ); prefixes.add( "app/controllers/" ); prefixes.add( "app/helpers/" ); return prefixes; } protected String getCode(String rackupScript) { return "require %q(rack)\nRack::Builder.new{(\n" + rackupScript + "\n)}.to_app"; } @Override public void undeploy(DeploymentUnit context) { // TODO Auto-generated method stub } private static final Logger log = Logger.getLogger( "org.torquebox.web.component" ); }
package org.navalplanner.web.limitingresources; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.joda.time.DateTime; import org.joda.time.Period; import org.joda.time.format.DateTimeFormat; import org.joda.time.format.DateTimeFormatter; import org.navalplanner.business.planner.limiting.entities.LimitingResourceQueueElement; import org.navalplanner.business.resources.daos.IResourceDAO; import org.navalplanner.business.resources.entities.LimitingResourceQueue; import org.springframework.beans.factory.annotation.Autowired; import org.zkoss.ganttz.timetracker.TimeTracker; import org.zkoss.ganttz.timetracker.TimeTracker.IDetailItemFilter; import org.zkoss.ganttz.timetracker.TimeTrackerComponent; import org.zkoss.ganttz.timetracker.zoom.DetailItem; import org.zkoss.ganttz.timetracker.zoom.IZoomLevelChangedListener; import org.zkoss.ganttz.timetracker.zoom.ZoomLevel; import org.zkoss.ganttz.util.ComponentsFinder; import org.zkoss.ganttz.util.Interval; import org.zkoss.ganttz.util.MutableTreeModel; import org.zkoss.zk.au.out.AuInvoke; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.HtmlMacroComponent; import org.zkoss.zk.ui.event.Event; import org.zkoss.zk.ui.event.EventListener; import org.zkoss.zk.ui.event.Events; import org.zkoss.zul.Button; import org.zkoss.zul.ListModel; import org.zkoss.zul.Listbox; import org.zkoss.zul.Listitem; import org.zkoss.zul.Separator; import org.zkoss.zul.SimpleListModel; public class LimitingResourcesPanel extends HtmlMacroComponent { public interface IToolbarCommand { public void doAction(); public String getLabel(); public String getImage(); } private LimitingResourcesController limitingResourcesController; private TimeTrackerComponent timeTrackerComponent; private LimitingResourcesLeftPane leftPane; private QueueListComponent queueListComponent; private MutableTreeModel<LimitingResourceQueue> treeModel; private TimeTracker timeTracker; private Listbox listZoomLevels; private Button paginationDownButton; private Button paginationUpButton; private Listbox horizontalPagination; private Component insertionPointLeftPanel; private Component insertionPointRightPanel; private Component insertionPointTimetracker; public void paginationDown() { horizontalPagination.setSelectedIndex(horizontalPagination .getSelectedIndex() - 1); goToSelectedHorizontalPage(); } public void paginationUp() { horizontalPagination.setSelectedIndex(Math.max(1, horizontalPagination .getSelectedIndex() + 1)); goToSelectedHorizontalPage(); } @Autowired IResourceDAO resourcesDAO; private LimitingDependencyList dependencyList = new LimitingDependencyList( this); private PaginatorFilter paginatorFilter; private TimeTrackerComponent timeTrackerHeader; private IZoomLevelChangedListener zoomChangedListener; /** * Returns the closest upper {@link LimitingResourcesPanel} instance going * all the way up from comp * * @param comp * @return */ public static LimitingResourcesPanel getLimitingResourcesPanel( Component comp) { if (comp == null) { return null; } if (comp instanceof LimitingResourcesPanel) { return (LimitingResourcesPanel) comp; } return getLimitingResourcesPanel(comp.getParent()); } public LimitingResourcesPanel( LimitingResourcesController limitingResourcesController, TimeTracker timeTracker) { init(limitingResourcesController, timeTracker); } public void init(LimitingResourcesController limitingResourcesController, TimeTracker timeTracker) { this.limitingResourcesController = limitingResourcesController; this.timeTracker = timeTracker; this.setVariable("limitingResourcesController", limitingResourcesController, true); treeModel = createModelForTree(); timeTrackerComponent = timeTrackerForLimitingResourcesPanel(timeTracker); queueListComponent = new QueueListComponent(this, timeTracker, treeModel); leftPane = new LimitingResourcesLeftPane(treeModel, queueListComponent); } public void appendQueueElementToQueue(LimitingResourceQueueElement element) { queueListComponent.appendQueueElement(element); dependencyList.addDependenciesFor(element); } public void removeQueueElementFrom(LimitingResourceQueue queue, LimitingResourceQueueElement element) { queueListComponent.removeQueueElementFrom(queue, element); dependencyList.removeDependenciesFor(element); } private MutableTreeModel<LimitingResourceQueue> createModelForTree() { MutableTreeModel<LimitingResourceQueue> result = MutableTreeModel .create(LimitingResourceQueue.class); for (LimitingResourceQueue LimitingResourceQueue : getLimitingResourceQueues()) { result.addToRoot(LimitingResourceQueue); } return result; } private List<LimitingResourceQueue> getLimitingResourceQueues() { return limitingResourcesController.getLimitingResourceQueues(); } public ListModel getZoomLevels() { ZoomLevel[] selectableZoomlevels = { ZoomLevel.DETAIL_THREE, ZoomLevel.DETAIL_FOUR, ZoomLevel.DETAIL_FIVE, ZoomLevel.DETAIL_SIX }; return new SimpleListModel(selectableZoomlevels); } public void setZoomLevel(final ZoomLevel zoomLevel) { timeTracker.setZoomLevel(zoomLevel); } public void zoomIncrease() { timeTracker.zoomIncrease(); } public void zoomDecrease() { timeTracker.zoomDecrease(); } public void add(final IToolbarCommand... commands) { Component toolbar = getToolbar(); Separator separator = getSeparator(); for (IToolbarCommand c : commands) { toolbar.insertBefore(asButton(c), separator); } } private Button asButton(final IToolbarCommand c) { Button result = new Button(); result.addEventListener(Events.ON_CLICK, new EventListener() { @Override public void onEvent(Event event) throws Exception { c.doAction(); } }); if (!StringUtils.isEmpty(c.getImage())) { result.setImage(c.getImage()); result.setTooltiptext(c.getLabel()); } else { result.setLabel(c.getLabel()); } return result; } @SuppressWarnings("unchecked") private Separator getSeparator() { List<Component> children = getToolbar().getChildren(); Separator separator = ComponentsFinder.findComponentsOfType( Separator.class, children).get(0); return separator; } private Component getToolbar() { Component toolbar = getFellow("toolbar"); return toolbar; } private TimeTrackerComponent timeTrackerForLimitingResourcesPanel( TimeTracker timeTracker) { return new TimeTrackerComponent(timeTracker) { @Override protected void scrollHorizontalPercentage(int pixelsDisplacement) { response("", new AuInvoke(queueListComponent, "adjustScrollHorizontalPosition", pixelsDisplacement + "")); } }; } @Override public void afterCompose() { super.afterCompose(); paginatorFilter = new PaginatorFilter(); initializeBindings(); listZoomLevels .setSelectedIndex(timeTracker.getDetailLevel().ordinal() - 2); // Pagination stuff paginationUpButton.setDisabled(paginatorFilter.isLastPage()); paginatorFilter.setInterval(timeTracker.getRealInterval()); timeTracker.setFilter(paginatorFilter); // Insert leftPane component with limitingresources list insertionPointLeftPanel.appendChild(leftPane); leftPane.afterCompose(); insertionPointRightPanel.appendChild(timeTrackerComponent); insertionPointRightPanel.appendChild(queueListComponent); queueListComponent.afterCompose(); dependencyList = generateDependencyComponentsList(); if (dependencyList != null) { dependencyList.afterCompose(); insertionPointRightPanel.appendChild(dependencyList); } zoomChangedListener = new IZoomLevelChangedListener() { @Override public void zoomLevelChanged(ZoomLevel newDetailLevel) { rebuildDependencies(); timeTracker.resetMapper(); paginatorFilter.setInterval(timeTracker.getRealInterval()); timeTracker.setFilter(paginatorFilter); reloadPanelComponents(); paginatorFilter.populateHorizontalListbox(); paginatorFilter.goToHorizontalPage(0); reloadComponent(); // Reset mapper for first detail if (newDetailLevel == ZoomLevel.DETAIL_THREE) { timeTracker.resetMapper(); queueListComponent.invalidate(); queueListComponent.afterCompose(); rebuildDependencies(); } } }; this.timeTracker.addZoomListener(zoomChangedListener); // Insert timetracker headers timeTrackerHeader = createTimeTrackerHeader(); insertionPointTimetracker.appendChild(timeTrackerHeader); timeTrackerHeader.afterCompose(); timeTrackerComponent.afterCompose(); paginatorFilter.populateHorizontalListbox(); } private void rebuildDependencies() { dependencyList.getChildren().clear(); insertionPointRightPanel.appendChild(dependencyList); dependencyList = generateDependencyComponentsList(); dependencyList.afterCompose(); } private void initializeBindings() { // Zoom and pagination listZoomLevels = (Listbox) getFellow("listZoomLevels"); horizontalPagination = (Listbox) getFellow("horizontalPagination"); paginationUpButton = (Button) getFellow("paginationUpButton"); paginationDownButton = (Button) getFellow("paginationDownButton"); insertionPointLeftPanel = getFellow("insertionPointLeftPanel"); insertionPointRightPanel = getFellow("insertionPointRightPanel"); insertionPointTimetracker = getFellow("insertionPointTimetracker"); } private void reloadPanelComponents() { timeTrackerComponent.getChildren().clear(); if (timeTrackerHeader != null) { timeTrackerHeader.afterCompose(); timeTrackerComponent.afterCompose(); } dependencyList.invalidate(); } private LimitingDependencyList generateDependencyComponentsList() { Set<LimitingResourceQueueElement> queueElements = queueListComponent .getLimitingResourceElementToQueueTaskMap().keySet(); for (LimitingResourceQueueElement each : queueElements) { dependencyList.addDependenciesFor(each); } return dependencyList; } public Map<LimitingResourceQueueElement, QueueTask> getQueueTaskMap() { return queueListComponent.getLimitingResourceElementToQueueTaskMap(); } public void clearComponents() { getFellow("insertionPointLeftPanel").getChildren().clear(); getFellow("insertionPointRightPanel").getChildren().clear(); getFellow("insertionPointTimetracker").getChildren().clear(); } public TimeTrackerComponent getTimeTrackerComponent() { return timeTrackerComponent; } private TimeTrackerComponent createTimeTrackerHeader() { return new TimeTrackerComponent(timeTracker) { @Override protected void scrollHorizontalPercentage(int pixelsDisplacement) { } }; } public void unschedule(QueueTask task) { LimitingResourceQueueElement queueElement = task.getLimitingResourceQueueElement(); LimitingResourceQueue queue = queueElement.getLimitingResourceQueue(); limitingResourcesController.unschedule(task); removeQueueTask(task); dependencyList.removeDependenciesFor(queueElement); queueListComponent.removeQueueElementFrom(queue, queueElement); } private void removeQueueTask(QueueTask task) { task.detach(); } public void moveQueueTask(QueueTask queueTask) { if (limitingResourcesController.moveTask(queueTask.getLimitingResourceQueueElement())) { removeQueueTask(queueTask); } } public void editResourceAllocation(QueueTask queueTask) { limitingResourcesController.editResourceAllocation(queueTask .getLimitingResourceQueueElement()); } public void removeDependenciesFor(LimitingResourceQueueElement element) { dependencyList.removeDependenciesFor(element); } public void addDependenciesFor(LimitingResourceQueueElement element) { dependencyList.addDependenciesFor(element); } public void refreshQueues(Set<LimitingResourceQueue> queues) { for (LimitingResourceQueue each: queues) { refreshQueue(each); } } public void refreshQueue(LimitingResourceQueue queue) { dependencyList.removeDependenciesFor(queue); queueListComponent.refreshQueue(queue); } public void goToSelectedHorizontalPage() { paginatorFilter.goToHorizontalPage(horizontalPagination .getSelectedIndex()); reloadComponent(); } public void reloadComponent() { timeTrackerHeader.recreate(); timeTrackerComponent.recreate(); dependencyList.clear(); queueListComponent.invalidate(); queueListComponent.afterCompose(); queueListComponent.refreshQueues(); rebuildDependencies(); } private class PaginatorFilter implements IDetailItemFilter { private DateTime intervalStart; private DateTime intervalEnd; private DateTime paginatorStart; private DateTime paginatorEnd; @Override public Interval getCurrentPaginationInterval() { return new Interval(paginatorStart.toDate(), paginatorEnd.toDate()); } private Period intervalIncrease() { switch (timeTracker.getDetailLevel()) { case DETAIL_ONE: return Period.years(5); case DETAIL_TWO: return Period.years(5); case DETAIL_THREE: return Period.years(2); case DETAIL_FOUR: return Period.months(12); case DETAIL_FIVE: return Period.weeks(12); case DETAIL_SIX: return Period.weeks(12); } // Default month return Period.years(2); } public void setInterval(Interval realInterval) { intervalStart = realInterval.getStart().toDateTimeAtStartOfDay(); intervalEnd = realInterval.getFinish().toDateTimeAtStartOfDay(); paginatorStart = intervalStart; paginatorEnd = intervalStart.plus(intervalIncrease()); if ((paginatorEnd.plus(intervalIncrease()).isAfter(intervalEnd))) { paginatorEnd = intervalEnd; } updatePaginationButtons(); } @Override public void resetInterval() { setInterval(timeTracker.getRealInterval()); } @Override public Collection<DetailItem> selectsFirstLevel( Collection<DetailItem> firstLevelDetails) { ArrayList<DetailItem> result = new ArrayList<DetailItem>(); for (DetailItem each : firstLevelDetails) { if ((each.getStartDate() == null) || !(each.getStartDate().isBefore(paginatorStart)) && (each.getStartDate().isBefore(paginatorEnd))) { result.add(each); } } return result; } @Override public Collection<DetailItem> selectsSecondLevel( Collection<DetailItem> secondLevelDetails) { ArrayList<DetailItem> result = new ArrayList<DetailItem>(); for (DetailItem each : secondLevelDetails) { if ((each.getStartDate() == null) || !(each.getStartDate().isBefore(paginatorStart)) && (each.getStartDate().isBefore(paginatorEnd))) { result.add(each); } } return result; } public void populateHorizontalListbox() { horizontalPagination.getItems().clear(); DateTimeFormatter df = DateTimeFormat.forPattern("dd/MMM/yyyy"); DateTime intervalStart = timeTracker.getRealInterval().getStart() .toDateTimeAtStartOfDay(); if (intervalStart != null) { DateTime itemStart = intervalStart; DateTime itemEnd = intervalStart.plus(intervalIncrease()); while (intervalEnd.isAfter(itemStart)) { if (intervalEnd.isBefore(itemEnd) || !intervalEnd.isAfter(itemEnd .plus(intervalIncrease()))) { itemEnd = intervalEnd; } Listitem item = new Listitem(df.print(itemStart) + " - " + df.print(itemEnd.minusDays(1))); horizontalPagination.appendChild(item); itemStart = itemEnd; itemEnd = itemEnd.plus(intervalIncrease()); } } horizontalPagination.setSelectedIndex(0); // Disable pagination if there's only one page int size = horizontalPagination.getItems().size(); horizontalPagination.setDisabled(size == 1); } public void goToHorizontalPage(int interval) { paginatorStart = intervalStart; paginatorStart = timeTracker.getDetailsFirstLevel().iterator() .next().getStartDate(); for (int i = 0; i < interval; i++) { paginatorStart = paginatorStart.plus(intervalIncrease()); } paginatorEnd = paginatorStart.plus(intervalIncrease()); if ((paginatorEnd.plus(intervalIncrease()).isAfter(intervalEnd))) { paginatorEnd = paginatorEnd.plus(intervalIncrease()); } timeTracker.resetMapper(); updatePaginationButtons(); } private void updatePaginationButtons() { paginationDownButton.setDisabled(isFirstPage()); paginationUpButton.setDisabled(isLastPage()); } public boolean isFirstPage() { return (horizontalPagination.getSelectedIndex() <= 0) || horizontalPagination.isDisabled(); } private boolean isLastPage() { return (horizontalPagination.getItemCount() == (horizontalPagination .getSelectedIndex() + 1)) || horizontalPagination.isDisabled(); } } }
package it.near.sdk.geopolis.geofences; import android.Manifest; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.location.Location; import android.os.Bundle; import android.os.IBinder; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; import com.google.android.gms.location.FusedLocationProviderClient; import com.google.android.gms.location.Geofence; import com.google.android.gms.location.GeofencingClient; import com.google.android.gms.location.GeofencingRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.tasks.OnSuccessListener; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.util.ArrayList; import java.util.List; import it.near.sdk.geopolis.GeopolisManager; import it.near.sdk.logging.NearLog; public class GeoFenceService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, ResultCallback<Status> { private static final String TAG = "GeoFenceService"; private static final String PREF_SUFFIX = "NearGeo"; private static final String LIST_IDS = "list_ids"; public static final String GEOFENCES = "geofences"; private PendingIntent mGeofencePendingIntent; private GoogleApiClient mGoogleApiClient; private List<Geofence> mPendingGeofences = new ArrayList<>(); private FusedLocationProviderClient fusedLocationProviderClient; private GeofencingClient geofencingClient; @Override public void onCreate() { super.onCreate(); NearLog.d(TAG, "onCreate()"); fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this); geofencingClient = LocationServices.getGeofencingClient(this); } @Override public int onStartCommand(Intent intent, int flags, int startId) { // can be called multiple times NearLog.d(TAG, "onStartCommand()"); if (mGoogleApiClient == null || !mGoogleApiClient.isConnected()) { startGoogleApiClient(); } if (intent != null && intent.hasExtra(GEOFENCES)) { List<GeofenceNode> nodes = intent.getParcelableArrayListExtra(GEOFENCES); mPendingGeofences = GeofenceNode.toGeofences(nodes); if (GeopolisManager.isRadarStarted(this)) { setGeoFences(nodes); pingSingleLocation(); } } return Service.START_STICKY; } private void pingSingleLocation() { if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } fusedLocationProviderClient.getLastLocation() .addOnSuccessListener(new OnSuccessListener<Location>() { @Override public void onSuccess(Location location) { if (location != null) { NearLog.d(TAG, "onLocationChanged"); NearLog.d(TAG, "location: " + location.getLongitude() + " " + location.getLatitude()); } } }); } @Override public void onDestroy() { NearLog.d(TAG, "onDestroy on geofence service"); super.onDestroy(); stopAllGeofences(); resetIds(this); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } /** * Create and start the google api client for the geofences. * Set this service as the listener for the connection callback methods. */ private void startGoogleApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(this) .addApi(LocationServices.API) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .build(); mGoogleApiClient.connect(); } /** * Load geofence request ids from disk. */ private List<String> loadIds() { Gson gson = new Gson(); SharedPreferences sp = getSharedPreferences(getSharedPrefName(this), 0); String jsonText = sp.getString(LIST_IDS, null); // TODO not catching the unchecked exception is dangerous return gson.fromJson(jsonText, new TypeToken<List<String>>() { }.getType()); } /** * Overwrite geofence request ids. */ private void saveIds(List<String> ids) { Gson gson = new Gson(); SharedPreferences.Editor edit = getSharedPreferences(getSharedPrefName(this), 0).edit(); edit.putString(LIST_IDS, gson.toJson(ids)).apply(); } /** * Reset the listened geofence request ids. */ public static void resetIds(Context context) { SharedPreferences.Editor edit = context.getSharedPreferences(getSharedPrefName(context), 0).edit(); edit.putString(LIST_IDS, null).apply(); } /** * Set the geofence to monitor. Filters the geofence to only add the new ones and to * remove the geofences it has no longer to monitor. Persists the new ids. * * @param geofenceNodes */ private void setGeoFences(List<GeofenceNode> geofenceNodes) { // get the ids of the geofence to monitor List<String> newIds = idsFromGeofences(geofenceNodes); // subtracting the new ids to the old ones, find the geofence to stop monitoring List<String> idsToremove = loadIds(); if (idsToremove != null) { idsToremove.removeAll(newIds); stopGeofencing(idsToremove); } // from the old and the new sets of ids, find the geofence to add List<Geofence> geofencesToAdd = fetchNewGeofence(geofenceNodes, newIds, loadIds()); startGeoFencing(getGeofencingRequest(geofencesToAdd)); saveIds(newIds); } private List<Geofence> fetchNewGeofence(List<GeofenceNode> geofenceNodes, List<String> newIds, List<String> oldIds) { // create copy of the new ids List<String> idsToAdd = new ArrayList<>(newIds); // subtract the old ids to the new if (oldIds != null) { idsToAdd.removeAll(oldIds); } // for each id, fetch the geofence and return them all List<Geofence> geoFenceNodesToAdd = new ArrayList<>(); for (String id : idsToAdd) { GeofenceNode geofenceNode = getGeofenceFromId(geofenceNodes, id); if (geofenceNode != null) { geoFenceNodesToAdd.add(geofenceNode.toGeofence()); } } return geoFenceNodesToAdd; } /** * Stop all geofences */ public void stopAllGeofences() { stopGeofencing(loadIds()); saveIds(new ArrayList<String>()); } /** * Find a geofence from a geofence list, given its id * * @param geofenceNodes * @param id * @return */ private GeofenceNode getGeofenceFromId(List<GeofenceNode> geofenceNodes, String id) { for (GeofenceNode geofenceNode : geofenceNodes) { if (geofenceNode.getId().equals(id)) { return geofenceNode; } } return null; } private List<String> idsFromGeofences(List<GeofenceNode> geofenceNodes) { List<String> ids = new ArrayList<>(); for (GeofenceNode geofenceNode : geofenceNodes) { ids.add(geofenceNode.getId()); } return ids; } /** * Stop geofencing on request ids. * * @param idsToremove */ public void stopGeofencing(List<String> idsToremove) { if (idsToremove == null || idsToremove.size() == 0) return; if (mGoogleApiClient == null || !mGoogleApiClient.isConnected()) return; geofencingClient.removeGeofences(idsToremove) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { NearLog.d(TAG, "Geofences removed"); } }); } /** * Start geofencing from a geofence request. If the google api client is not yet connected, * store the geofecing as pending to be started once the client is connected. * * @param request */ private void startGeoFencing(GeofencingRequest request) { if (request == null) return; if (!mGoogleApiClient.isConnected()) { mPendingGeofences = request.getGeofences(); return; } mPendingGeofences.clear(); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling // ActivityCompat // int[] grantResults) // for ActivityCompat return; } NearLog.d(TAG, "startGeofencing"); geofencingClient.addGeofences( request, getGeofencePendingIntent() ).addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { NearLog.d(TAG, "Geofences added"); pingSingleLocation(); } }); } /** * Builds the geofence request from a list of geofences * * @return */ private GeofencingRequest getGeofencingRequest(List<Geofence> geofences) { if (geofences == null || geofences.size() == 0) { return null; } GeofencingRequest.Builder builder = new GeofencingRequest.Builder(); builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER); builder.addGeofences(geofences); return builder.build(); } /** * Build the geofence pending intent. * * @return */ private PendingIntent getGeofencePendingIntent() { // Reuse the PendingIntent if we already have it. if (mGeofencePendingIntent != null) { return mGeofencePendingIntent; } Intent intent = new Intent(this, NearGeofenceTransitionsIntentService.class); // We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when // calling addGeofences() and removeGeofences(). mGeofencePendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent. FLAG_UPDATE_CURRENT); return mGeofencePendingIntent; } @Override public void onConnected(@Nullable Bundle bundle) { NearLog.d(TAG, "onConnected"); // If we have pending geofences (that need to be started) // we start the geofence now that the client is connected. if (mPendingGeofences != null) { startGeoFencing(getGeofencingRequest(mPendingGeofences)); } } @Override public void onConnectionSuspended(int i) { NearLog.d(TAG, "onConnectionSuspended"); } @Override public void onConnectionFailed(@NonNull ConnectionResult connectionResult) { NearLog.d(TAG, "onConnectionFailed"); } @Override public void onResult(@NonNull Status status) { NearLog.d(TAG, "onResult: " + status.getStatusMessage()); } public static String getSharedPrefName(Context context) { String PACK_NAME = context.getApplicationContext().getPackageName(); return PACK_NAME + PREF_SUFFIX; } }
package de.geeksfactory.opacclient.frontend; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Rect; import android.os.AsyncTask; import android.os.Build; import android.os.Bundle; import android.preference.PreferenceManager; import android.support.v4.app.Fragment; import android.support.v4.view.MenuItemCompat; import android.support.v4.view.ViewCompat; import android.support.v7.graphics.Palette; import android.support.v7.widget.ActionMenuView; import android.support.v7.widget.Toolbar; import android.text.util.Linkify; import android.util.Log; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.animation.AnimationUtils; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.nineoldandroids.view.ViewHelper; import org.acra.ACRA; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URL; import java.util.Arrays; import java.util.List; import java.util.Map; import de.geeksfactory.opacclient.OpacClient; import de.geeksfactory.opacclient.R; import de.geeksfactory.opacclient.apis.EbookServiceApi; import de.geeksfactory.opacclient.apis.EbookServiceApi.BookingResult; import de.geeksfactory.opacclient.apis.OpacApi; import de.geeksfactory.opacclient.apis.OpacApi.MultiStepResult; import de.geeksfactory.opacclient.apis.OpacApi.ReservationResult; import de.geeksfactory.opacclient.frontend.MultiStepResultHelper.Callback; import de.geeksfactory.opacclient.frontend.MultiStepResultHelper.StepTask; import de.geeksfactory.opacclient.objects.Account; import de.geeksfactory.opacclient.objects.Detail; import de.geeksfactory.opacclient.objects.DetailledItem; import de.geeksfactory.opacclient.storage.AccountDataSource; import de.geeksfactory.opacclient.storage.StarDataSource; import de.geeksfactory.opacclient.ui.ObservableScrollView; import de.geeksfactory.opacclient.ui.WhitenessUtils; import de.geeksfactory.opacclient.utils.ISBNTools; /** * A fragment representing a single SearchResult detail screen. This fragment is either contained in * a {@link SearchResultListActivity} in two-pane mode (on tablets) or a {@link * SearchResultDetailActivity} on handsets. */ public class SearchResultDetailFragment extends Fragment implements Toolbar.OnMenuItemClickListener, ObservableScrollView.Callbacks { /** * The fragment argument representing the item ID that this fragment represents. */ public static final String ARG_ITEM_ID = "item_id"; public static final String ARG_ITEM_NR = "item_nr"; public static final String ARG_ITEM_COVER_BITMAP = "item_cover_bitmap"; /** * A dummy implementation of the {@link Callbacks} interface that does nothing. Used only when * this fragment is not attached to an activity. */ private static Callbacks dummyCallbacks = new Callbacks() { @Override public void removeFragment() { } }; /** * The fragment's current callback object, which is notified of list item clicks. */ private Callbacks callbacks = dummyCallbacks; protected boolean back_button_visible = false; protected boolean image_analyzed = false; protected Toolbar toolbar; protected ImageView ivCover; protected ObservableScrollView scrollView; protected View gradientBottom, gradientTop, tint; protected TextView tvTitel, tvCopies; protected LinearLayout llDetails, llCopies; protected ProgressBar progressBar; protected RelativeLayout detailsLayout; protected FrameLayout errorView; /** * The detailled item that this fragment represents. */ private DetailledItem item; private String id; private Integer nr; private OpacClient app; private View view; private FetchTask ft; private ProgressDialog dialog; private AlertDialog adialog; private boolean account_switched = false; private boolean invalidated = false; private boolean progress = false; private Boolean[] cardAnimations; /** * Mandatory empty constructor for the fragment manager to instantiate the fragment (e.g. upon * screen orientation changes). */ public SearchResultDetailFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); } public void setProgress(boolean show, boolean animate) { progress = show; if (view != null) { View content = detailsLayout; if (scrollView != null) { scrollView.setVisibility(View.VISIBLE); } if (show) { if (animate) { progressBar.startAnimation(AnimationUtils.loadAnimation( getActivity(), android.R.anim.fade_in)); content.startAnimation(AnimationUtils.loadAnimation( getActivity(), android.R.anim.fade_out)); } else { progressBar.clearAnimation(); content.clearAnimation(); } progressBar.setVisibility(View.VISIBLE); content.setVisibility(View.GONE); } else { if (animate) { progressBar.startAnimation(AnimationUtils.loadAnimation( getActivity(), android.R.anim.fade_out)); content.startAnimation(AnimationUtils.loadAnimation( getActivity(), android.R.anim.fade_in)); } else { progressBar.clearAnimation(); content.clearAnimation(); } progressBar.setVisibility(View.GONE); content.setVisibility(View.VISIBLE); } } } public void showConnectivityError() { errorView.removeAllViews(); View connError = getActivity().getLayoutInflater().inflate( R.layout.error_connectivity, errorView); connError.findViewById(R.id.btRetry) .setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { errorView.removeAllViews(); reload(); } }); progressBar.startAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_out)); scrollView.startAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_out)); connError.startAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_in)); progressBar.setVisibility(View.GONE); scrollView.setVisibility(View.GONE); connError.setVisibility(View.VISIBLE); } public void setProgress() { setProgress(progress, false); } private void load(int nr, String id) { setProgress(true, true); this.id = id; this.nr = nr; ft = new FetchTask(nr, id); ft.execute(); } private void reload() { load(nr, id); } @Override public void onAttach(Activity activity) { super.onAttach(activity); app = (OpacClient) activity.getApplication(); // Activities containing this fragment must implement its callbacks. if (!(activity instanceof Callbacks)) { throw new IllegalStateException( "Activity must implement fragment's callbacks."); } callbacks = (Callbacks) activity; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); if (item != null) { display(); } else if (getArguments().containsKey(ARG_ITEM_ID) || getArguments().containsKey(ARG_ITEM_NR)) { load(getArguments().getInt(ARG_ITEM_NR), getArguments().getString(ARG_ITEM_ID)); } } @Override public void onDetach() { super.onDetach(); // Reset the active callbacks interface to the dummy implementation. callbacks = dummyCallbacks; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_searchresult_detail, container, false); view = rootView; findViews(); toolbar.setVisibility(View.VISIBLE); setHasOptionsMenu(false); if (getActivity() instanceof SearchResultDetailActivity) { // This applies on phones, where the Toolbar is also the // main ActionBar of the Activity and needs a back button toolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getActivity().supportFinishAfterTransition(); } }); back_button_visible = true; } toolbar.inflateMenu(R.menu.search_result_details_activity); refreshMenu(toolbar.getMenu()); toolbar.setOnMenuItemClickListener(this); setRetainInstance(true); setProgress(); scrollView.addCallbacks(this); if (getArguments().containsKey(ARG_ITEM_COVER_BITMAP)) { Bitmap bitmap = getArguments().getParcelable(ARG_ITEM_COVER_BITMAP); ivCover.setImageBitmap(bitmap); analyzeCover(bitmap); showCoverView(true); } else { showCoverView(false); } fixEllipsize(tvTitel); return rootView; } private void analyzeCover(Bitmap bitmap) { Palette.generateAsync(bitmap, new Palette.PaletteAsyncListener() { @Override public void onGenerated(Palette palette) { Palette.Swatch swatch = palette.getDarkVibrantSwatch(); if (swatch != null) { ivCover.setBackgroundColor(swatch.getRgb()); tint.setBackgroundColor(swatch.getRgb()); } } }); analyzeWhitenessOfCoverAsync(bitmap); image_analyzed = true; } private void findViews() { toolbar = (Toolbar) view.findViewById(R.id.toolbar); scrollView = (ObservableScrollView) view.findViewById(R.id.rootView); ivCover = (ImageView) view.findViewById(R.id.ivCover); gradientBottom = view.findViewById(R.id.gradient_bottom); gradientTop = view.findViewById(R.id.gradient_top); tint = view.findViewById(R.id.tint); tvTitel = (TextView) view.findViewById(R.id.tvTitle); llDetails = (LinearLayout) view.findViewById(R.id.llDetails); llCopies = (LinearLayout) view.findViewById(R.id.llCopies); progressBar = (ProgressBar) view.findViewById(R.id.progress); detailsLayout = (RelativeLayout) view.findViewById(R.id.detailsLayout); errorView = (FrameLayout) view.findViewById(R.id.error_view); tvCopies = (TextView) view.findViewById(R.id.tvCopies); } /** * Workaround because the built-in ellipsize function does not work for multiline TextViews This * function is only prepared for one or two lines * * @param tv The TextView to fix */ private void fixEllipsize(final TextView tv) { tv.getViewTreeObserver() .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { if (tv.getLineCount() > 2) { try { int lineEndIndex = tv.getLayout().getLineEnd(1); String text = tv.getText().subSequence(0, lineEndIndex - 3) + "..."; tv.setText(text); } catch (StringIndexOutOfBoundsException e) { // Happens in strange cases where the second line is less than three // characters long e.printStackTrace(); } } } }); } /** * Examine how many white pixels are in the bitmap in order to determine whether or not we need * gradient overlays on top of the image. */ @SuppressLint("NewApi") private void analyzeWhitenessOfCoverAsync(final Bitmap bitmap) { AnalyzeWhitenessTask task = new AnalyzeWhitenessTask(); // Execute in parallel with FetchTask if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, bitmap); } else { task.execute(bitmap); } } protected void display() { try { Log.i("result", getItem().toString()); } catch (Exception e) { ACRA.getErrorReporter().handleException(e); } tvTitel.setText(getItem().getTitle()); llDetails.removeAllViews(); for (Detail detail : item.getDetails()) { View v = getLayoutInflater(null) .inflate(R.layout.listitem_detail, null); ((TextView) v.findViewById(R.id.tvDesc)).setText(detail.getDesc()); ((TextView) v.findViewById(R.id.tvContent)).setText(detail .getContent()); Linkify.addLinks((TextView) v.findViewById(R.id.tvContent), Linkify.WEB_URLS); llDetails.addView(v); } llCopies.removeAllViews(); if (item.getVolumesearch() != null) { tvCopies.setText(R.string.volumes); Button btnVolume = new Button(getActivity()); btnVolume.setText(R.string.volumesearch); btnVolume.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { app.startVolumeSearch(getActivity(), getItem().getVolumesearch()); } }); llCopies.addView(btnVolume); } else if (item.getVolumes().size() > 0) { tvCopies.setText(R.string.volumes); for (final Map<String, String> band : item.getVolumes()) { View v = getLayoutInflater(null).inflate(R.layout.listitem_volume, null); ((TextView) v.findViewById(R.id.tvTitel)).setText(band .get(DetailledItem.KEY_CHILD_TITLE)); v.findViewById(R.id.llItem).setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(getActivity(), SearchResultDetailActivity.class); intent.putExtra(ARG_ITEM_ID, band.get(DetailledItem.KEY_CHILD_ID)); intent.putExtra("from_collection", true); startActivity(intent); } }); llCopies.addView(v); } } else { if (item.getCopies().size() == 0) { tvCopies.setVisibility(View.GONE); } else { for (Map<String, String> copy : item.getCopies()) { View v = getLayoutInflater(null).inflate( R.layout.listitem_copy, llCopies, false); if (v.findViewById(R.id.tvBranch) != null) { if (containsAndNotEmpty(copy, DetailledItem.KEY_COPY_BRANCH)) { ((TextView) v.findViewById(R.id.tvBranch)) .setText(copy .get(DetailledItem.KEY_COPY_BRANCH)); v.findViewById(R.id.tvBranch).setVisibility(View.VISIBLE); } else { v.findViewById(R.id.tvBranch).setVisibility(View.GONE); } } if (v.findViewById(R.id.tvDepartment) != null) { if (containsAndNotEmpty(copy, DetailledItem.KEY_COPY_DEPARTMENT)) { ((TextView) v.findViewById(R.id.tvDepartment)) .setText(copy .get(DetailledItem.KEY_COPY_DEPARTMENT)); v.findViewById(R.id.tvDepartment).setVisibility(View.VISIBLE); } else { v.findViewById(R.id.tvDepartment).setVisibility(View.GONE); } } if (v.findViewById(R.id.tvLocation) != null) { if (containsAndNotEmpty(copy, DetailledItem.KEY_COPY_LOCATION)) { ((TextView) v.findViewById(R.id.tvLocation)) .setText(copy .get(DetailledItem.KEY_COPY_LOCATION)); v.findViewById(R.id.tvLocation).setVisibility(View.VISIBLE); } else { v.findViewById(R.id.tvLocation).setVisibility(View.GONE); } } if (v.findViewById(R.id.tvShelfmark) != null) { if (containsAndNotEmpty(copy, DetailledItem.KEY_COPY_SHELFMARK)) { ((TextView) v.findViewById(R.id.tvShelfmark)) .setText(copy .get(DetailledItem.KEY_COPY_SHELFMARK)); v.findViewById(R.id.tvShelfmark).setVisibility(View.VISIBLE); } else { v.findViewById(R.id.tvShelfmark).setVisibility(View.GONE); } } if (v.findViewById(R.id.tvStatus) != null) { if (containsAndNotEmpty(copy, DetailledItem.KEY_COPY_STATUS)) { ((TextView) v.findViewById(R.id.tvStatus)) .setText(copy .get(DetailledItem.KEY_COPY_STATUS)); v.findViewById(R.id.tvStatus).setVisibility(View.VISIBLE); } else { v.findViewById(R.id.tvStatus).setVisibility(View.GONE); } } if (v.findViewById(R.id.tvReservations) != null) { if (containsAndNotEmpty(copy, DetailledItem.KEY_COPY_RESERVATIONS)) { ((TextView) v.findViewById(R.id.tvReservations)) .setText(copy.get(DetailledItem.KEY_COPY_RESERVATIONS)); v.findViewById(R.id.tvReservations).setVisibility(View.VISIBLE); } else { v.findViewById(R.id.tvReservations).setVisibility(View.GONE); } } if (v.findViewById(R.id.tvReturndate) != null) { if (containsAndNotEmpty(copy, DetailledItem.KEY_COPY_RETURN)) { ((TextView) v.findViewById(R.id.tvReturndate)) .setText(copy.get(DetailledItem.KEY_COPY_RETURN)); v.findViewById(R.id.tvReturndate).setVisibility(View.VISIBLE); } else { v.findViewById(R.id.tvReturndate).setVisibility(View.GONE); } } llCopies.addView(v); } } } if (id == null || id.equals("")) { id = getItem().getId(); } setProgress(false, true); refreshMenu(toolbar.getMenu()); toolbar.getViewTreeObserver() .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { toolbar.getViewTreeObserver().removeGlobalOnLayoutListener(this); fixTitle(); } }); toolbar.requestLayout(); } private void displayCover() { if (getItem().getCoverBitmap() != null) { ivCover.setVisibility(View.VISIBLE); ivCover.setImageBitmap(getItem().getCoverBitmap()); if (!image_analyzed) { analyzeCover(getItem().getCoverBitmap()); } showCoverView(true); } else if (getArguments().containsKey(ARG_ITEM_COVER_BITMAP)) { showCoverView(true); } else { showCoverView(false); toolbar.setTitle(getItem().getTitle()); } } private boolean containsAndNotEmpty(Map<String, String> map, String key) { return map.containsKey(key) && !map.get(key).equals(""); } private void showCoverView(boolean b) { ivCover.setVisibility(b ? View.VISIBLE : View.GONE); tvTitel.setVisibility(b ? View.VISIBLE : View.GONE); gradientBottom.setVisibility(b ? View.VISIBLE : View.GONE); gradientTop.setVisibility(b ? View.VISIBLE : View.GONE); RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT); if (b) { toolbar.setBackgroundResource(R.color.transparent); ViewCompat.setElevation(toolbar, 0); llDetails.setPadding( llDetails.getPaddingLeft(), 0, llDetails.getPaddingRight(), llDetails.getPaddingBottom() ); params.addRule(RelativeLayout.BELOW, R.id.ivCover); } else { toolbar.setBackgroundResource(getToolbarBackgroundColor()); ViewCompat.setElevation(toolbar, TypedValue.applyDimension(TypedValue .COMPLEX_UNIT_DIP, 4f, getResources().getDisplayMetrics())); params.addRule(RelativeLayout.BELOW, R.id.toolbar); } detailsLayout.setLayoutParams(params); } private int getToolbarBackgroundColor() { if (getActivity() != null) { if (getActivity() instanceof SearchResultListActivity) { return R.color.primary_red_dark; } else { return R.color.primary_red; } } else { return R.color.primary_red; } } private void fixTitle() { if (getItem().getCoverBitmap() != null || getArguments().containsKey(ARG_ITEM_COVER_BITMAP)) { // tvTitel is used for displaying title fixTitleWidth(); tvTitel.getViewTreeObserver() .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { // We need to wait for tvTitel to refresh to get correct calculations tvTitel.getViewTreeObserver().removeGlobalOnLayoutListener( this); if (tvTitel.getLayout() != null && tvTitel.getLayout().getLineCount() > 1) { toolbar.getLayoutParams().height = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_SP, 84f, getResources().getDisplayMetrics()); toolbar.getParent().requestLayout(); } } }); } else { // Toolbar is used for displaying title toolbar.getViewTreeObserver() .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { // We need to wait for toolbar to refresh to get correct calculations toolbar.getViewTreeObserver().removeGlobalOnLayoutListener( this); if (toolbar.isTitleTruncated()) { toolbar.getLayoutParams().height = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_SP, 84f, getResources().getDisplayMetrics()); TextView titleTextView = findTitleTextView(toolbar); titleTextView.setSingleLine( false); fixEllipsize(titleTextView); toolbar.getParent().requestLayout(); } } }); } onScrollChanged(0, 0); } private void fixTitleWidth() { ActionMenuView view = findActionMenuView(toolbar); if (view != null) { float density = getResources().getDisplayMetrics().density; Menu menu = view.getMenu(); float availableWidth = calculateAvailableWidthInToolbar(); if (availableWidth / density < 150 && (menu.findItem(R.id.action_lendebook).isVisible() || menu.findItem(R.id.action_reservation).isVisible()) && tvTitel.getWidth() > availableWidth * 36f / 20f) { // We have so little space for the title that we should move the // "Lend eBook" and "Reserve" menu items to the overflow menu MenuItemCompat.setShowAsAction(menu.findItem(R.id.action_lendebook), MenuItemCompat.SHOW_AS_ACTION_NEVER); MenuItemCompat.setShowAsAction(menu.findItem(R.id.action_reservation), MenuItemCompat.SHOW_AS_ACTION_NEVER); toolbar.requestLayout(); toolbar.getViewTreeObserver() .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @Override public void onGlobalLayout() { toolbar.getViewTreeObserver().removeGlobalOnLayoutListener(this); float availableWidth = calculateAvailableWidthInToolbar(); changeTitleWidth(availableWidth); } }); } else { changeTitleWidth(availableWidth); } } } /** * Calculates the width available for a title in the toolbar in pixels. Follows the following * formula: Toolbar width - menu width - margin - back button width * * @return Available width in pixels */ private float calculateAvailableWidthInToolbar() { float density = getResources().getDisplayMetrics().density; ActionMenuView view = findActionMenuView(toolbar); return toolbar.getWidth() - view.getWidth() - 16 * density - (back_button_visible ? 56 * density : 0); } private void changeTitleWidth(float availableWidth) { if (tvTitel.getWidth() > availableWidth * 36f / 20f) { tvTitel.getLayoutParams().width = (int) (availableWidth * 36f / 20f); tvTitel.getParent().requestLayout(); } } /** * Hacky way to find the {@link android.support.v7.widget.ActionMenuView} inside a {@link * android.support.v7.widget.Toolbar}. Will return null if none is found * * @param toolbar a Toolbar * @return the ActionMenuView inside this toolbar, or null if none is found */ private ActionMenuView findActionMenuView(Toolbar toolbar) { for (int i = 0; i < toolbar.getChildCount(); i++) { View view = toolbar.getChildAt(i); if (view instanceof ActionMenuView) { return (ActionMenuView) view; } } return null; } /** * Hacky way to find the first {@link android.widget.TextView} inside a {@link android * .support.v7.widget.Toolbar}, wnich is typically the title. Will return null if none is found * * @param toolbar a Toolbar * @return the first TextView inside this toolbar, or null if none is found */ private TextView findTitleTextView(Toolbar toolbar) { for (int i = 0; i < toolbar.getChildCount(); i++) { View view = toolbar.getChildAt(i); if (view instanceof TextView) { return (TextView) view; } } return null; } @Override public void onScrollChanged(int deltaX, int deltaY) { if (getItem() == null) { return; } int scrollY = scrollView.getScrollY(); boolean hasCover = getItem().getCoverBitmap() != null || getArguments().containsKey(ARG_ITEM_COVER_BITMAP); if (hasCover) { // Parallax effect ViewHelper.setTranslationY(ivCover, scrollY * 0.5f); ViewHelper.setTranslationY(gradientBottom, scrollY * 0.5f); ViewHelper.setTranslationY(gradientTop, scrollY * 0.5f); } // Toolbar stays at the top ViewHelper.setTranslationY(toolbar, scrollY); if (hasCover) { float minHeight = toolbar.getHeight(); float progress = Math.min(((float) scrollY) / (ivCover.getHeight() - minHeight), 1); float scale = 1 - progress + 20f / 36f * progress; ViewHelper.setPivotX(tvTitel, 0); ViewHelper.setPivotY(tvTitel, tvTitel.getHeight()); ViewHelper.setScaleX(tvTitel, scale); ViewHelper.setScaleY(tvTitel, scale); if (back_button_visible) { ViewHelper.setTranslationX(tvTitel, progress * TypedValue .applyDimension(TypedValue.COMPLEX_UNIT_DIP, 56f, getResources() .getDisplayMetrics())); } ViewHelper.setAlpha(tint, progress); if (progress == 1) { ViewHelper.setTranslationY(tvTitel, scrollY - ivCover.getHeight() + minHeight); if (!ivCover.getBackground().equals(toolbar.getBackground())) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) { toolbar.setBackground(ivCover.getBackground()); } else { //noinspection deprecation toolbar.setBackgroundDrawable(ivCover.getBackground()); } ViewCompat.setElevation(toolbar, TypedValue.applyDimension(TypedValue .COMPLEX_UNIT_DIP, 4f, getResources().getDisplayMetrics())); ViewCompat.setElevation(tvTitel, TypedValue.applyDimension(TypedValue .COMPLEX_UNIT_DIP, 4f, getResources().getDisplayMetrics())); } } else { ViewHelper.setTranslationY(tvTitel, 0); if (ivCover.getBackground().equals(toolbar.getBackground())) { toolbar.setBackgroundResource(R.color.transparent); ViewCompat.setElevation(toolbar, 0); ViewCompat.setElevation(tvTitel, 0); } } } // Card animations if (cardAnimations == null) { cardAnimations = new Boolean[llCopies.getChildCount()]; Arrays.fill(cardAnimations, false); } for (int i = 0; i < llCopies.getChildCount(); i++) { if (!cardAnimations[i]) { View card = llCopies.getChildAt(i); Rect scrollBounds = new Rect(); scrollView.getHitRect(scrollBounds); if (card.getLocalVisibleRect(scrollBounds)) { // card is visible cardAnimations[i] = true; card.startAnimation(AnimationUtils.loadAnimation(getActivity(), R.anim.card_appear)); } } } } @Override public void onViewStateRestored(Bundle savedInstanceState) { super.onViewStateRestored(savedInstanceState); if (item != null) { display(); } } protected void dialog_wrong_credentials(String s, final boolean finish) { if (getActivity() == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setMessage(getString(R.string.opac_error) + " " + s) .setCancelable(false) .setNegativeButton(R.string.close, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { dialog.cancel(); if (finish) { callbacks.removeFragment(); } } }) .setPositiveButton(R.string.prefs, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { Intent intent = new Intent(getActivity(), AccountEditActivity.class); intent.putExtra( AccountEditActivity.EXTRA_ACCOUNT_ID, app.getAccount().getId()); startActivity(intent); } }); AlertDialog alert = builder.create(); alert.show(); } @Override public void onStop() { super.onStop(); if (dialog != null) { if (dialog.isShowing()) { dialog.cancel(); } } try { if (ft != null) { if (!ft.isCancelled()) { ft.cancel(true); } } } catch (Exception e) { e.printStackTrace(); } } @Override public void onDestroy() { super.onDestroy(); OpacActivity.unbindDrawables(view.findViewById(R.id.rootView)); System.gc(); } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.search_result_details_activity, menu); refreshMenu(menu); super.onCreateOptionsMenu(menu, inflater); } protected void refreshMenu(Menu menu) { if (item != null) { if (item.isReservable()) { menu.findItem(R.id.action_reservation).setVisible(true); } else { menu.findItem(R.id.action_reservation).setVisible(false); } if (item.isBookable() && app.getApi() instanceof EbookServiceApi) { if (((EbookServiceApi) app.getApi()).isEbook(item)) { menu.findItem(R.id.action_lendebook).setVisible(true); } else { menu.findItem(R.id.action_lendebook).setVisible(false); } } else { menu.findItem(R.id.action_lendebook).setVisible(false); } menu.findItem(R.id.action_tocollection).setVisible( item.getCollectionId() != null); } else { menu.findItem(R.id.action_reservation).setVisible(false); menu.findItem(R.id.action_lendebook).setVisible(false); menu.findItem(R.id.action_tocollection).setVisible(false); } String bib = app.getLibrary().getIdent(); StarDataSource data = new StarDataSource(getActivity()); if ((id == null || id.equals("")) && item != null) { if (data.isStarredTitle(bib, item.getTitle())) { menu.findItem(R.id.action_star).setIcon( R.drawable.ic_action_star_1); } } else { if (data.isStarred(bib, id)) { menu.findItem(R.id.action_star).setIcon( R.drawable.ic_action_star_1); } } } @Override public boolean onMenuItemClick(MenuItem item) { return onOptionsItemSelected(item); } @Override public boolean onOptionsItemSelected(MenuItem item) { final String bib = app.getLibrary().getIdent(); if (item.getItemId() == R.id.action_reservation) { reservationStart(); return true; } else if (item.getItemId() == R.id.action_lendebook) { bookingStart(); return true; } else if (item.getItemId() == R.id.action_tocollection) { if (getActivity().getIntent().getBooleanExtra("from_collection", false)) { getActivity().finish(); } else { Intent intent = new Intent(getActivity(), SearchResultDetailActivity.class); intent.putExtra(SearchResultDetailFragment.ARG_ITEM_ID, getItem().getCollectionId()); startActivity(intent); getActivity().finish(); } return true; } else if (item.getItemId() == R.id.action_share) { if (getItem() == null) { Toast toast = Toast.makeText(getActivity(), getString(R.string.share_wait), Toast.LENGTH_SHORT); toast.show(); } else { final String title = getItem().getTitle(); final String id = getItem().getId(); final CharSequence[] items = {getString(R.string.share_link), getString(R.string.share_details)}; AlertDialog.Builder builder = new AlertDialog.Builder( getActivity()); builder.setTitle(R.string.share_dialog_select); builder.setItems(items, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int di) { if (di == 0) { // Share link Intent intent = new Intent( android.content.Intent.ACTION_SEND); intent.setType("text/plain"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT); } else { //noinspection deprecation intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); } // Add data to the intent, the receiving app will // decide // what to do with it. intent.putExtra(Intent.EXTRA_SUBJECT, title); String t = title; try { t = java.net.URLEncoder.encode(t, "UTF-8"); } catch (UnsupportedEncodingException e) { } String shareUrl = app.getApi().getShareUrl(id, t); if (shareUrl != null) { intent.putExtra(Intent.EXTRA_TEXT, shareUrl); startActivity(Intent.createChooser(intent, getResources() .getString(R.string.share))); } else { Toast toast = Toast.makeText(getActivity(), getString(R.string.share_notsupported), Toast.LENGTH_SHORT); toast.show(); } } else { // Share details Intent intent = new Intent( android.content.Intent.ACTION_SEND); intent.setType("text/plain"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT); } else { //noinspection deprecation intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET); } // Add data to the intent, the receiving app will // decide // what to do with it. intent.putExtra(Intent.EXTRA_SUBJECT, title); String t = title; try { t = t != null ? java.net.URLEncoder.encode(t, "UTF-8") : ""; } catch (UnsupportedEncodingException e) { } String text = t + "\n\n"; for (Detail detail : getItem().getDetails()) { String colon = ""; if (!detail.getDesc().endsWith(":")) { colon = ":"; } text += detail.getDesc() + colon + "\n" + detail.getContent() + "\n\n"; } String shareUrl = app.getApi().getShareUrl(id, t); if (shareUrl != null) { text += shareUrl; } intent.putExtra(Intent.EXTRA_TEXT, text); startActivity(Intent.createChooser(intent, getResources().getString(R.string.share))); } } }); AlertDialog alert = builder.create(); alert.show(); } return true; } else if (item.getItemId() == R.id.action_star) { StarDataSource star = new StarDataSource(getActivity()); if (getItem() == null) { Toast toast = Toast.makeText(getActivity(), getString(R.string.star_wait), Toast.LENGTH_SHORT); toast.show(); } else if (getItem().getId() == null || getItem().getId().equals("")) { final String title = getItem().getTitle(); if (star.isStarredTitle(bib, title)) { star.remove(star.getItemByTitle(bib, title)); item.setIcon(R.drawable.ic_action_star_0); } else { star.star(null, title, bib); Toast toast = Toast.makeText(getActivity(), getString(R.string.starred), Toast.LENGTH_SHORT); toast.show(); item.setIcon(R.drawable.ic_action_star_1); } } else { final String title = getItem().getTitle(); final String id = getItem().getId(); if (star.isStarred(bib, id)) { star.remove(star.getItem(bib, id)); item.setIcon(R.drawable.ic_action_star_0); } else { star.star(id, title, bib); Toast toast = Toast.makeText(getActivity(), getString(R.string.starred), Toast.LENGTH_SHORT); toast.show(); item.setIcon(R.drawable.ic_action_star_1); } } return true; } else { return super.onOptionsItemSelected(item); } } public DetailledItem getItem() { return item; } protected void dialog_no_credentials() { if (getActivity() == null) { return; } AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setMessage(R.string.status_nouser) .setCancelable(false) .setNegativeButton(R.string.close, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }) .setPositiveButton(R.string.accounts_edit, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { Intent intent = new Intent(getActivity(), AccountEditActivity.class); intent.putExtra( AccountEditActivity.EXTRA_ACCOUNT_ID, app.getAccount().getId()); startActivity(intent); } }); AlertDialog alert = builder.create(); alert.show(); } protected void reservationStart() { if (invalidated) { new RestoreSessionTask(false).execute(); } if (app.getApi() instanceof EbookServiceApi) { SharedPreferences sp = PreferenceManager .getDefaultSharedPreferences(getActivity()); if (sp.getString("email", "").equals("") && ((EbookServiceApi) app.getApi()).isEbook(item)) { AlertDialog.Builder builder = new AlertDialog.Builder( getActivity()); builder.setMessage(getString(R.string.opac_error_email)) .setCancelable(false) .setNegativeButton(R.string.close, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }) .setPositiveButton(R.string.prefs, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); app.toPrefs(getActivity()); } }); AlertDialog alert = builder.create(); alert.show(); return; } } AccountDataSource data = new AccountDataSource(getActivity()); data.open(); final List<Account> accounts = data.getAccountsWithPassword(app .getLibrary().getIdent()); data.close(); if (accounts.size() == 0) { dialog_no_credentials(); } else if (accounts.size() > 1 && !getActivity().getIntent().getBooleanExtra("reservation", false) && (app.getApi().getSupportFlags() & OpacApi.SUPPORT_FLAG_CHANGE_ACCOUNT) != 0 && !(SearchResultDetailFragment.this.id == null || SearchResultDetailFragment.this.id.equals("null") || SearchResultDetailFragment.this.id .equals(""))) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); // Get the layout inflater LayoutInflater inflater = getLayoutInflater(null); View view = inflater.inflate(R.layout.dialog_simple_list, null, false); ListView lv = (ListView) view.findViewById(R.id.lvBibs); AccountListAdapter adapter = new AccountListAdapter(getActivity(), accounts); lv.setAdapter(adapter); lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if (accounts.get(position).getId() != app.getAccount() .getId() || account_switched) { if (SearchResultDetailFragment.this.id == null || SearchResultDetailFragment.this.id .equals("null") || SearchResultDetailFragment.this.id .equals("")) { Toast.makeText(getActivity(), R.string.accchange_sorry, Toast.LENGTH_LONG) .show(); } else { app.setAccount(accounts.get(position).getId()); Intent intent = new Intent(getActivity(), SearchResultDetailActivity.class); intent.putExtra( SearchResultDetailFragment.ARG_ITEM_ID, SearchResultDetailFragment.this.id); // TODO: refresh fragment instead intent.putExtra("reservation", true); startActivity(intent); } } else { reservationDo(); } adialog.dismiss(); } }); builder.setTitle(R.string.account_select) .setView(view) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { adialog.cancel(); } }); adialog = builder.create(); adialog.show(); } else { reservationDo(); } } public void reservationDo() { MultiStepResultHelper<DetailledItem> msrhReservation = new MultiStepResultHelper<>( getActivity(), item, R.string.doing_res); msrhReservation.setCallback(new Callback<DetailledItem>() { @Override public void onSuccess(MultiStepResult result) { AccountDataSource adata = new AccountDataSource(getActivity()); adata.open(); adata.invalidateCachedAccountData(app.getAccount()); adata.close(); if (result.getMessage() != null) { AlertDialog.Builder builder = new AlertDialog.Builder( getActivity()); builder.setMessage(result.getMessage()) .setCancelable(false) .setNegativeButton(R.string.close, new DialogInterface.OnClickListener() { @Override public void onClick( DialogInterface dialog, int id) { dialog.cancel(); } }) .setPositiveButton(R.string.account, new DialogInterface.OnClickListener() { @Override public void onClick( DialogInterface dialog, int id) { Intent intent = new Intent( getActivity(), app .getMainActivity()); intent.putExtra("fragment", "account"); getActivity().startActivity(intent); getActivity().finish(); } }); AlertDialog alert = builder.create(); alert.show(); } else { Intent intent = new Intent(getActivity(), app .getMainActivity()); intent.putExtra("fragment", "account"); getActivity().startActivity(intent); getActivity().finish(); } } @Override public void onError(MultiStepResult result) { dialog_wrong_credentials(result.getMessage(), false); } @Override public void onUnhandledResult(MultiStepResult result) { } @Override public void onUserCancel() { } @Override public StepTask<?> newTask(MultiStepResultHelper helper, int useraction, String selection, DetailledItem item) { return new ResTask(helper, useraction, selection, item); } }); msrhReservation.start(); } protected void bookingStart() { AccountDataSource data = new AccountDataSource(getActivity()); data.open(); final List<Account> accounts = data.getAccountsWithPassword(app .getLibrary().getIdent()); data.close(); if (accounts.size() == 0) { dialog_no_credentials(); } else if (accounts.size() > 1) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); // Get the layout inflater LayoutInflater inflater = getLayoutInflater(null); View view = inflater.inflate(R.layout.dialog_simple_list, null, false); ListView lv = (ListView) view.findViewById(R.id.lvBibs); AccountListAdapter adapter = new AccountListAdapter(getActivity(), accounts); lv.setAdapter(adapter); lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { app.setAccount(accounts.get(position).getId()); bookingDo(); adialog.dismiss(); } }); builder.setTitle(R.string.account_select) .setView(view) .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { adialog.cancel(); } }); adialog = builder.create(); adialog.show(); } else { bookingDo(); } } public void bookingDo() { MultiStepResultHelper<DetailledItem> msrhBooking = new MultiStepResultHelper<>( getActivity(), item, R.string.doing_res); msrhBooking.setCallback(new Callback<DetailledItem>() { @Override public void onSuccess(MultiStepResult result) { if (getActivity() == null) { return; } AccountDataSource adata = new AccountDataSource(getActivity()); adata.open(); adata.invalidateCachedAccountData(app.getAccount()); adata.close(); Intent intent = new Intent(getActivity(), app.getMainActivity()); intent.putExtra("fragment", "account"); getActivity().startActivity(intent); getActivity().finish(); } @Override public void onError(MultiStepResult result) { if (getActivity() == null) { return; } dialog_wrong_credentials(result.getMessage(), false); } @Override public void onUnhandledResult(MultiStepResult result) { } @Override public void onUserCancel() { } @Override public StepTask<?> newTask(MultiStepResultHelper helper, int useraction, String selection, DetailledItem item) { return new BookingTask(helper, useraction, selection, item); } }); msrhBooking.start(); } /** * A callback interface that all activities containing this fragment must implement. This * mechanism allows activities to be notified of item selections. */ public interface Callbacks { /** * Callback for when the fragment should be deleted */ public void removeFragment(); } public class LoadCoverTask extends AsyncTask<Void, Void, Bitmap> { @Override protected Bitmap doInBackground(Void... params) { try { float density = getActivity().getResources().getDisplayMetrics().density; URL newurl = new URL(ISBNTools.getBestSizeCoverUrl(item.getCover(), view.getWidth(), (int) (260 * density))); return BitmapFactory.decodeStream(newurl.openConnection().getInputStream()); } catch (Exception e) { // We don't want an unavailable Cover to cause any error message e.printStackTrace(); return null; } } protected void onPostExecute(Bitmap cover) { if (cover != null && cover.getHeight() > 1 && cover.getWidth() > 1) { // When images embedded from Amazon aren't available, a 1x1 pixel image is returned item.setCoverBitmap(cover); } else { item.setCover(null); } displayCover(); } } public class FetchTask extends AsyncTask<Void, Void, DetailledItem> { protected boolean success = true; protected Integer nr; protected String id; public FetchTask(Integer nr, String id) { this.nr = nr; this.id = id; } @Override protected DetailledItem doInBackground(Void... voids) { try { DetailledItem res; if (id != null && !id.equals("")) { SharedPreferences sp = PreferenceManager .getDefaultSharedPreferences(getActivity()); String homebranch = sp.getString( OpacClient.PREF_HOME_BRANCH_PREFIX + app.getAccount().getId(), null); if (getActivity().getIntent().hasExtra("reservation") && getActivity().getIntent().getBooleanExtra( "reservation", false)) { app.getApi().start(); } res = app.getApi().getResultById(id, homebranch); if (res.getId() == null) res.setId(id); } else { res = app.getApi().getResult(nr); } success = true; return res; } catch (Exception e) { success = false; e.printStackTrace(); } return null; } @Override @SuppressLint("NewApi") protected void onPostExecute(DetailledItem result) { if (getActivity() == null) { return; } if (!success || result == null) { showConnectivityError(); return; } item = result; if (item.getCover() != null && item.getCoverBitmap() == null) { new LoadCoverTask().execute(); } else { displayCover(); } display(); if (getActivity().getIntent().hasExtra("reservation") && getActivity().getIntent().getBooleanExtra("reservation", false)) { reservationStart(); } } } private class AnalyzeWhitenessTask extends AsyncTask<Bitmap, Void, Boolean> { @Override protected Boolean doInBackground(Bitmap... params) { return WhitenessUtils.isBitmapWhiteAtTopOrBottom(params[0]); } @Override protected void onPostExecute(Boolean isWhite) { super.onPostExecute(isWhite); gradientBottom.setVisibility(isWhite ? View.VISIBLE : View.GONE); gradientTop.setVisibility(isWhite ? View.VISIBLE : View.GONE); } } public class ResTask extends StepTask<ReservationResult> { private DetailledItem item; public ResTask(MultiStepResultHelper helper, int useraction, String selection, DetailledItem item) { super(helper, useraction, selection); this.item = item; } @Override protected ReservationResult doInBackground(Void... voids) { try { return app.getApi().reservation(item, app.getAccount(), useraction, selection); } catch (IOException e) { publishProgress(e, "ioerror"); } catch (Exception e) { ACRA.getErrorReporter().handleException(e); } return null; } @Override protected void onPostExecute(ReservationResult res) { if (getActivity() == null) { return; } if (res == null) { AlertDialog.Builder builder = new AlertDialog.Builder( getActivity()); builder.setMessage(R.string.error) .setCancelable(true) .setNegativeButton(R.string.close, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); return; } super.onPostExecute(res); } } public class BookingTask extends StepTask<BookingResult> { private DetailledItem item; public BookingTask(MultiStepResultHelper helper, int useraction, String selection, DetailledItem item) { super(helper, useraction, selection); this.item = item; } @Override protected BookingResult doInBackground(Void... voids) { try { return ((EbookServiceApi) app.getApi()).booking( item, app.getAccount(), useraction, selection); } catch (IOException e) { publishProgress(e, "ioerror"); } catch (Exception e) { ACRA.getErrorReporter().handleException(e); } return null; } @Override protected void onPostExecute(BookingResult res) { if (getActivity() == null) { return; } if (res == null) { AlertDialog.Builder builder = new AlertDialog.Builder( getActivity()); builder.setMessage(R.string.error) .setCancelable(true) .setNegativeButton(R.string.close, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); return; } super.onPostExecute(res); } } public class RestoreSessionTask extends AsyncTask<Void, Void, Integer> { private boolean reservation; public RestoreSessionTask(boolean reservation) { this.reservation = reservation; } @Override protected Integer doInBackground(Void... voids) { try { if (id != null) { SharedPreferences sp = PreferenceManager .getDefaultSharedPreferences(getActivity()); String homebranch = sp.getString( OpacClient.PREF_HOME_BRANCH_PREFIX + app.getAccount().getId(), null); app.getApi().getResultById(id, homebranch); return 0; } else { ACRA.getErrorReporter().handleException( new Throwable("No ID supplied")); } } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { ACRA.getErrorReporter().handleException(e); } return 1; } @Override protected void onPostExecute(Integer result) { if (getActivity() == null) { return; } if (reservation) { reservationDo(); } } } }
package org.opendaylight.ovsdb.openstack.netvirt.impl; import java.net.InetAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.apache.commons.lang3.tuple.ImmutablePair; import org.apache.commons.lang3.tuple.Pair; import org.opendaylight.ovsdb.openstack.netvirt.AbstractEvent; import org.opendaylight.ovsdb.openstack.netvirt.AbstractHandler; import org.opendaylight.ovsdb.openstack.netvirt.ConfigInterface; import org.opendaylight.ovsdb.openstack.netvirt.NeutronL3AdapterEvent; import org.opendaylight.ovsdb.openstack.netvirt.api.Action; import org.opendaylight.ovsdb.openstack.netvirt.api.ArpProvider; import org.opendaylight.ovsdb.openstack.netvirt.api.ConfigurationService; import org.opendaylight.ovsdb.openstack.netvirt.api.Constants; import org.opendaylight.ovsdb.openstack.netvirt.api.EventDispatcher; import org.opendaylight.ovsdb.openstack.netvirt.api.GatewayMacResolver; import org.opendaylight.ovsdb.openstack.netvirt.api.GatewayMacResolverListener; import org.opendaylight.ovsdb.openstack.netvirt.api.InboundNatProvider; import org.opendaylight.ovsdb.openstack.netvirt.api.L3ForwardingProvider; import org.opendaylight.ovsdb.openstack.netvirt.api.NodeCacheManager; import org.opendaylight.ovsdb.openstack.netvirt.api.OutboundNatProvider; import org.opendaylight.ovsdb.openstack.netvirt.api.RoutingProvider; import org.opendaylight.ovsdb.openstack.netvirt.api.SecurityServicesManager; import org.opendaylight.ovsdb.openstack.netvirt.api.Southbound; import org.opendaylight.ovsdb.openstack.netvirt.api.Status; import org.opendaylight.ovsdb.openstack.netvirt.api.StatusCode; import org.opendaylight.ovsdb.openstack.netvirt.api.TenantNetworkManager; import org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronFloatingIP; import org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronNetwork; import org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronPort; import org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronRouter; import org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronRouter_Interface; import org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronSecurityGroup; import org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronSubnet; import org.opendaylight.ovsdb.openstack.netvirt.translator.Neutron_IPs; import org.opendaylight.ovsdb.openstack.netvirt.translator.crud.INeutronFloatingIPCRUD; import org.opendaylight.ovsdb.openstack.netvirt.translator.crud.INeutronNetworkCRUD; import org.opendaylight.ovsdb.openstack.netvirt.translator.crud.INeutronPortCRUD; import org.opendaylight.ovsdb.openstack.netvirt.translator.crud.INeutronSubnetCRUD; import org.opendaylight.ovsdb.openstack.netvirt.translator.iaware.impl.NeutronIAwareUtil; import org.opendaylight.ovsdb.utils.neutron.utils.NeutronModelsDataStoreHelper; import org.opendaylight.ovsdb.utils.servicehelper.ServiceHelper; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IpAddress; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev100924.MacAddress; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.Uuid; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.Routers; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.l3.rev150712.routers.attributes.routers.Router; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.Ports; import org.opendaylight.yang.gen.v1.urn.opendaylight.neutron.ports.rev150712.ports.attributes.ports.Port; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105.OvsdbTerminationPointAugmentation; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node; import org.osgi.framework.ServiceReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.common.base.Preconditions; import com.google.common.util.concurrent.FutureCallback; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; /** * Neutron L3 Adapter implements a hub-like adapter for the various Neutron events. Based on * these events, the abstract router callbacks can be generated to the multi-tenant aware router, * as well as the multi-tenant router forwarding provider. */ public class NeutronL3Adapter extends AbstractHandler implements GatewayMacResolverListener, ConfigInterface { private static final Logger LOG = LoggerFactory.getLogger(NeutronL3Adapter.class); // The implementation for each of these services is resolved by the OSGi Service Manager private volatile ConfigurationService configurationService; private volatile TenantNetworkManager tenantNetworkManager; private volatile NodeCacheManager nodeCacheManager; private volatile INeutronNetworkCRUD neutronNetworkCache; private volatile INeutronSubnetCRUD neutronSubnetCache; private volatile INeutronPortCRUD neutronPortCache; private volatile INeutronFloatingIPCRUD neutronFloatingIpCache; private volatile L3ForwardingProvider l3ForwardingProvider; private volatile InboundNatProvider inboundNatProvider; private volatile OutboundNatProvider outboundNatProvider; private volatile ArpProvider arpProvider; private volatile RoutingProvider routingProvider; private volatile GatewayMacResolver gatewayMacResolver; private volatile SecurityServicesManager securityServicesManager; private class FloatIpData { // br-int of node where floating ip is associated with tenant port private final Long dpid; // patch port in br-int used to reach br-ex private final Long ofPort; // segmentation id of the net where fixed ip is instantiated private final String segId; // mac address assigned to neutron port of floating ip private final String macAddress; private final String floatingIpAddress; // ip address given to tenant vm private final String fixedIpAddress; private final String neutronRouterMac; FloatIpData(final Long dpid, final Long ofPort, final String segId, final String macAddress, final String floatingIpAddress, final String fixedIpAddress, final String neutronRouterMac) { this.dpid = dpid; this.ofPort = ofPort; this.segId = segId; this.macAddress = macAddress; this.floatingIpAddress = floatingIpAddress; this.fixedIpAddress = fixedIpAddress; this.neutronRouterMac = neutronRouterMac; } } private Map<String, String> networkIdToRouterMacCache; private Map<String, List<Neutron_IPs>> networkIdToRouterIpListCache; private Map<String, NeutronRouter_Interface> subnetIdToRouterInterfaceCache; private Map<String, Pair<Long, Uuid>> neutronPortToDpIdCache; private Map<String, FloatIpData> floatIpDataMapCache; private String externalRouterMac; private Boolean enabled = false; private Boolean flgDistributedARPEnabled = true; private Boolean isCachePopulationDone = false; private final ExecutorService gatewayMacResolverPool = Executors.newFixedThreadPool(5); private Southbound southbound; private NeutronModelsDataStoreHelper neutronModelsDataStoreHelper; private static final String OWNER_ROUTER_INTERFACE = "network:router_interface"; private static final String OWNER_ROUTER_INTERFACE_DISTRIBUTED = "network:router_interface_distributed"; private static final String OWNER_ROUTER_GATEWAY = "network:router_gateway"; private static final String OWNER_FLOATING_IP = "network:floatingip"; private static final String DEFAULT_EXT_RTR_MAC = "00:00:5E:00:01:01"; public NeutronL3Adapter(NeutronModelsDataStoreHelper neutronHelper) { LOG.info(">>>>>> NeutronL3Adapter constructor {}", this.getClass()); this.neutronModelsDataStoreHelper = neutronHelper; } private void initL3AdapterMembers() { Preconditions.checkNotNull(configurationService); if (configurationService.isL3ForwardingEnabled()) { this.networkIdToRouterMacCache = new HashMap<>(); this.networkIdToRouterIpListCache = new HashMap<>(); this.subnetIdToRouterInterfaceCache = new HashMap<>(); this.neutronPortToDpIdCache = new HashMap<>(); this.floatIpDataMapCache = new HashMap<>(); this.externalRouterMac = configurationService.getDefaultGatewayMacAddress(null); if (this.externalRouterMac == null) { this.externalRouterMac = DEFAULT_EXT_RTR_MAC; } this.enabled = true; LOG.info("OVSDB L3 forwarding is enabled"); if (configurationService.isDistributedArpDisabled()) { this.flgDistributedARPEnabled = false; LOG.info("Distributed ARP responder is disabled"); } else { LOG.debug("Distributed ARP responder is enabled"); } } else { LOG.debug("OVSDB L3 forwarding is disabled"); } } // Callbacks from AbstractHandler @Override public void processEvent(AbstractEvent abstractEvent) { if (!(abstractEvent instanceof NeutronL3AdapterEvent)) { LOG.error("Unable to process abstract event " + abstractEvent); return; } if (!this.enabled) { return; } NeutronL3AdapterEvent ev = (NeutronL3AdapterEvent) abstractEvent; switch (ev.getAction()) { case UPDATE: if (ev.getSubType() == NeutronL3AdapterEvent.SubType.SUBTYPE_EXTERNAL_MAC_UPDATE) { updateExternalRouterMac( ev.getMacAddress().getValue() ); } else { LOG.warn("Received update for an unexpected event " + ev); } break; case ADD: // fall through... // break; case DELETE: // fall through... // break; default: LOG.warn("Unable to process event " + ev); break; } } // Callbacks from GatewayMacResolverListener @Override public void gatewayMacResolved(Long externalNetworkBridgeDpid, IpAddress gatewayIpAddress, MacAddress macAddress) { LOG.info("got gatewayMacResolved callback for ip {} on dpid {} to mac {}", gatewayIpAddress, externalNetworkBridgeDpid, macAddress); if (!this.enabled) { return; } if (macAddress == null || macAddress.getValue() == null) { // TODO: handle cases when mac is null return; } // Enqueue event so update is handled by adapter's thread enqueueEvent( new NeutronL3AdapterEvent(externalNetworkBridgeDpid, gatewayIpAddress, macAddress) ); } private void populateL3ForwardingCaches() { if (!this.enabled) { return; } if(this.isCachePopulationDone || this.neutronFloatingIpCache == null || this.neutronPortCache == null ||this.neutronNetworkCache == null) { return; } this.isCachePopulationDone = true; LOG.debug("Populating NetVirt L3 caches from data store configuration"); Routers routers = this.neutronModelsDataStoreHelper.readAllNeutronRouters(); Ports ports = this.neutronModelsDataStoreHelper.readAllNeutronPorts(); if(routers != null && routers.getRouter() != null && ports != null) { LOG.debug("L3 Cache Population : {} Neutron router present in data store",routers.getRouter().size()); for( Router router : routers.getRouter()) { LOG.debug("L3 Cache Population : Populate caches for router {}",router); if(!ports.getPort().isEmpty()) { for( Port port : ports.getPort()) { if (port.getDeviceId().equals(router.getUuid().getValue()) && port.getDeviceOwner().equals(OWNER_ROUTER_INTERFACE)) { LOG.debug("L3 Cache Population : Router interface {} found.",port); networkIdToRouterMacCache.put(port.getNetworkId().getValue() , port.getMacAddress()); networkIdToRouterIpListCache.put(port.getNetworkId().getValue(), NeutronIAwareUtil.convertMDSalIpToNeutronIp(port.getFixedIps())); subnetIdToRouterInterfaceCache.put(port.getFixedIps().get(0).getSubnetId().getValue(), NeutronIAwareUtil.convertMDSalInterfaceToNeutronRouterInterface(port)); } } }else { LOG.warn("L3 Cache Population :Did not find any port information " + "in config Data Store for router {}",router); } } } LOG.debug("NetVirt L3 caches population is done"); } private Pair<Long, Uuid> getDpIdOfNeutronPort(String neutronTenantPortUuid) { if(neutronPortToDpIdCache.get(neutronTenantPortUuid) == null) { List<Node> bridges = this.southbound.readOvsdbTopologyBridgeNodes(); LOG.debug("getDpIdOfNeutronPort : {} bridges present in ovsdb topology",bridges.size()); for(Node bridge : bridges) { List<OvsdbTerminationPointAugmentation> interfaces = southbound.extractTerminationPointAugmentations(bridge); if(interfaces != null && !interfaces.isEmpty()) { LOG.debug("getDpIdOfNeutronPort : {} termination point present on bridge {}", interfaces.size(), bridge.getNodeId()); for (OvsdbTerminationPointAugmentation intf : interfaces) { NeutronPort neutronPort = tenantNetworkManager.getTenantPort(intf); if(neutronPort != null && neutronPort.getID().equals(neutronTenantPortUuid)) { Long dpId = getDpidForIntegrationBridge(bridge); Uuid interfaceUuid = intf.getInterfaceUuid(); LOG.debug("getDpIdOfNeutronPort : Found bridge {} and interface {} for the tenant neutron" + " port {}",dpId,interfaceUuid,neutronTenantPortUuid); handleInterfaceEventAdd(neutronPort.getPortUUID(), dpId, interfaceUuid); break; } } } } } return neutronPortToDpIdCache.get(neutronTenantPortUuid); } private Collection<FloatIpData> getAllFloatingIPsWithMetadata() { LOG.debug("getAllFloatingIPsWithMetadata : Fechting all floating Ips and it's metadata"); List<NeutronFloatingIP> neutronFloatingIps = neutronFloatingIpCache.getAllFloatingIPs(); if(neutronFloatingIps != null && !neutronFloatingIps.isEmpty()) { for (NeutronFloatingIP neutronFloatingIP : neutronFloatingIps) { if(!floatIpDataMapCache.containsKey(neutronFloatingIP.getID())){ LOG.debug("Metadata for floating ip {} is not present in the cache. " + "Fetching from data store.",neutronFloatingIP.getID()); this.getFloatingIPWithMetadata(neutronFloatingIP.getID()); } } } LOG.debug("getAllFloatingIPsWithMetadata : {} floating points found in data store",floatIpDataMapCache.size()); return floatIpDataMapCache.values(); } private FloatIpData getFloatingIPWithMetadata(String neutronFloatingId) { LOG.debug("getFloatingIPWithMetadata : Get Floating ip and it's meta data for neutron " + "floating id {} ",neutronFloatingId); if(floatIpDataMapCache.get(neutronFloatingId) == null) { NeutronFloatingIP neutronFloatingIP = neutronFloatingIpCache.getFloatingIP(neutronFloatingId); if (neutronFloatingIP == null) { LOG.error("getFloatingIPWithMetadata : Floating ip {} is missing from data store, that should not happen",neutronFloatingId); return null; } List<NeutronPort> neutronPorts = neutronPortCache.getAllPorts(); NeutronPort neutronPortForFloatIp = null; for (NeutronPort neutronPort : neutronPorts) { if (neutronPort.getDeviceOwner().equals(OWNER_FLOATING_IP) && neutronPort.getDeviceID().equals(neutronFloatingIP.getID())) { neutronPortForFloatIp = neutronPort; break; } } String neutronTenantPortUuid = neutronFloatingIP.getPortUUID(); if(neutronTenantPortUuid == null) { return null; } Pair<Long, Uuid> nodeIfPair = this.getDpIdOfNeutronPort(neutronTenantPortUuid); String floatingIpMac = neutronPortForFloatIp == null ? null : neutronPortForFloatIp.getMacAddress(); String fixedIpAddress = neutronFloatingIP.getFixedIPAddress(); String floatingIpAddress = neutronFloatingIP.getFloatingIPAddress(); NeutronPort tenantNeutronPort = neutronPortCache.getPort(neutronTenantPortUuid); NeutronNetwork tenantNeutronNetwork = tenantNeutronPort != null ? neutronNetworkCache.getNetwork(tenantNeutronPort.getNetworkUUID()) : null; String providerSegmentationId = tenantNeutronNetwork != null ? tenantNeutronNetwork.getProviderSegmentationID() : null; String neutronRouterMac = tenantNeutronNetwork != null ? networkIdToRouterMacCache.get(tenantNeutronNetwork.getID()) : null; if (nodeIfPair == null || neutronTenantPortUuid == null || providerSegmentationId == null || providerSegmentationId.isEmpty() || floatingIpMac == null || floatingIpMac.isEmpty() || neutronRouterMac == null || neutronRouterMac.isEmpty()) { LOG.debug("getFloatingIPWithMetadata :Floating IP {}<->{}, incomplete floatPort {} tenantPortUuid {} " + "seg {} mac {} rtrMac {}", fixedIpAddress, floatingIpAddress, neutronPortForFloatIp, neutronTenantPortUuid, providerSegmentationId, floatingIpMac, neutronRouterMac); return null; } // get ofport for patch port in br-int final Long dpId = nodeIfPair.getLeft(); final Long ofPort = findOFPortForExtPatch(dpId); if (ofPort == null) { LOG.warn("getFloatingIPWithMetadata : Unable to locate OF port of patch port " + "to connect floating ip to external bridge. dpid {}", dpId); return null; } final FloatIpData floatIpData = new FloatIpData(dpId, ofPort, providerSegmentationId, floatingIpMac, floatingIpAddress, fixedIpAddress, neutronRouterMac); floatIpDataMapCache.put(neutronFloatingIP.getID(), floatIpData); } return floatIpDataMapCache.get(neutronFloatingId); } /** * Invoked to configure the mac address for the external gateway in br-ex. ovsdb netvirt needs help in getting * mac for given ip in br-ex (bug 3378). For example, since ovsdb has no real arp, it needs a service in can * subscribe so that the mac address associated to the gateway ip address is available. * * @param externalRouterMacUpdate The mac address to be associated to the gateway. */ public void updateExternalRouterMac(final String externalRouterMacUpdate) { Preconditions.checkNotNull(externalRouterMacUpdate); flushExistingIpRewrite(); this.externalRouterMac = externalRouterMacUpdate; rebuildExistingIpRewrite(); } /** * Process the event. * * @param action the {@link org.opendaylight.ovsdb.openstack.netvirt.api.Action} action to be handled. * @param subnet An instance of NeutronSubnet object. */ public void handleNeutronSubnetEvent(final NeutronSubnet subnet, Action action) { LOG.debug("Neutron subnet {} event : {}", action, subnet.toString()); } /** * Process the port event as a router interface event. * For a not delete action, since a port is only create when the tennat uses the subnet, it is required to * verify if all routers across all nodes have the interface for the port's subnet(s) configured. * * @param action the {@link org.opendaylight.ovsdb.openstack.netvirt.api.Action} action to be handled. * @param neutronPort An instance of NeutronPort object. */ public void handleNeutronPortEvent(final NeutronPort neutronPort, Action action) { LOG.debug("Neutron port {} event : {}", action, neutronPort.toString()); if (!this.enabled) { return; } this.processSecurityGroupUpdate(neutronPort); final boolean isDelete = action == Action.DELETE; if (neutronPort.getDeviceOwner().equalsIgnoreCase(OWNER_ROUTER_GATEWAY)){ if(!isDelete){ Node externalBridgeNode = getExternalBridgeNode(); if(externalBridgeNode != null){ LOG.info("Port {} is network router gateway interface, " + "triggering gateway resolution for the attached external network on node {}", neutronPort, externalBridgeNode); this.triggerGatewayMacResolver(externalBridgeNode, neutronPort); }else{ LOG.error("Did not find Node that has external bridge (br-ex), Gateway resolution failed"); } }else{ NeutronNetwork externalNetwork = neutronNetworkCache.getNetwork(neutronPort.getNetworkUUID()); if (externalNetwork != null && externalNetwork.isRouterExternal()) { final NeutronSubnet externalSubnet = getExternalNetworkSubnet(neutronPort); // TODO support IPv6 if (externalSubnet != null && externalSubnet.getIpVersion() == 4) { gatewayMacResolver.stopPeriodicRefresh(new Ipv4Address(externalSubnet.getGatewayIP())); } } } } // Treat the port event as a router interface event if the port belongs to router. This is a // helper for handling cases when handleNeutronRouterInterfaceEvent is not available if (neutronPort.getDeviceOwner().equalsIgnoreCase(OWNER_ROUTER_INTERFACE) || neutronPort.getDeviceOwner().equalsIgnoreCase(OWNER_ROUTER_INTERFACE_DISTRIBUTED)) { if (neutronPort.getFixedIPs() != null) { for (Neutron_IPs neutronIP : neutronPort.getFixedIPs()) { NeutronRouter_Interface neutronRouterInterface = new NeutronRouter_Interface(neutronIP.getSubnetUUID(), neutronPort.getPortUUID()); // id of router interface to be same as subnet neutronRouterInterface.setID(neutronIP.getSubnetUUID()); neutronRouterInterface.setTenantID(neutronPort.getTenantID()); this.handleNeutronRouterInterfaceEvent(null /*neutronRouter*/, neutronRouterInterface, action); } } } else { // We made it here, port is not used as a router interface. If this is not a delete action, make sure that // all nodes that are supposed to have a router interface for the port's subnet(s), have it configured. We // need to do this check here because a router interface is not added to a node until tenant becomes needed // there. if (!isDelete && neutronPort.getFixedIPs() != null) { for (Neutron_IPs neutronIP : neutronPort.getFixedIPs()) { NeutronRouter_Interface neutronRouterInterface = subnetIdToRouterInterfaceCache.get(neutronIP.getSubnetUUID()); if (neutronRouterInterface != null) { this.handleNeutronRouterInterfaceEvent(null /*neutronRouter*/, neutronRouterInterface, action); } } } this.updateL3ForNeutronPort(neutronPort, isDelete); } } /** * Process the event. * * @param action the {@link org.opendaylight.ovsdb.openstack.netvirt.api.Action} action to be handled. * @param neutronRouter An instance of NeutronRouter object. */ public void handleNeutronRouterEvent(final NeutronRouter neutronRouter, Action action) { LOG.debug("Neutron router {} event : {}", action, neutronRouter.toString()); } /** * Process the event enforcing actions and verifying dependencies between all router's interface. For example, * delete the ports on the same subnet. * * @param action the {@link org.opendaylight.ovsdb.openstack.netvirt.api.Action} action to be handled. * @param neutronRouter An instance of NeutronRouter object. * @param neutronRouterInterface An instance of NeutronRouter_Interface object. */ public void handleNeutronRouterInterfaceEvent(final NeutronRouter neutronRouter, final NeutronRouter_Interface neutronRouterInterface, Action action) { LOG.debug("Router interface {} got event {}. Subnet {}", neutronRouterInterface.getPortUUID(), action, neutronRouterInterface.getSubnetUUID()); if (!this.enabled) { return; } final boolean isDelete = action == Action.DELETE; this.programFlowsForNeutronRouterInterface(neutronRouterInterface, isDelete); // As neutron router interface is added/removed, we need to iterate through all the neutron ports and // see if they are affected by l3 for (NeutronPort neutronPort : neutronPortCache.getAllPorts()) { boolean currPortShouldBeDeleted = false; // Note: delete in this case only applies to 1)router interface delete and 2)ports on the same subnet if (isDelete) { if (neutronPort.getFixedIPs() != null) { for (Neutron_IPs neutronIP : neutronPort.getFixedIPs()) { if (neutronRouterInterface.getSubnetUUID().equalsIgnoreCase(neutronIP.getSubnetUUID())) { currPortShouldBeDeleted = true; break; } } } } this.updateL3ForNeutronPort(neutronPort, currPortShouldBeDeleted); } if (isDelete) { /* * Bug 4277: Remove the router interface cache only after deleting the neutron port l3 flows. */ this.cleanupRouterCache(neutronRouterInterface); } } /** * Invoked when a neutron message regarding the floating ip association is sent to odl via ml2. If the action is * a creation, it will first add ARP rules for the given floating ip and then configure the DNAT (rewrite the * packets from the floating IP address to the internal fixed ip) rules on OpenFlow Table 30 and SNAT rules (other * way around) on OpenFlow Table 100. * * @param actionIn the {@link org.opendaylight.ovsdb.openstack.netvirt.api.Action} action to be handled. * @param neutronFloatingIP An {@link org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronFloatingIP} instance of NeutronFloatingIP object. */ public void handleNeutronFloatingIPEvent(final NeutronFloatingIP neutronFloatingIP, Action actionIn) { Preconditions.checkNotNull(neutronFloatingIP); LOG.debug(" Floating IP {} {}<->{}, network uuid {}", actionIn, neutronFloatingIP.getFixedIPAddress(), neutronFloatingIP.getFloatingIPAddress(), neutronFloatingIP.getFloatingNetworkUUID()); if (!this.enabled) { return; } Action action; // Consider action to be delete if getFixedIPAddress is null if (neutronFloatingIP.getFixedIPAddress() == null) { action = Action.DELETE; } else { action = actionIn; } // this.programFlowsForFloatingIP(neutronFloatingIP, action == Action.DELETE); if (action != Action.DELETE) { // must be first, as it updates floatIpDataMapCache programFlowsForFloatingIPArpAdd(neutronFloatingIP); programFlowsForFloatingIPInbound(neutronFloatingIP, Action.ADD); programFlowsForFloatingIPOutbound(neutronFloatingIP, Action.ADD); } else { programFlowsForFloatingIPOutbound(neutronFloatingIP, Action.DELETE); programFlowsForFloatingIPInbound(neutronFloatingIP, Action.DELETE); // must be last, as it updates floatIpDataMapCache programFlowsForFloatingIPArpDelete(neutronFloatingIP.getID()); } } /** * This method performs creation or deletion of in-bound rules into Table 30 for a existing available floating * ip, otherwise for newer one. */ private void programFlowsForFloatingIPInbound(final NeutronFloatingIP neutronFloatingIP, final Action action) { Preconditions.checkNotNull(neutronFloatingIP); final FloatIpData fid = getFloatingIPWithMetadata(neutronFloatingIP.getID()); if (fid == null) { LOG.trace("programFlowsForFloatingIPInboundAdd {} for {} uuid {} not in local cache", action, neutronFloatingIP.getFloatingIPAddress(), neutronFloatingIP.getID()); return; } programInboundIpRewriteStage1(fid.dpid, fid.ofPort, fid.segId, fid.floatingIpAddress, fid.fixedIpAddress, action); } /** * This method performs creation or deletion of out-bound rules into Table 100 for a existing available floating * ip, otherwise for newer one. */ private void programFlowsForFloatingIPOutbound(final NeutronFloatingIP neutronFloatingIP, final Action action) { Preconditions.checkNotNull(neutronFloatingIP); final FloatIpData fid = getFloatingIPWithMetadata(neutronFloatingIP.getID()); if (fid == null) { LOG.trace("programFlowsForFloatingIPOutbound {} for {} uuid {} not in local cache", action, neutronFloatingIP.getFloatingIPAddress(), neutronFloatingIP.getID()); return; } programOutboundIpRewriteStage1(fid, action); } private void flushExistingIpRewrite() { for (FloatIpData fid : getAllFloatingIPsWithMetadata()) { programOutboundIpRewriteStage1(fid, Action.DELETE); } } private void rebuildExistingIpRewrite() { for (FloatIpData fid : getAllFloatingIPsWithMetadata()) { programOutboundIpRewriteStage1(fid, Action.ADD); } } /** * This method creates ARP response rules into OpenFlow Table 30 for a given floating ip. In order to connect * to br-ex from br-int, a patch-port is used. Thus, the patch-port will be responsible to respond the ARP * requests. */ private void programFlowsForFloatingIPArpAdd(final NeutronFloatingIP neutronFloatingIP) { Preconditions.checkNotNull(neutronFloatingIP); Preconditions.checkNotNull(neutronFloatingIP.getFixedIPAddress()); Preconditions.checkNotNull(neutronFloatingIP.getFloatingIPAddress()); // find bridge Node where floating ip is configured by looking up cache for its port final NeutronPort neutronPortForFloatIp = findNeutronPortForFloatingIp(neutronFloatingIP.getID()); final String neutronTenantPortUuid = neutronFloatingIP.getPortUUID(); final Pair<Long, Uuid> nodeIfPair = this.getDpIdOfNeutronPort(neutronTenantPortUuid); final String floatingIpMac = neutronPortForFloatIp == null ? null : neutronPortForFloatIp.getMacAddress(); final String fixedIpAddress = neutronFloatingIP.getFixedIPAddress(); final String floatingIpAddress = neutronFloatingIP.getFloatingIPAddress(); final NeutronPort tenantNeutronPort = neutronPortCache.getPort(neutronTenantPortUuid); final NeutronNetwork tenantNeutronNetwork = tenantNeutronPort != null ? neutronNetworkCache.getNetwork(tenantNeutronPort.getNetworkUUID()) : null; final String providerSegmentationId = tenantNeutronNetwork != null ? tenantNeutronNetwork.getProviderSegmentationID() : null; final String neutronRouterMac = tenantNeutronNetwork != null ? networkIdToRouterMacCache.get(tenantNeutronNetwork.getID()) : null; if (nodeIfPair == null || neutronTenantPortUuid == null || providerSegmentationId == null || providerSegmentationId.isEmpty() || floatingIpMac == null || floatingIpMac.isEmpty() || neutronRouterMac == null || neutronRouterMac.isEmpty()) { LOG.trace("Floating IP {}<->{}, incomplete floatPort {} tenantPortUuid {} seg {} mac {} rtrMac {}", fixedIpAddress, floatingIpAddress, neutronPortForFloatIp, neutronTenantPortUuid, providerSegmentationId, floatingIpMac, neutronRouterMac); return; } // get ofport for patch port in br-int final Long dpId = nodeIfPair.getLeft(); final Long ofPort = findOFPortForExtPatch(dpId); if (ofPort == null) { LOG.warn("Unable to locate OF port of patch port to connect floating ip to external bridge. dpid {}", dpId); return; } // Respond to ARPs for the floating ip address by default, via the patch port that connects br-int to br-ex if (programStaticArpStage1(dpId, encodeExcplicitOFPort(ofPort), floatingIpMac, floatingIpAddress, Action.ADD)) { final FloatIpData floatIpData = new FloatIpData(dpId, ofPort, providerSegmentationId, floatingIpMac, floatingIpAddress, fixedIpAddress, neutronRouterMac); floatIpDataMapCache.put(neutronFloatingIP.getID(), floatIpData); LOG.info("Floating IP {}<->{} programmed ARP mac {} on OFport {} seg {} dpid {}", neutronFloatingIP.getFixedIPAddress(), neutronFloatingIP.getFloatingIPAddress(), floatingIpMac, ofPort, providerSegmentationId, dpId); } } private void programFlowsForFloatingIPArpDelete(final String neutronFloatingIPUuid) { final FloatIpData floatIpData = getFloatingIPWithMetadata(neutronFloatingIPUuid); if (floatIpData == null) { LOG.trace("programFlowsForFloatingIPArpDelete for uuid {} is not needed", neutronFloatingIPUuid); return; } if (programStaticArpStage1(floatIpData.dpid, encodeExcplicitOFPort(floatIpData.ofPort), floatIpData.macAddress, floatIpData.floatingIpAddress, Action.DELETE)) { floatIpDataMapCache.remove(neutronFloatingIPUuid); LOG.info("Floating IP {} un-programmed ARP mac {} on {} dpid {}", floatIpData.floatingIpAddress, floatIpData.macAddress, floatIpData.ofPort, floatIpData.dpid); } } private NeutronPort findNeutronPortForFloatingIp(final String floatingIpUuid) { for (NeutronPort neutronPort : neutronPortCache.getAllPorts()) { if (neutronPort.getDeviceOwner().equals(OWNER_FLOATING_IP) && neutronPort.getDeviceID().equals(floatingIpUuid)) { return neutronPort; } } return null; } private Long findOFPortForExtPatch(Long dpId) { final String brInt = configurationService.getIntegrationBridgeName(); final String brExt = configurationService.getExternalBridgeName(); final String portNameInt = configurationService.getPatchPortName(new ImmutablePair<>(brInt, brExt)); Preconditions.checkNotNull(dpId); Preconditions.checkNotNull(portNameInt); final long dpidPrimitive = dpId; for (Node node : nodeCacheManager.getBridgeNodes()) { if (dpidPrimitive == southbound.getDataPathId(node)) { final OvsdbTerminationPointAugmentation terminationPointOfBridge = southbound.getTerminationPointOfBridge(node, portNameInt); return terminationPointOfBridge == null ? null : terminationPointOfBridge.getOfport(); } } return null; } /** * Process the event. * * @param action the {@link org.opendaylight.ovsdb.openstack.netvirt.api.Action} action to be handled. * @param neutronNetwork An {@link org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronNetwork} instance of NeutronFloatingIP object. */ public void handleNeutronNetworkEvent(final NeutronNetwork neutronNetwork, Action action) { LOG.debug("neutronNetwork {}: network: {}", action, neutronNetwork); } // Callbacks from OVSDB's southbound handler /** * Process the event. * * @param bridgeNode An instance of Node object. * @param intf An {@link org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ovsdb.rev150105 * .OvsdbTerminationPointAugmentation} instance of OvsdbTerminationPointAugmentation object. * @param neutronNetwork An {@link org.opendaylight.ovsdb.openstack.netvirt.translator.NeutronNetwork} instance of NeutronNetwork * object. * @param action the {@link org.opendaylight.ovsdb.openstack.netvirt.api.Action} action to be handled. */ public void handleInterfaceEvent(final Node bridgeNode, final OvsdbTerminationPointAugmentation intf, final NeutronNetwork neutronNetwork, Action action) { LOG.debug("southbound interface {} node:{} interface:{}, neutronNetwork:{}", action, bridgeNode.getNodeId().getValue(), intf.getName(), neutronNetwork); if (!this.enabled) { return; } final NeutronPort neutronPort = tenantNetworkManager.getTenantPort(intf); final Long dpId = getDpidForIntegrationBridge(bridgeNode); final Uuid interfaceUuid = intf.getInterfaceUuid(); LOG.trace("southbound interface {} node:{} interface:{}, neutronNetwork:{} port:{} dpid:{} intfUuid:{}", action, bridgeNode.getNodeId().getValue(), intf.getName(), neutronNetwork, neutronPort, dpId, interfaceUuid); if (neutronPort != null) { final String neutronPortUuid = neutronPort.getPortUUID(); if (action != Action.DELETE && dpId != null && interfaceUuid != null) { handleInterfaceEventAdd(neutronPortUuid, dpId, interfaceUuid); } handleNeutronPortEvent(neutronPort, action); } if (action == Action.DELETE && interfaceUuid != null) { handleInterfaceEventDelete(intf, dpId); } } private void handleInterfaceEventAdd(final String neutronPortUuid, Long dpId, final Uuid interfaceUuid) { neutronPortToDpIdCache.put(neutronPortUuid, new ImmutablePair<>(dpId, interfaceUuid)); LOG.debug("handleInterfaceEvent add cache entry NeutronPortUuid {} : dpid {}, ifUuid {}", neutronPortUuid, dpId, interfaceUuid.getValue()); } private void handleInterfaceEventDelete(final OvsdbTerminationPointAugmentation intf, final Long dpId) { // Remove entry from neutronPortToDpIdCache based on interface uuid for (Map.Entry<String, Pair<Long, Uuid>> entry : neutronPortToDpIdCache.entrySet()) { final String currPortUuid = entry.getKey(); if (intf.getInterfaceUuid().equals(entry.getValue().getRight())) { LOG.debug("handleInterfaceEventDelete remove cache entry NeutronPortUuid {} : dpid {}, ifUuid {}", currPortUuid, dpId, intf.getInterfaceUuid().getValue()); neutronPortToDpIdCache.remove(currPortUuid); break; } } } // Internal helpers private void updateL3ForNeutronPort(final NeutronPort neutronPort, final boolean isDelete) { final String networkUUID = neutronPort.getNetworkUUID(); final String routerMacAddress = networkIdToRouterMacCache.get(networkUUID); // If there is no router interface handling the networkUUID, we are done if (routerMacAddress == null || routerMacAddress.isEmpty()) { return; } // If this is the neutron port for the router interface itself, ignore it as well. Ports that represent the // router interface are handled via handleNeutronRouterInterfaceEvent. if (routerMacAddress.equalsIgnoreCase(neutronPort.getMacAddress())) { return; } final NeutronNetwork neutronNetwork = neutronNetworkCache.getNetwork(networkUUID); final String providerSegmentationId = neutronNetwork != null ? neutronNetwork.getProviderSegmentationID() : null; final String tenantMac = neutronPort.getMacAddress(); if (providerSegmentationId == null || providerSegmentationId.isEmpty() || tenantMac == null || tenantMac.isEmpty()) { // done: go no further w/out all the info needed... return; } final Action action = isDelete ? Action.DELETE : Action.ADD; List<Node> nodes = nodeCacheManager.getBridgeNodes(); if (nodes.isEmpty()) { LOG.trace("updateL3ForNeutronPort has no nodes to work with"); } for (Node node : nodes) { final Long dpid = getDpidForIntegrationBridge(node); if (dpid == null) { continue; } if (neutronPort.getFixedIPs() == null) { continue; } for (Neutron_IPs neutronIP : neutronPort.getFixedIPs()) { final String tenantIpStr = neutronIP.getIpAddress(); if (tenantIpStr.isEmpty()) { continue; } // Configure L3 fwd. We do that regardless of tenant network present, because these rules are // still needed when routing to subnets non-local to node (bug 2076). programL3ForwardingStage1(node, dpid, providerSegmentationId, tenantMac, tenantIpStr, action); // Configure distributed ARP responder if (flgDistributedARPEnabled) { // Arp rule is only needed when segmentation exists in the given node (bug 4752). boolean arpNeeded = tenantNetworkManager.isTenantNetworkPresentInNode(node, providerSegmentationId); final Action actionForNode = arpNeeded ? action : Action.DELETE; programStaticArpStage1(dpid, providerSegmentationId, tenantMac, tenantIpStr, actionForNode); } } } } private void processSecurityGroupUpdate(NeutronPort neutronPort) { LOG.trace("processSecurityGroupUpdate:" + neutronPort); /** * Get updated data and original data for the the changed. Identify the security groups that got * added and removed and call the appropriate providers for updating the flows. */ try { NeutronPort originalPort = neutronPort.getOriginalPort(); if (null == originalPort) { LOG.debug("processSecurityGroupUpdate: originalport is empty"); return; } List<NeutronSecurityGroup> addedGroup = getsecurityGroupChanged(neutronPort, neutronPort.getOriginalPort()); List<NeutronSecurityGroup> deletedGroup = getsecurityGroupChanged(neutronPort.getOriginalPort(), neutronPort); if (null != addedGroup && !addedGroup.isEmpty()) { securityServicesManager.syncSecurityGroup(neutronPort,addedGroup,true); } if (null != deletedGroup && !deletedGroup.isEmpty()) { securityServicesManager.syncSecurityGroup(neutronPort,deletedGroup,false); } } catch (Exception e) { LOG.error("Exception in processSecurityGroupUpdate", e); } } private List<NeutronSecurityGroup> getsecurityGroupChanged(NeutronPort port1, NeutronPort port2) { LOG.trace("getsecurityGroupChanged:" + "Port1:" + port1 + "Port2" + port2); List<NeutronSecurityGroup> list1 = new ArrayList<>(port1.getSecurityGroups()); List<NeutronSecurityGroup> list2 = new ArrayList<>(port2.getSecurityGroups()); for (Iterator<NeutronSecurityGroup> iterator = list1.iterator(); iterator.hasNext();) { NeutronSecurityGroup securityGroup1 = iterator.next(); for (NeutronSecurityGroup securityGroup2 :list2) { if (securityGroup1.getID().equals(securityGroup2.getID())) { iterator.remove(); } } } return list1; } private void programL3ForwardingStage1(Node node, Long dpid, String providerSegmentationId, String macAddress, String ipStr, Action actionForNode) { if (actionForNode == Action.DELETE) { LOG.trace("Deleting Flow : programL3ForwardingStage1 for node {} providerId {} mac {} ip {} action {}", node.getNodeId().getValue(), providerSegmentationId, macAddress, ipStr, actionForNode); } if (actionForNode == Action.ADD) { LOG.trace("Adding Flow : programL3ForwardingStage1 for node {} providerId {} mac {} ip {} action {}", node.getNodeId().getValue(), providerSegmentationId, macAddress, ipStr, actionForNode); } this.programL3ForwardingStage2(node, dpid, providerSegmentationId, macAddress, ipStr, actionForNode); } private Status programL3ForwardingStage2(Node node, Long dpid, String providerSegmentationId, String macAddress, String address, Action actionForNode) { Status status; try { InetAddress inetAddress = InetAddress.getByName(address); status = l3ForwardingProvider == null ? new Status(StatusCode.SUCCESS) : l3ForwardingProvider.programForwardingTableEntry(dpid, providerSegmentationId, inetAddress, macAddress, actionForNode); } catch (UnknownHostException e) { status = new Status(StatusCode.BADREQUEST); } if (status.isSuccess()) { LOG.debug("ProgramL3Forwarding {} for mac:{} addr:{} node:{} action:{}", l3ForwardingProvider == null ? "skipped" : "programmed", macAddress, address, node.getNodeId().getValue(), actionForNode); } else { LOG.error("ProgramL3Forwarding failed for mac:{} addr:{} node:{} action:{} status:{}", macAddress, address, node.getNodeId().getValue(), actionForNode, status); } return status; } private void programFlowsForNeutronRouterInterface(final NeutronRouter_Interface destNeutronRouterInterface, Boolean isDelete) { Preconditions.checkNotNull(destNeutronRouterInterface); final NeutronPort neutronPort = neutronPortCache.getPort(destNeutronRouterInterface.getPortUUID()); String macAddress = neutronPort != null ? neutronPort.getMacAddress() : null; List<Neutron_IPs> ipList = neutronPort != null ? neutronPort.getFixedIPs() : null; final NeutronSubnet subnet = neutronSubnetCache.getSubnet(destNeutronRouterInterface.getSubnetUUID()); final NeutronNetwork neutronNetwork = subnet != null ? neutronNetworkCache.getNetwork(subnet.getNetworkUUID()) : null; final String destinationSegmentationId = neutronNetwork != null ? neutronNetwork.getProviderSegmentationID() : null; final Boolean isExternal = neutronNetwork != null ? neutronNetwork.getRouterExternal() : Boolean.TRUE; final String cidr = subnet != null ? subnet.getCidr() : null; final int mask = getMaskLenFromCidr(cidr); LOG.trace("programFlowsForNeutronRouterInterface called for interface {} isDelete {}", destNeutronRouterInterface, isDelete); // in delete path, mac address as well as ip address are not provided. Being so, let's find them from // the local cache if (neutronNetwork != null) { if (macAddress == null || macAddress.isEmpty()) { macAddress = networkIdToRouterMacCache.get(neutronNetwork.getNetworkUUID()); } if (ipList == null || ipList.isEmpty()) { ipList = networkIdToRouterIpListCache.get(neutronNetwork.getNetworkUUID()); } } if (destinationSegmentationId == null || destinationSegmentationId.isEmpty() || cidr == null || cidr.isEmpty() || macAddress == null || macAddress.isEmpty() || ipList == null || ipList.isEmpty()) { LOG.debug("programFlowsForNeutronRouterInterface is bailing seg:{} cidr:{} mac:{} ip:{}", destinationSegmentationId, cidr, macAddress, ipList); // done: go no further w/out all the info needed... return; } final Action actionForNode = isDelete ? Action.DELETE : Action.ADD; // Keep cache for finding router's mac from network uuid -- add if (! isDelete) { networkIdToRouterMacCache.put(neutronNetwork.getNetworkUUID(), macAddress); networkIdToRouterIpListCache.put(neutronNetwork.getNetworkUUID(), new ArrayList<>(ipList)); subnetIdToRouterInterfaceCache.put(subnet.getSubnetUUID(), destNeutronRouterInterface); } List<Node> nodes = nodeCacheManager.getBridgeNodes(); if (nodes.isEmpty()) { LOG.trace("programFlowsForNeutronRouterInterface has no nodes to work with"); } for (Node node : nodes) { final Long dpid = getDpidForIntegrationBridge(node); if (dpid == null) { continue; } for (Neutron_IPs neutronIP : ipList) { final String ipStr = neutronIP.getIpAddress(); if (ipStr.isEmpty()) { LOG.debug("programFlowsForNeutronRouterInterface is skipping node {} ip {}", node.getNodeId().getValue(), ipStr); continue; } // Iterate through all other interfaces and add/remove reflexive flows to this interface for (NeutronRouter_Interface srcNeutronRouterInterface : subnetIdToRouterInterfaceCache.values()) { programFlowsForNeutronRouterInterfacePair(node, dpid, srcNeutronRouterInterface, destNeutronRouterInterface, neutronNetwork, destinationSegmentationId, macAddress, ipStr, mask, actionForNode, true /*isReflexsive*/); } if (! isExternal) { programFlowForNetworkFromExternal(node, dpid, destinationSegmentationId, macAddress, ipStr, mask, actionForNode); } // Enable ARP responder by default, because router interface needs to be responded always. programStaticArpStage1(dpid, destinationSegmentationId, macAddress, ipStr, actionForNode); } // Compute action to be programmed. In the case of rewrite exclusions, we must never program rules // for the external neutron networks. { final Action actionForRewriteExclusion = isExternal ? Action.DELETE : actionForNode; programIpRewriteExclusionStage1(node, dpid, destinationSegmentationId, cidr, actionForRewriteExclusion); } } // Keep cache for finding router's mac from network uuid -- NOTE: remove is done later, via cleanupRouterCache() } private void programFlowForNetworkFromExternal(final Node node, final Long dpid, final String destinationSegmentationId, final String dstMacAddress, final String destIpStr, final int destMask, final Action actionForNode) { programRouterInterfaceStage1(node, dpid, Constants.EXTERNAL_NETWORK, destinationSegmentationId, dstMacAddress, destIpStr, destMask, actionForNode); } private void programFlowsForNeutronRouterInterfacePair(final Node node, final Long dpid, final NeutronRouter_Interface srcNeutronRouterInterface, final NeutronRouter_Interface dstNeutronRouterInterface, final NeutronNetwork dstNeutronNetwork, final String destinationSegmentationId, final String dstMacAddress, final String destIpStr, final int destMask, final Action actionForNode, Boolean isReflexsive) { Preconditions.checkNotNull(srcNeutronRouterInterface); Preconditions.checkNotNull(dstNeutronRouterInterface); final String sourceSubnetId = srcNeutronRouterInterface.getSubnetUUID(); if (sourceSubnetId == null) { LOG.error("Could not get provider Subnet ID from router interface {}", srcNeutronRouterInterface.getID()); return; } final NeutronSubnet sourceSubnet = neutronSubnetCache.getSubnet(sourceSubnetId); final String sourceNetworkId = sourceSubnet == null ? null : sourceSubnet.getNetworkUUID(); if (sourceNetworkId == null) { LOG.error("Could not get provider Network ID from subnet {}", sourceSubnetId); return; } final NeutronNetwork sourceNetwork = neutronNetworkCache.getNetwork(sourceNetworkId); if (sourceNetwork == null) { LOG.error("Could not get provider Network for Network ID {}", sourceNetworkId); return; } if (! sourceNetwork.getTenantID().equals(dstNeutronNetwork.getTenantID())) { // Isolate subnets from different tenants within the same router return; } final String sourceSegmentationId = sourceNetwork.getProviderSegmentationID(); if (sourceSegmentationId == null) { LOG.error("Could not get provider Segmentation ID for Subnet {}", sourceSubnetId); return; } if (sourceSegmentationId.equals(destinationSegmentationId)) { // Skip 'self' return; } programRouterInterfaceStage1(node, dpid, sourceSegmentationId, destinationSegmentationId, dstMacAddress, destIpStr, destMask, actionForNode); // Flip roles src->dst; dst->src if (isReflexsive) { final NeutronPort sourceNeutronPort = neutronPortCache.getPort(srcNeutronRouterInterface.getPortUUID()); final String macAddress2 = sourceNeutronPort != null ? sourceNeutronPort.getMacAddress() : null; final List<Neutron_IPs> ipList2 = sourceNeutronPort != null ? sourceNeutronPort.getFixedIPs() : null; final String cidr2 = sourceSubnet.getCidr(); final int mask2 = getMaskLenFromCidr(cidr2); if (cidr2 == null || cidr2.isEmpty() || macAddress2 == null || macAddress2.isEmpty() || ipList2 == null || ipList2.isEmpty()) { LOG.trace("programFlowsForNeutronRouterInterfacePair reflexive is bailing seg:{} cidr:{} mac:{} ip:{}", sourceSegmentationId, cidr2, macAddress2, ipList2); // done: go no further w/out all the info needed... return; } for (Neutron_IPs neutronIP2 : ipList2) { final String ipStr2 = neutronIP2.getIpAddress(); if (ipStr2.isEmpty()) { continue; } programFlowsForNeutronRouterInterfacePair(node, dpid, dstNeutronRouterInterface, srcNeutronRouterInterface, sourceNetwork, sourceSegmentationId, macAddress2, ipStr2, mask2, actionForNode, false /*isReflexsive*/); } } } private void programRouterInterfaceStage1(Node node, Long dpid, String sourceSegmentationId, String destinationSegmentationId, String macAddress, String ipStr, int mask, Action actionForNode) { if (actionForNode == Action.DELETE) { LOG.trace("Deleting Flow : programRouterInterfaceStage1 for node {} sourceSegId {} destSegId {} mac {} ip {} mask {}" + " action {}", node.getNodeId().getValue(), sourceSegmentationId, destinationSegmentationId, macAddress, ipStr, mask, actionForNode); } if (actionForNode == Action.ADD) { LOG.trace("Adding Flow : programRouterInterfaceStage1 for node {} sourceSegId {} destSegId {} mac {} ip {} mask {}" + " action {}", node.getNodeId().getValue(), sourceSegmentationId, destinationSegmentationId, macAddress, ipStr, mask, actionForNode); } this.programRouterInterfaceStage2(node, dpid, sourceSegmentationId, destinationSegmentationId, macAddress, ipStr, mask, actionForNode); } private Status programRouterInterfaceStage2(Node node, Long dpid, String sourceSegmentationId, String destinationSegmentationId, String macAddress, String address, int mask, Action actionForNode) { Status status; try { InetAddress inetAddress = InetAddress.getByName(address); status = routingProvider == null ? new Status(StatusCode.SUCCESS) : routingProvider.programRouterInterface(dpid, sourceSegmentationId, destinationSegmentationId, macAddress, inetAddress, mask, actionForNode); } catch (UnknownHostException e) { status = new Status(StatusCode.BADREQUEST); } if (status.isSuccess()) { LOG.debug("ProgramRouterInterface {} for mac:{} addr:{}/{} node:{} srcTunId:{} destTunId:{} action:{}", routingProvider == null ? "skipped" : "programmed", macAddress, address, mask, node.getNodeId().getValue(), sourceSegmentationId, destinationSegmentationId, actionForNode); } else { LOG.error("ProgramRouterInterface failed for mac:{} addr:{}/{} node:{} srcTunId:{} destTunId:{} action:{} status:{}", macAddress, address, mask, node.getNodeId().getValue(), sourceSegmentationId, destinationSegmentationId, actionForNode, status); } return status; } private boolean programStaticArpStage1(Long dpid, String segOrOfPort, String macAddress, String ipStr, Action action) { if (action == Action.DELETE ) { LOG.trace("Deleting Flow : programStaticArpStage1 dpid {} segOrOfPort {} mac {} ip {} action {}", dpid, segOrOfPort, macAddress, ipStr, action); } if (action == Action.ADD) { LOG.trace("Adding Flow : programStaticArpStage1 dpid {} segOrOfPort {} mac {} ip {} action {} is already done", dpid, segOrOfPort, macAddress, ipStr, action); } Status status = this.programStaticArpStage2(dpid, segOrOfPort, macAddress, ipStr, action); return status.isSuccess(); } private Status programStaticArpStage2(Long dpid, String segOrOfPort, String macAddress, String address, Action action) { Status status; try { InetAddress inetAddress = InetAddress.getByName(address); status = arpProvider == null ? new Status(StatusCode.SUCCESS) : arpProvider.programStaticArpEntry(dpid, segOrOfPort, macAddress, inetAddress, action); } catch (UnknownHostException e) { status = new Status(StatusCode.BADREQUEST); } if (status.isSuccess()) { LOG.debug("ProgramStaticArp {} for mac:{} addr:{} dpid:{} segOrOfPort:{} action:{}", arpProvider == null ? "skipped" : "programmed", macAddress, address, dpid, segOrOfPort, action); } else { LOG.error("ProgramStaticArp failed for mac:{} addr:{} dpid:{} segOrOfPort:{} action:{} status:{}", macAddress, address, dpid, segOrOfPort, action, status); } return status; } private boolean programInboundIpRewriteStage1(Long dpid, Long inboundOFPort, String providerSegmentationId, String matchAddress, String rewriteAddress, Action action) { if (action == Action.DELETE ) { LOG.trace("Deleting Flow : programInboundIpRewriteStage1 dpid {} OFPort {} seg {} matchAddress {} rewriteAddress {}" + " action {}", dpid, inboundOFPort, providerSegmentationId, matchAddress, rewriteAddress, action); } if (action == Action.ADD ) { LOG.trace("Adding Flow : programInboundIpRewriteStage1 dpid {} OFPort {} seg {} matchAddress {} rewriteAddress {}" + " action {}", dpid, inboundOFPort, providerSegmentationId, matchAddress, rewriteAddress, action); } Status status = programInboundIpRewriteStage2(dpid, inboundOFPort, providerSegmentationId, matchAddress, rewriteAddress, action); return status.isSuccess(); } private Status programInboundIpRewriteStage2(Long dpid, Long inboundOFPort, String providerSegmentationId, String matchAddress, String rewriteAddress, Action action) { Status status; try { InetAddress inetMatchAddress = InetAddress.getByName(matchAddress); InetAddress inetRewriteAddress = InetAddress.getByName(rewriteAddress); status = inboundNatProvider == null ? new Status(StatusCode.SUCCESS) : inboundNatProvider.programIpRewriteRule(dpid, inboundOFPort, providerSegmentationId, inetMatchAddress, inetRewriteAddress, action); } catch (UnknownHostException e) { status = new Status(StatusCode.BADREQUEST); } if (status.isSuccess()) { final boolean isSkipped = inboundNatProvider == null; LOG.debug("programInboundIpRewriteStage2 {} for dpid:{} ofPort:{} seg:{} match:{} rewrite:{} action:{}", isSkipped ? "skipped" : "programmed", dpid, inboundOFPort, providerSegmentationId, matchAddress, rewriteAddress, action); } else { LOG.error("programInboundIpRewriteStage2 failed for dpid:{} ofPort:{} seg:{} match:{} rewrite:{} action:{}" + " status:{}", dpid, inboundOFPort, providerSegmentationId, matchAddress, rewriteAddress, action, status); } return status; } private void programIpRewriteExclusionStage1(Node node, Long dpid, String providerSegmentationId, String cidr, Action actionForRewriteExclusion) { if (actionForRewriteExclusion == Action.DELETE ) { LOG.trace("Deleting Flow : programIpRewriteExclusionStage1 node {} providerId {} cidr {} action {}", node.getNodeId().getValue(), providerSegmentationId, cidr, actionForRewriteExclusion); } if (actionForRewriteExclusion == Action.ADD) { LOG.trace("Adding Flow : programIpRewriteExclusionStage1 node {} providerId {} cidr {} action {}", node.getNodeId().getValue(), providerSegmentationId, cidr, actionForRewriteExclusion); } this.programIpRewriteExclusionStage2(node, dpid, providerSegmentationId, cidr,actionForRewriteExclusion); } private Status programIpRewriteExclusionStage2(Node node, Long dpid, String providerSegmentationId, String cidr, Action actionForNode) { final Status status = outboundNatProvider == null ? new Status(StatusCode.SUCCESS) : outboundNatProvider.programIpRewriteExclusion(dpid, providerSegmentationId, cidr, actionForNode); if (status.isSuccess()) { final boolean isSkipped = outboundNatProvider == null; LOG.debug("IpRewriteExclusion {} for cidr:{} node:{} action:{}", isSkipped ? "skipped" : "programmed", cidr, node.getNodeId().getValue(), actionForNode); } else { LOG.error("IpRewriteExclusion failed for cidr:{} node:{} action:{} status:{}", cidr, node.getNodeId().getValue(), actionForNode, status); } return status; } private void programOutboundIpRewriteStage1(FloatIpData fid, Action action) { if (action == Action.DELETE) { LOG.trace("Deleting Flow : programOutboundIpRewriteStage1 dpid {} seg {} fixedIpAddress {} floatIp {} action {} ", fid.dpid, fid.segId, fid.fixedIpAddress, fid.floatingIpAddress, action); } if (action == Action.ADD) { LOG.trace("Adding Flow : programOutboundIpRewriteStage1 dpid {} seg {} fixedIpAddress {} floatIp {} action {} " , fid.dpid, fid.segId, fid.fixedIpAddress, fid.floatingIpAddress, action); } this.programOutboundIpRewriteStage2(fid, action); } private Status programOutboundIpRewriteStage2(FloatIpData fid, Action action) { Status status; try { InetAddress matchSrcAddress = InetAddress.getByName(fid.fixedIpAddress); InetAddress rewriteSrcAddress = InetAddress.getByName(fid.floatingIpAddress); status = outboundNatProvider == null ? new Status(StatusCode.SUCCESS) : outboundNatProvider.programIpRewriteRule( fid.dpid, fid.segId, fid.neutronRouterMac, matchSrcAddress, fid.macAddress, this.externalRouterMac, rewriteSrcAddress, fid.ofPort, action); } catch (UnknownHostException e) { status = new Status(StatusCode.BADREQUEST); } if (status.isSuccess()) { final boolean isSkipped = outboundNatProvider == null; LOG.debug("programOutboundIpRewriteStage2 {} for dpid {} seg {} fixedIpAddress {} floatIp {}" + " action {}", isSkipped ? "skipped" : "programmed", fid.dpid, fid.segId, fid.fixedIpAddress, fid.floatingIpAddress, action); } else { LOG.error("programOutboundIpRewriteStage2 failed for dpid {} seg {} fixedIpAddress {} floatIp {}" + " action {} status:{}", fid.dpid, fid.segId, fid.fixedIpAddress, fid.floatingIpAddress, action, status); } return status; } private int getMaskLenFromCidr(String cidr) { if (cidr == null) { return 0; } String[] splits = cidr.split("/"); if (splits.length != 2) { return 0; } int result; try { result = Integer.parseInt(splits[1].trim()); } catch (NumberFormatException nfe) { result = 0; } return result; } private Long getDpidForIntegrationBridge(Node node) { // Check if node is integration bridge; and only then return its dpid if (southbound.getBridge(node, configurationService.getIntegrationBridgeName()) != null) { return southbound.getDataPathId(node); } return null; } private Long getDpidForExternalBridge(Node node) { // Check if node is integration bridge; and only then return its dpid if (southbound.getBridge(node, configurationService.getExternalBridgeName()) != null) { return southbound.getDataPathId(node); } return null; } private Node getExternalBridgeNode(){ //Pickup the first node that has external bridge (br-ex). //NOTE: We are assuming that all the br-ex are serving one external network and gateway ip of //the external network is reachable from every br-ex // TODO: Consider other deployment scenario, and thing of better solution. List<Node> allBridges = nodeCacheManager.getBridgeNodes(); for(Node node : allBridges){ if (southbound.getBridge(node, configurationService.getExternalBridgeName()) != null) { return node; } } return null; } private NeutronSubnet getExternalNetworkSubnet(NeutronPort gatewayPort){ if (gatewayPort.getFixedIPs() == null) { return null; } for (Neutron_IPs neutronIPs : gatewayPort.getFixedIPs()) { String subnetUUID = neutronIPs.getSubnetUUID(); NeutronSubnet extSubnet = neutronSubnetCache.getSubnet(subnetUUID); if (extSubnet != null && extSubnet.getGatewayIP() != null) { return extSubnet; } if (extSubnet == null) { // TODO: when subnet is created, try again. LOG.debug("subnet {} in not found", subnetUUID); } } return null; } private void cleanupRouterCache(final NeutronRouter_Interface neutronRouterInterface) { /* * Fix for 4277 * Remove the router cache only after deleting the neutron * port l3 flows. */ final NeutronPort neutronPort = neutronPortCache.getPort(neutronRouterInterface.getPortUUID()); if (neutronPort != null) { networkIdToRouterMacCache.remove(neutronPort.getNetworkUUID()); networkIdToRouterIpListCache.remove(neutronPort.getNetworkUUID()); subnetIdToRouterInterfaceCache.remove(neutronRouterInterface.getSubnetUUID()); } } public void triggerGatewayMacResolver(final Node node, final NeutronPort gatewayPort ){ Preconditions.checkNotNull(node); Preconditions.checkNotNull(gatewayPort); NeutronNetwork externalNetwork = neutronNetworkCache.getNetwork(gatewayPort.getNetworkUUID()); if(externalNetwork != null){ if(externalNetwork.isRouterExternal()){ final NeutronSubnet externalSubnet = getExternalNetworkSubnet(gatewayPort); // TODO: address IPv6 case. if (externalSubnet != null && externalSubnet.getIpVersion() == 4 && gatewayPort.getFixedIPs() != null) { LOG.info("Trigger MAC resolution for gateway ip {} on Node {}",externalSubnet.getGatewayIP(),node.getNodeId()); ListenableFuture<MacAddress> gatewayMacAddress = gatewayMacResolver.resolveMacAddress(this, getDpidForExternalBridge(node), new Ipv4Address(externalSubnet.getGatewayIP()), new Ipv4Address(gatewayPort.getFixedIPs().get(0).getIpAddress()), new MacAddress(gatewayPort.getMacAddress()), true); if(gatewayMacAddress != null){ Futures.addCallback(gatewayMacAddress, new FutureCallback<MacAddress>(){ @Override public void onSuccess(MacAddress result) { if(result != null){ if(!result.getValue().equals(externalRouterMac)){ updateExternalRouterMac(result.getValue()); LOG.info("Resolved MAC address for gateway IP {} is {}", externalSubnet.getGatewayIP(),result.getValue()); } }else{ LOG.warn("MAC address resolution failed for gateway IP {}", externalSubnet.getGatewayIP()); } } @Override public void onFailure(Throwable t) { LOG.warn("MAC address resolution failed for gateway IP {}", externalSubnet.getGatewayIP()); } }, gatewayMacResolverPool); } } else { LOG.warn("No gateway IP address found for external network {}", externalNetwork); } } }else{ LOG.warn("Neutron network not found for router interface {}", gatewayPort); } } /** * Return String that represents OF port with marker explicitly provided (reverse of MatchUtils:parseExplicitOFPort) * * @param ofPort the OF port number * @return the string with encoded OF port (example format "OFPort|999") */ public static String encodeExcplicitOFPort(Long ofPort) { return "OFPort|" + ofPort.toString(); } @Override public void setDependencies(ServiceReference serviceReference) { eventDispatcher = (EventDispatcher) ServiceHelper.getGlobalInstance(EventDispatcher.class, this); eventDispatcher.eventHandlerAdded(serviceReference, this); tenantNetworkManager = (TenantNetworkManager) ServiceHelper.getGlobalInstance(TenantNetworkManager.class, this); configurationService = (ConfigurationService) ServiceHelper.getGlobalInstance(ConfigurationService.class, this); arpProvider = (ArpProvider) ServiceHelper.getGlobalInstance(ArpProvider.class, this); inboundNatProvider = (InboundNatProvider) ServiceHelper.getGlobalInstance(InboundNatProvider.class, this); outboundNatProvider = (OutboundNatProvider) ServiceHelper.getGlobalInstance(OutboundNatProvider.class, this); routingProvider = (RoutingProvider) ServiceHelper.getGlobalInstance(RoutingProvider.class, this); l3ForwardingProvider = (L3ForwardingProvider) ServiceHelper.getGlobalInstance(L3ForwardingProvider.class, this); nodeCacheManager = (NodeCacheManager) ServiceHelper.getGlobalInstance(NodeCacheManager.class, this); southbound = (Southbound) ServiceHelper.getGlobalInstance(Southbound.class, this); gatewayMacResolver = (GatewayMacResolver) ServiceHelper.getGlobalInstance(GatewayMacResolver.class, this); securityServicesManager = (SecurityServicesManager) ServiceHelper.getGlobalInstance(SecurityServicesManager.class, this); initL3AdapterMembers(); } @Override public void setDependencies(Object impl) { if (impl instanceof INeutronNetworkCRUD) { neutronNetworkCache = (INeutronNetworkCRUD)impl; } else if (impl instanceof INeutronPortCRUD) { neutronPortCache = (INeutronPortCRUD)impl; } else if (impl instanceof INeutronSubnetCRUD) { neutronSubnetCache = (INeutronSubnetCRUD)impl; } else if (impl instanceof INeutronFloatingIPCRUD) { neutronFloatingIpCache = (INeutronFloatingIPCRUD)impl; } else if (impl instanceof ArpProvider) { arpProvider = (ArpProvider)impl; } else if (impl instanceof InboundNatProvider) { inboundNatProvider = (InboundNatProvider)impl; } else if (impl instanceof OutboundNatProvider) { outboundNatProvider = (OutboundNatProvider)impl; } else if (impl instanceof RoutingProvider) { routingProvider = (RoutingProvider)impl; } else if (impl instanceof L3ForwardingProvider) { l3ForwardingProvider = (L3ForwardingProvider)impl; }else if (impl instanceof GatewayMacResolver) { gatewayMacResolver = (GatewayMacResolver)impl; } populateL3ForwardingCaches(); } }
package org.spoofax.interpreter.library.index; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.spoofax.interpreter.library.IOAgent; import org.spoofax.interpreter.terms.IStrategoAppl; import org.spoofax.interpreter.terms.IStrategoConstructor; import org.spoofax.interpreter.terms.IStrategoList; import org.spoofax.interpreter.terms.IStrategoTerm; import org.spoofax.interpreter.terms.ITermFactory; import com.google.common.collect.ArrayListMultimap; import com.google.common.collect.LinkedHashMultimap; import com.google.common.collect.Multimap; public class Index implements IIndex { public static final boolean DEBUG_ENABLED = Index.class.desiredAssertionStatus(); private static final int EXPECTED_DISTINCT_PARTITIONS = 100; private static final int EXPECTED_VALUES_PER_PARTITION = 1000; private final ConcurrentHashMap<IndexURI, Multimap<IndexPartitionDescriptor, IndexEntry>> entries = new ConcurrentHashMap<IndexURI, Multimap<IndexPartitionDescriptor, IndexEntry>>(); private final ConcurrentHashMap<IndexURI, Multimap<IndexPartitionDescriptor, IndexEntry>> childs = new ConcurrentHashMap<IndexURI, Multimap<IndexPartitionDescriptor, IndexEntry>>(); private final Multimap<IndexPartitionDescriptor, IndexEntry> entriesPerPartitionDescriptor = LinkedHashMultimap .create(); private final Map<IndexPartitionDescriptor, IndexPartition> partitions = new HashMap<IndexPartitionDescriptor, IndexPartition>(); private IOAgent agent; private ITermFactory termFactory; private IndexEntryFactory factory; public void initialize(ITermFactory factory, IOAgent agent) { this.agent = agent; this.factory = new IndexEntryFactory(factory); this.termFactory = factory; } private void ensureInitialized() { if(factory == null) throw new IllegalStateException("Index not initialized"); } public IndexEntryFactory getFactory() { return factory; } private Multimap<IndexPartitionDescriptor, IndexEntry> innerEntries(IndexURI uri) { Multimap<IndexPartitionDescriptor, IndexEntry> innerMap = ArrayListMultimap.create(EXPECTED_DISTINCT_PARTITIONS, EXPECTED_VALUES_PER_PARTITION); Multimap<IndexPartitionDescriptor, IndexEntry> ret = entries.putIfAbsent(uri, innerMap); if(ret == null) ret = innerMap; return ret; } private Multimap<IndexPartitionDescriptor, IndexEntry> innerChildEntries(IndexURI uri) { Multimap<IndexPartitionDescriptor, IndexEntry> innerMap = ArrayListMultimap.create(EXPECTED_DISTINCT_PARTITIONS, EXPECTED_VALUES_PER_PARTITION); Multimap<IndexPartitionDescriptor, IndexEntry> ret = childs.putIfAbsent(uri, innerMap); if(ret == null) ret = innerMap; return ret; } public void add(IStrategoAppl entry, IndexPartitionDescriptor partitionDescriptor) { ensureInitialized(); IStrategoConstructor constructor = entry.getConstructor(); IStrategoTerm type = factory.getEntryType(entry); IStrategoTerm identifier = factory.getEntryIdentifier(entry); IStrategoTerm value = factory.getEntryValue(entry); IndexEntry newEntry = factory.createEntry(constructor, identifier, type, value, partitionDescriptor); add(newEntry); } public void add(IndexEntry entry) { final IndexPartitionDescriptor partition = entry.getPartition(); final IndexURI uri = entry.getKey(); addOrGetPartition(partition); innerEntries(uri).put(partition, entry); // Add entry to children. IndexURI parent = uri.getParent(termFactory); if(parent != null) innerChildEntries(parent).put(partition, entry); // Add entry to partitions. entriesPerPartitionDescriptor.put(partition, entry); } public void addAll(IStrategoList entries, IndexPartitionDescriptor partitionDescriptor) { while(!entries.isEmpty()) { add((IStrategoAppl) entries.head(), partitionDescriptor); entries = entries.tail(); } } public Collection<IndexEntry> remove(IStrategoAppl template, IndexPartitionDescriptor partitionDescriptor) { IndexURI uri = factory.createURIFromTemplate(template); IndexURI parentURI = uri.getParent(termFactory); // TODO: Should this use innerEntries()/innerChildEntries()? Multimap<IndexPartitionDescriptor, IndexEntry> entryValues = entries.get(uri); Multimap<IndexPartitionDescriptor, IndexEntry> childValues = null; if(parentURI != null) childValues = childs.get(parentURI); Collection<IndexEntry> removedEntries = entryValues.removeAll(partitionDescriptor); for(IndexEntry entry : removedEntries) { if(parentURI != null) childValues.remove(partitionDescriptor, entry); entriesPerPartitionDescriptor.remove(partitionDescriptor, entry); } return removedEntries; } public Collection<IndexEntry> removeAll(IStrategoAppl template) { IndexURI uri = factory.createURIFromTemplate(template); IndexURI parentURI = uri.getParent(termFactory); Multimap<IndexPartitionDescriptor, IndexEntry> entryValues = innerEntries(uri); Multimap<IndexPartitionDescriptor, IndexEntry> childValues = null; if(parentURI != null) childValues = innerChildEntries(uri.getParent(termFactory)); Collection<IndexEntry> removedEntries = entryValues.values(); entries.remove(uri); for(IndexEntry entry : removedEntries) { if(parentURI != null) childValues.remove(entry.getPartition(), entry); entriesPerPartitionDescriptor.remove(entry.getPartition(), entry); } return removedEntries; } public IIndexEntryIterable get(IStrategoAppl template) { IndexURI uri = factory.createURIFromTemplate(template); return getEntryIterable(innerEntries(uri).values()); } public IIndexEntryIterable getChildren(IStrategoAppl template) { IndexURI uri = factory.createURIFromTemplate(template); return getEntryIterable(innerChildEntries(uri).values()); } public IIndexEntryIterable getInPartition(IndexPartitionDescriptor partitionDescriptor) { return getEntryIterable(entriesPerPartitionDescriptor.get(partitionDescriptor)); } public Collection<IndexPartitionDescriptor> getPartitionsOf(IStrategoAppl template) { IndexURI uri = factory.createURIFromTemplate(template); return getCollection(innerEntries(uri).keySet()); } public IIndexEntryIterable getAll() { List<IndexEntry> allEntries = new LinkedList<IndexEntry>(); Collection<Multimap<IndexPartitionDescriptor, IndexEntry>> values = entries.values(); for(Multimap<IndexPartitionDescriptor, IndexEntry> map : values) allEntries.addAll(map.values()); return getEntryIterable(allEntries); } public IndexPartition getPartition(IndexPartitionDescriptor partitionDescriptor) { return addOrGetPartition(partitionDescriptor); } private IndexPartition addOrGetPartition(IndexPartitionDescriptor partitionDescriptor) { IndexPartition partition = partitions.get(partitionDescriptor); if(partition == null) { partition = new IndexPartition(partitionDescriptor, null); partitions.put(partitionDescriptor, partition); } return partition; } public IndexPartitionDescriptor getPartitionDescriptor(IStrategoTerm partitionTerm) { return IndexPartitionDescriptor.fromTerm(agent, partitionTerm); } public void clearPartition(IStrategoTerm partitionTerm) { clearPartitionInternal(getPartitionDescriptor(partitionTerm)); } public void clearPartition(IndexPartitionDescriptor partitionDescriptor) { clearPartitionInternal(partitionDescriptor); } private void clearPartitionInternal(IndexPartitionDescriptor partitionDescriptor) { assert partitionDescriptor.getPartition() != null || partitionDescriptor.getURI() != null; Collection<Multimap<IndexPartitionDescriptor, IndexEntry>> entryValues = entries.values(); for(Multimap<IndexPartitionDescriptor, IndexEntry> map : entryValues) map.removeAll(partitionDescriptor); Collection<Multimap<IndexPartitionDescriptor, IndexEntry>> childValues = childs.values(); for(Multimap<IndexPartitionDescriptor, IndexEntry> map : childValues) map.removeAll(partitionDescriptor); entriesPerPartitionDescriptor.removeAll(partitionDescriptor); assert !getInPartition(partitionDescriptor).iterator().hasNext(); } public Collection<IndexPartition> getAllPartitions() { return getCollection(partitions.values()); } public Collection<IndexPartitionDescriptor> getAllPartitionDescriptors() { return getCollection(partitions.keySet()); } public void clearAll() { entries.clear(); childs.clear(); entriesPerPartitionDescriptor.clear(); partitions.clear(); } private static final IIndexEntryIterable getEntryIterable(Collection<IndexEntry> collection) { return new IndexEntryIterable(collection, null); } /** * Returns an unmodifiable collection if in debug mode, or the collection if not. */ private static final <T> Collection<T> getCollection(Collection<T> collection) { if(DEBUG_ENABLED) { return Collections.unmodifiableCollection(collection); } else { return collection; } } }
package org.pieShare.pieShareServer.services; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.pieShare.pieShareServer.services.api.IIncomeTask; import org.pieShare.pieShareServer.services.api.ISocketListener; import org.pieShare.pieTools.pieUtilities.service.beanService.IBeanService; import org.pieShare.pieTools.pieUtilities.service.pieLogger.PieLogger; /** * * @author Richard */ public class SocketListener implements ISocketListener { private int port; private IBeanService beanService; private final ExecutorService executor; public SocketListener() { executor = Executors.newCachedThreadPool(); } public void setBeanService(IBeanService beanService) { this.beanService = beanService; } @Override public void run() { port = 6312; PieLogger.info(this.getClass(), "Listener Running"); ServerSocket server; try { server = new ServerSocket(port); while (true) { Socket sock = server.accept(); IIncomeTask task = beanService.getBean(IncomeTask.class); task.setSocket(sock); executor.execute(task); } } catch (IOException ex) { PieLogger.info(this.getClass(), "Listener Error", ex); } } }
package net.ontrack.backend; import net.ontrack.core.model.*; import net.ontrack.service.ExportService; import net.ontrack.service.ManagementService; import org.codehaus.jackson.map.ObjectMapper; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import java.util.Collections; import java.util.List; import java.util.concurrent.Callable; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; public class ExportServiceTest extends AbstractBackendTest { private final Logger logger = LoggerFactory.getLogger(ExportServiceTest.class); @Autowired private ObjectMapper objectMapper; @Autowired private ManagementService managementService; @Autowired private ExportService exportService; /** * This test aims to check the consistency of the export-import-export chain. * <p/> * <ol> * <li>A complete project structure is created</li> * <li>The project is export as JSON - file 1</li> * <li>The project is deleted</li> * <li>The project is re-imported from file 1</li> * <li>The re-imported project is exported as file 2</li> * <li>File 1 & 2 must be identical but for the ID attribute (which are generated at import time)</li> * </ol> */ @Test(timeout = 2000L) public void create_export_delete_import_export() throws Exception { // Creates the project structure final ProjectSummary project = asAdmin().call(new Callable<ProjectSummary>() { @Override public ProjectSummary call() throws Exception { ProjectSummary project = managementService.createProject(new ProjectCreationForm(uid("PRJ"), "Export")); // Branches BranchSummary b1 = managementService.createBranch(project.getId(), new BranchCreationForm("B1", "B1")); BranchSummary b2 = managementService.createBranch(project.getId(), new BranchCreationForm("B2", "B2")); // Promotion levels PromotionLevelSummary b1dev = managementService.createPromotionLevel(b1.getId(), new PromotionLevelCreationForm("DEV", "Development")); PromotionLevelSummary b1prod = managementService.createPromotionLevel(b1.getId(), new PromotionLevelCreationForm("PROD", "Production")); PromotionLevelSummary b2dev = managementService.createPromotionLevel(b2.getId(), new PromotionLevelCreationForm("DEV", "Development")); PromotionLevelSummary b2prod = managementService.createPromotionLevel(b2.getId(), new PromotionLevelCreationForm("PROD", "Production")); // TODO Validation stamps // TODO Builds // TODO Promoted runs // TODO Validation runs // TODO Validation run statuses // TODO Comments // TODO Properties // TODO Build clean-up policy return project; } }); // Export final ExportData exportData = exportProject(project.getId()); // Checks assertNotNull(exportData); // Deletes the created file asAdmin().call(new Callable<Object>() { @Override public Object call() throws Exception { managementService.deleteProject(project.getId()); return null; } }); // Imports the project List<ProjectSummary> projects = asAdmin().call(new Callable<List<ProjectSummary>>() { @Override public List<ProjectSummary> call() throws Exception { // TODO Imports the file // String uuid = exportService.importLaunch(); // TODO Waits until the import is done /** while (!exportService.importCheck(uuid).isSuccess()) { logger.debug("Waiting for the import of the file"); Thread.sleep(100); } */ // TODO Gets the results // return exportService.importResults(uuid); return null; } }); assertNotNull(projects); assertEquals(1, projects.size()); ProjectSummary importedProject = projects.get(0); assertNotNull(importedProject); assertEquals(project.getName(), importedProject.getName()); // Exports the imported project ExportData exportImportedData = exportProject(importedProject.getId()); // TODO Compares files 1 & 2 // TODO Compares the JSON trees without taking into account the IDs and the order of fields } private ExportData exportProject(final int projectId) throws Exception { return asAdmin().call(new Callable<ExportData>() { @Override public ExportData call() throws Exception { // Exports the project String uuid = exportService.exportLaunch(Collections.singletonList(projectId)); // Waits until the export is done while (!exportService.exportCheck(uuid).isSuccess()) { logger.debug("Waiting for the generation of the export file"); Thread.sleep(100); } // Downloads the file return exportService.exportDownload(uuid); } }); } }
package org.elasticsearch.xpack.monitoring.exporter.http; import org.apache.http.HttpEntity; import org.apache.http.entity.ByteArrayEntity; import org.apache.http.entity.ContentType; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.message.ParameterizedMessage; import org.apache.logging.log4j.util.Supplier; import org.apache.lucene.util.BytesRef; import org.elasticsearch.action.ActionListener; import org.elasticsearch.client.Response; import org.elasticsearch.client.ResponseListener; import org.elasticsearch.client.RestClient; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.common.logging.Loggers; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.common.xcontent.XContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.xpack.core.monitoring.exporter.MonitoringDoc; import org.elasticsearch.xpack.core.monitoring.exporter.MonitoringTemplateUtils; import org.elasticsearch.xpack.monitoring.exporter.ExportBulk; import org.elasticsearch.xpack.monitoring.exporter.ExportException; import org.joda.time.format.DateTimeFormatter; import java.io.IOException; import java.util.Collection; import java.util.Map; /** * {@code HttpExportBulk} uses the {@link RestClient} to perform a bulk operation against the remote cluster. */ class HttpExportBulk extends ExportBulk { private static final Logger logger = Loggers.getLogger(HttpExportBulk.class); /** * The {@link RestClient} managed by the {@link HttpExporter}. */ private final RestClient client; /** * The querystring parameters to pass along with every bulk request. */ private final Map<String, String> params; /** * {@link DateTimeFormatter} used to resolve timestamped index name. */ private final DateTimeFormatter formatter; /** * The bytes payload that represents the bulk body is created via {@link #doAdd(Collection)}. */ private byte[] payload = null; HttpExportBulk(final String name, final RestClient client, final Map<String, String> parameters, final DateTimeFormatter dateTimeFormatter, final ThreadContext threadContext) { super(name, threadContext); this.client = client; this.params = parameters; this.formatter = dateTimeFormatter; } @Override public void doAdd(Collection<MonitoringDoc> docs) throws ExportException { try { if (docs != null && docs.isEmpty() == false) { try (BytesStreamOutput payload = new BytesStreamOutput()) { for (MonitoringDoc monitoringDoc : docs) { // any failure caused by an individual doc will be written as an empty byte[], thus not impacting the rest payload.write(toBulkBytes(monitoringDoc)); } // store the payload until we flush this.payload = BytesReference.toBytes(payload.bytes()); } } } catch (Exception e) { throw new ExportException("failed to add documents to export bulk [{}]", e, name); } } @Override public void doFlush(ActionListener<Void> listener) throws ExportException { if (payload == null) { listener.onFailure(new ExportException("unable to send documents because none were loaded for export bulk [{}]", name)); } else if (payload.length != 0) { final HttpEntity body = new ByteArrayEntity(payload, ContentType.APPLICATION_JSON); // free the memory payload = null; client.performRequestAsync("POST", "/_bulk", params, body, new ResponseListener() { @Override public void onSuccess(Response response) { try { HttpExportBulkResponseListener.INSTANCE.onSuccess(response); } finally { listener.onResponse(null); } } @Override public void onFailure(Exception exception) { try { HttpExportBulkResponseListener.INSTANCE.onFailure(exception); } finally { listener.onFailure(exception); } } }); } } @Override protected void doClose(ActionListener<Void> listener) { // nothing serious to do at this stage assert payload == null; listener.onResponse(null); } private byte[] toBulkBytes(final MonitoringDoc doc) throws IOException { final XContentType xContentType = XContentType.JSON; final XContent xContent = xContentType.xContent(); final String index = MonitoringTemplateUtils.indexName(formatter, doc.getSystem(), doc.getTimestamp()); final String id = doc.getId(); try (BytesStreamOutput out = new BytesStreamOutput()) { try (XContentBuilder builder = new XContentBuilder(xContent, out)) { // Builds the bulk action metadata line builder.startObject(); { builder.startObject("index"); { builder.field("_index", index); builder.field("_type", "doc"); if (id != null) { builder.field("_id", id); } } builder.endObject(); } builder.endObject(); } // Adds action metadata line bulk separator out.write(xContent.streamSeparator()); // Adds the source of the monitoring document final BytesRef source = XContentHelper.toXContent(doc, xContentType, false).toBytesRef(); out.write(source.bytes, source.offset, source.length); // Adds final bulk separator out.write(xContent.streamSeparator()); logger.trace("added index request [index={}, type={}, id={}]", index, doc.getType(), id); return BytesReference.toBytes(out.bytes()); } catch (Exception e) { logger.warn((Supplier<?>) () -> new ParameterizedMessage("failed to render document [{}], skipping it [{}]", doc, name), e); return BytesRef.EMPTY_BYTES; } } }
package org.elasticsearch.xpack.watcher.transform.search; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.message.ParameterizedMessage; import org.apache.logging.log4j.util.Supplier; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.client.Client; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.script.Script; import org.elasticsearch.xpack.watcher.execution.WatchExecutionContext; import org.elasticsearch.xpack.watcher.support.search.WatcherSearchTemplateRequest; import org.elasticsearch.xpack.watcher.support.search.WatcherSearchTemplateService; import org.elasticsearch.xpack.watcher.transform.ExecutableTransform; import org.elasticsearch.xpack.watcher.watch.Payload; import java.util.concurrent.TimeUnit; import static org.elasticsearch.xpack.ClientHelper.WATCHER_ORIGIN; import static org.elasticsearch.xpack.ClientHelper.stashWithOrigin; import static org.elasticsearch.xpack.watcher.transform.search.SearchTransform.TYPE; public class ExecutableSearchTransform extends ExecutableTransform<SearchTransform, SearchTransform.Result> { public static final SearchType DEFAULT_SEARCH_TYPE = SearchType.QUERY_THEN_FETCH; protected final Client client; protected final WatcherSearchTemplateService searchTemplateService; protected final TimeValue timeout; public ExecutableSearchTransform(SearchTransform transform, Logger logger, Client client, WatcherSearchTemplateService searchTemplateService, TimeValue defaultTimeout) { super(transform, logger); this.client = client; this.searchTemplateService = searchTemplateService; this.timeout = transform.getTimeout() != null ? transform.getTimeout() : defaultTimeout; } @Override public SearchTransform.Result execute(WatchExecutionContext ctx, Payload payload) { WatcherSearchTemplateRequest request = null; try { Script template = transform.getRequest().getOrCreateTemplate(); String renderedTemplate = searchTemplateService.renderTemplate(template, ctx, payload); // We need to make a copy, so that we don't modify the original instance that we keep around in a watch: request = new WatcherSearchTemplateRequest(transform.getRequest(), new BytesArray(renderedTemplate)); try (ThreadContext.StoredContext ignore = stashWithOrigin(client.threadPool().getThreadContext(), WATCHER_ORIGIN)) { SearchResponse resp = client.search(searchTemplateService.toSearchRequest(request)) .get(timeout.millis(), TimeUnit.MILLISECONDS); return new SearchTransform.Result(request, new Payload.XContent(resp)); } } catch (Exception e) { logger.error((Supplier<?>) () -> new ParameterizedMessage("failed to execute [{}] transform for [{}]", TYPE, ctx.id()), e); return new SearchTransform.Result(request, e); } } }
package org.opennms.dashboard.client; import com.google.gwt.core.client.EntryPoint; import com.google.gwt.core.client.GWT; import com.google.gwt.user.client.rpc.ServiceDefTarget; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.ClickListener; import com.google.gwt.user.client.ui.DialogBox; import com.google.gwt.user.client.ui.HTMLPanel; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.SimplePanel; import com.google.gwt.user.client.ui.VerticalPanel; import com.google.gwt.user.client.ui.Widget; public class Dashboard implements EntryPoint, ErrorHandler { Dashlet m_surveillance; AlarmDashlet m_alarms; OutageDashlet m_outages; NodeStatusDashlet m_nodeStatus; NotificationDashlet m_notifications; GraphDashlet m_graphs; private SurveillanceServiceAsync m_surveillanceService; public void onModuleLoad() { add(createSurveillanceDashlet(), "surveillanceView"); add(createAlarmDashlet(), "alarms"); add(createGraphDashlet(), "graphs"); add(createNotificationDashlet(), "notifications"); //add(createOutageDashlet(), "outages"); add(createNodeStatusDashlet(), "nodeStatus"); setSurveillanceSet(SurveillanceSet.DEFAULT); } private GraphDashlet createGraphDashlet() { m_graphs = new GraphDashlet(this); m_graphs.setSurveillanceService(getSurveillanceService()); return m_graphs; } private NotificationDashlet createNotificationDashlet() { m_notifications = new NotificationDashlet(this); m_notifications.setSurveillanceService(getSurveillanceService()); return m_notifications; } private OutageDashlet createOutageDashlet() { m_outages = new OutageDashlet(this); return m_outages; } private AlarmDashlet createAlarmDashlet() { m_alarms = new AlarmDashlet(this); m_alarms.setSurveillanceService(getSurveillanceService()); m_alarms.setSurveillanceSet(SurveillanceSet.DEFAULT); return m_alarms; } private Dashlet createSurveillanceDashlet() { SurveillanceDashlet surveillance = new SurveillanceDashlet(this); SurveillanceListener listener = new SurveillanceListener() { public void onAllClicked(Dashlet viewer) { setSurveillanceSet(SurveillanceSet.DEFAULT); } public void onIntersectionClicked(Dashlet viewer, SurveillanceIntersection intersection) { setSurveillanceSet(intersection); } public void onSurveillanceGroupClicked(Dashlet viewer, SurveillanceGroup group) { setSurveillanceSet(group); } }; surveillance.addSurveillanceViewListener(listener); final SurveillanceServiceAsync svc = getSurveillanceService(); surveillance.setSurveillanceService(svc); m_surveillance = surveillance; return m_surveillance; } private SurveillanceServiceAsync getSurveillanceService() { if (m_surveillanceService == null) { String serviceEntryPoint = GWT.getModuleBaseURL()+"surveillanceService.gwt"; // define the service you want to call final SurveillanceServiceAsync svc = (SurveillanceServiceAsync) GWT.create(SurveillanceService.class); ServiceDefTarget endpoint = (ServiceDefTarget) svc; endpoint.setServiceEntryPoint(serviceEntryPoint); m_surveillanceService = svc; } return m_surveillanceService; } private NodeStatusDashlet createNodeStatusDashlet() { m_nodeStatus = new NodeStatusDashlet(this); m_nodeStatus.setSurveillanceService(getSurveillanceService()); m_nodeStatus.setSurveillanceSet(SurveillanceSet.DEFAULT); return m_nodeStatus; } public void add(Widget widget, String elementId) { RootPanel panel = RootPanel.get(elementId); if (panel == null) { throw new IllegalArgumentException("element with id '"+elementId+"' not found!"); } panel.add(widget); } public void error(Throwable e) { error(e.toString()); } public void error(String err) { final DialogBox dialog = new DialogBox(); dialog.setText("Error Occurred"); VerticalPanel panel = new VerticalPanel(); HTMLPanel html = new HTMLPanel(err); html.setStyleName("Message"); panel.add(html); Button ok = new Button("OK"); SimplePanel buttonPanel = new SimplePanel(); buttonPanel.setWidget(ok); buttonPanel.setStyleName("Button"); panel.add(buttonPanel); dialog.setWidget(panel); ok.addClickListener(new ClickListener() { public void onClick(Widget arg0) { dialog.hide(); } }); dialog.show(); } private void setSurveillanceSet(SurveillanceSet set) { m_surveillance.setSurveillanceSet(set); m_alarms.setSurveillanceSet(set); m_graphs.setSurveillanceSet(set); m_notifications.setSurveillanceSet(set); m_nodeStatus.setSurveillanceSet(set); } }
package com.python.pydev.refactoring.hyperlink; import org.eclipse.core.runtime.Assert; import org.eclipse.jface.action.IAction; import org.eclipse.jface.text.IRegion; import org.eclipse.jface.text.hyperlink.IHyperlink; import org.python.pydev.editor.PyEdit; import com.python.pydev.refactoring.actions.PyGoToDefinition; /** * Hiperlink will try to open the current selected word. * * @author Fabio */ public class PythonHyperlink implements IHyperlink { private final IRegion fRegion; private PyEdit fEditor; public PythonHyperlink(IRegion region, PyEdit editor) { Assert.isNotNull(region); fRegion = region; fEditor = editor; } @Override public IRegion getHyperlinkRegion() { return fRegion; } @Override public String getHyperlinkText() { return "Go To Definition"; } @Override public String getTypeLabel() { return null; } /** * Try to find a definition and open it. */ @Override public void open() { PyGoToDefinition pyGoToDefinition = new PyGoToDefinition(); pyGoToDefinition.setEditor(this.fEditor); pyGoToDefinition.run((IAction) null); } }
package org.opennms.web.rest; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.SecurityContext; import javax.ws.rs.core.UriInfo; import org.opennms.netmgt.dao.OutageDao; import org.opennms.netmgt.model.OnmsCriteria; import org.opennms.netmgt.model.OnmsOutage; import org.opennms.netmgt.model.OnmsOutageCollection; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import com.sun.jersey.spi.resource.PerRequest; @Component @PerRequest @Scope("prototype") @Path("outages") public class OutageRestService extends OnmsRestService { @Autowired private OutageDao m_outageDao; @Context UriInfo m_uriInfo; @Context SecurityContext m_securityContext; @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Path("{outageId}") @Transactional public OnmsOutage getOutage(@PathParam("outageId") String outageId) { OnmsOutage result= m_outageDao.get(Integer.valueOf(outageId)); return result; } @GET @Produces("text/plain") @Path("count") @Transactional public String getCount() { return Integer.toString(m_outageDao.countAll()); } @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) @Transactional public OnmsOutageCollection getOutages() { MultivaluedMap<java.lang.String,java.lang.String> params=m_uriInfo.getQueryParameters(); OnmsCriteria criteria=new OnmsCriteria(OnmsOutage.class); setLimitOffset(params, criteria); addFiltersToCriteria(params, criteria, OnmsOutage.class); return new OnmsOutageCollection(m_outageDao.findMatching(criteria)); } }
package uk.ac.cam.ch.wwmm.opsin; 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.Set; import java.util.Stack; import java.util.regex.Matcher; import java.util.regex.Pattern; import static uk.ac.cam.ch.wwmm.opsin.XmlDeclarations.*; import static uk.ac.cam.ch.wwmm.opsin.OpsinTools.*; import nu.xom.Attribute; import nu.xom.Element; import nu.xom.Elements; import nu.xom.Node; /**Performs structure-aware destructive procedural parsing on parser results. * * @author dl387 * */ class ComponentProcessor { private final static Pattern matchAddedHydrogenBracket =Pattern.compile("[\\[\\(\\{]([^\\[\\(\\{]*)H[\\]\\)\\}]"); private final static Pattern matchElementSymbolOrAminoAcidLocant = Pattern.compile("[A-Z][a-z]?'*(\\d+[a-z]?'*)?"); private final static Pattern matchChalcogenReplacement= Pattern.compile("thio|seleno|telluro"); private final static Pattern matchInlineSuffixesThatAreAlsoGroups = Pattern.compile("carbon|oxy|sulfen|sulfin|sulfon|selenen|selenin|selenon|telluren|tellurin|telluron"); private final static String[] traditionalAlkanePositionNames =new String[]{"alpha", "beta", "gamma", "delta", "epsilon", "zeta"}; private final SuffixRules suffixRules; private final BuildState state; private final Element parse; //rings that look like HW rings but have other meanings. For the HW like inorganics the true meaning is given private static final HashMap<String, String[]> specialHWRings = new HashMap<String, String[]>(); static{ //The first entry of the array is a special instruction e.g. blocked or saturated. The correct order of the heteroatoms follows //terminal e is ignored from all of the keys as it is optional in the input name specialHWRings.put("oxin", new String[]{"blocked"}); specialHWRings.put("azin", new String[]{"blocked"}); specialHWRings.put("selenin", new String[]{"not_icacid", "Se","C","C","C","C","C"}); specialHWRings.put("tellurin", new String[]{"not_icacid", "Te","C","C","C","C","C"}); specialHWRings.put("thiol", new String[]{"not_nothingOrOlate", "S","C","C","C","C"}); specialHWRings.put("selenol", new String[]{"not_nothingOrOlate", "Se","C","C","C","C"}); specialHWRings.put("tellurol", new String[]{"not_nothingOrOlate", "Te","C","C","C","C"}); specialHWRings.put("oxazol", new String[]{"","O","C","N","C","C"}); specialHWRings.put("thiazol", new String[]{"","S","C","N","C","C"}); specialHWRings.put("selenazol", new String[]{"","Se","C","N","C","C"}); specialHWRings.put("tellurazol", new String[]{"","Te","C","N","C","C"}); specialHWRings.put("oxazolidin", new String[]{"","O","C","N","C","C"}); specialHWRings.put("thiazolidin", new String[]{"","S","C","N","C","C"}); specialHWRings.put("selenazolidin", new String[]{"","Se","C","N","C","C"}); specialHWRings.put("tellurazolidin", new String[]{"","Te","C","N","C","C"}); specialHWRings.put("oxazolid", new String[]{"","O","C","N","C","C"}); specialHWRings.put("thiazolid", new String[]{"","S","C","N","C","C"}); specialHWRings.put("selenazolid", new String[]{"","Se","C","N","C","C"}); specialHWRings.put("tellurazolid", new String[]{"","Te","C","N","C","C"}); specialHWRings.put("oxazolin", new String[]{"","O","C","N","C","C"}); specialHWRings.put("thiazolin", new String[]{"","S","C","N","C","C"}); specialHWRings.put("selenazolin", new String[]{"","Se","C","N","C","C"}); specialHWRings.put("tellurazolin", new String[]{"","Te","C","N","C","C"}); specialHWRings.put("oxoxolan", new String[]{"","O","C","O","C","C"}); specialHWRings.put("oxoxan", new String[]{"","O","C","C","O","C","C"}); specialHWRings.put("oxoxin", new String[]{"","O","C","C","O","C","C"}); specialHWRings.put("boroxin", new String[]{"saturated","O","B","O","B","O","B"}); specialHWRings.put("borazin", new String[]{"saturated","N","B","N","B","N","B"}); specialHWRings.put("borthiin", new String[]{"saturated","S","B","S","B","S","B"}); } public ComponentProcessor(SuffixRules suffixRules, BuildState state, Element parse) { this.suffixRules = suffixRules; this.state = state; this.parse = parse; } /** * Processes a parse result that has already gone through the ComponentGenerator. * At this stage one can expect all substituents/roots to have at least 1 group. * Multiple groups are present in, for example, fusion nomenclature. By the end of this function there will be exactly 1 group * associated with each substituent/root. Multiplicative nomenclature can result in there being multiple roots * @throws ComponentGenerationException * @throws StructureBuildingException */ void processParse() throws ComponentGenerationException, StructureBuildingException { List<Element> words =XOMTools.getDescendantElementsWithTagName(parse, WORD_EL); int wordCount =words.size(); for (int i = wordCount -1; i>=0; i Element word =words.get(i); String wordRule = OpsinTools.getParentWordRule(word).getAttributeValue(WORDRULE_EL); state.currentWordRule = WordRule.valueOf(wordRule); if (word.getAttributeValue(TYPE_ATR).equals(WordType.functionalTerm.toString())){ continue;//functionalTerms are handled on a case by case basis by wordRules } List<Element> roots = XOMTools.getDescendantElementsWithTagName(word, ROOT_EL); if (roots.size() >1){ throw new ComponentGenerationException("Multiple roots, but only 0 or 1 were expected. Found: " +roots.size()); } List<Element> substituents = XOMTools.getDescendantElementsWithTagName(word, SUBSTITUENT_EL); List<Element> substituentsAndRoot = OpsinTools.combineElementLists(substituents, roots); List<Element> brackets = XOMTools.getDescendantElementsWithTagName(word, BRACKET_EL); List<Element> substituentsAndRootAndBrackets =OpsinTools.combineElementLists(substituentsAndRoot, brackets); List<Element> groups = XOMTools.getDescendantElementsWithTagName(word, GROUP_EL); for (Element group : groups) { Fragment thisFrag = resolveGroup(state, group); processChargeAndOxidationNumberSpecification(group, thisFrag);//e.g. mercury(2+) or mercury(II) state.xmlFragmentMap.put(group, thisFrag); } for (Element subOrRoot : substituentsAndRoot) { applyDLPrefixes(subOrRoot); processCarbohydrates(subOrRoot);//e.g. glucopyranose (needs to be done before determineLocantMeaning to cope with alpha,beta for undefined anomer stereochemistry) } for (int j = substituents.size() -1; j >=0; j Element substituent = substituents.get(j); boolean removed = removeAndMoveToAppropriateGroupIfHydroSubstituent(substituent);//this REMOVES a substituent just containing hydro/perhydro elements and moves these elements in front of an appropriate ring if (!removed){ removed = removeAndMoveToAppropriateGroupIfSubtractivePrefix(substituent); } if (removed){ substituents.remove(j); substituentsAndRoot.remove(substituent); substituentsAndRootAndBrackets.remove(substituent); } } Element finalSubOrRootInWord =(Element) word.getChild(word.getChildElements().size()-1); while (!finalSubOrRootInWord.getLocalName().equals(ROOT_EL) && !finalSubOrRootInWord.getLocalName().equals(SUBSTITUENT_EL)){ List<Element> children = XOMTools.getChildElementsWithTagNames(finalSubOrRootInWord, new String[]{ROOT_EL, SUBSTITUENT_EL, BRACKET_EL}); if (children.size()==0){ throw new ComponentGenerationException("Unable to find finalSubOrRootInWord"); } finalSubOrRootInWord = children.get(children.size()-1); } for (Element subOrRootOrBracket : substituentsAndRootAndBrackets) { determineLocantMeaning(subOrRootOrBracket, finalSubOrRootInWord); } for (Element subOrRoot : substituentsAndRoot) { processMultipliers(subOrRoot); detectConjunctiveSuffixGroups(subOrRoot, groups); matchLocantsToDirectFeatures(subOrRoot); Elements groupsOfSubOrRoot = subOrRoot.getChildElements(GROUP_EL); Element lastGroupInSubOrRoot =groupsOfSubOrRoot.get(groupsOfSubOrRoot.size()-1); preliminaryProcessSuffixes(lastGroupInSubOrRoot, XOMTools.getChildElementsWithTagName(subOrRoot, SUFFIX_EL)); } FunctionalReplacement.processAcidReplacingFunctionalClassNomenclature(state, finalSubOrRootInWord, word); if (FunctionalReplacement.processPrefixFunctionalReplacementNomenclature(state, groups, substituents)){//true if functional replacement performed, 1 or more substituents will have been removed substituentsAndRoot = OpsinTools.combineElementLists(substituents, roots); substituentsAndRootAndBrackets =OpsinTools.combineElementLists(substituentsAndRoot, brackets); } handleGroupIrregularities(groups); for (Element subOrRoot : substituentsAndRoot) { processHW(subOrRoot);//hantzch-widman rings FusedRingBuilder.processFusedRings(state, subOrRoot); processFusedRingBridges(subOrRoot); assignElementSymbolLocants(subOrRoot); processRingAssemblies(subOrRoot); processPolyCyclicSpiroNomenclature(subOrRoot); } for (Element subOrRoot : substituentsAndRoot) { applyLambdaConvention(subOrRoot); handleMultiRadicals(subOrRoot); } //System.out.println(new XOMFormatter().elemToString(elem)); addImplicitBracketsToAminoAcids(groups, brackets); findAndStructureImplictBrackets(substituents, brackets); for (Element subOrRoot : substituentsAndRoot) { matchLocantsToIndirectFeatures(subOrRoot); assignImplicitLocantsToDiTerminalSuffixes(subOrRoot); processConjunctiveNomenclature(subOrRoot); resolveSuffixes(subOrRoot.getFirstChildElement(GROUP_EL), XOMTools.getChildElementsWithTagName(subOrRoot, SUFFIX_EL)); } moveErroneouslyPositionedLocantsAndMultipliers(brackets);//e.g. (tetramethyl)azanium == tetra(methyl)azanium List<Element> children = XOMTools.getChildElementsWithTagNames(word, new String[]{ROOT_EL, SUBSTITUENT_EL, BRACKET_EL}); while (children.size()==1){ children = XOMTools.getChildElementsWithTagNames(children.get(0), new String[]{ROOT_EL, SUBSTITUENT_EL, BRACKET_EL}); } if (children.size()>0){ assignLocantsToMultipliedRootIfPresent(children.get(children.size()-1));//multiplicative nomenclature e.g. methylenedibenzene or 3,4'-oxydipyridine } addImplicitBracketsInCaseWhereSubstituentHasTwoLocants(substituents, brackets); substituentsAndRootAndBrackets =OpsinTools.combineElementLists(substituentsAndRoot, brackets);//implicit brackets may have been created for (Element subBracketOrRoot : substituentsAndRootAndBrackets) { assignLocantsAndMultipliers(subBracketOrRoot); } processBiochemicalLinkageDescriptors(substituents, brackets); processWordLevelMultiplierIfApplicable(word, wordCount); } new WordRulesOmittedSpaceCorrector(state, parse).correctOmittedSpaces();//TODO where should this go? } /**Resolves the contents of a group element * * @param group The group element * @return The fragment specified by the group element. * @throws StructureBuildingException If the group can't be built. * @throws ComponentGenerationException */ static Fragment resolveGroup(BuildState state, Element group) throws StructureBuildingException, ComponentGenerationException { String groupType = group.getAttributeValue(TYPE_ATR); String groupSubType = group.getAttributeValue(SUBTYPE_ATR); String groupValue = group.getAttributeValue(VALUE_ATR); String groupValType = group.getAttributeValue(VALTYPE_ATR); Fragment thisFrag =null; if(groupValType.equals(SMILES_VALTYPE_VAL)) { if (group.getAttribute(LABELS_ATR)!=null){ thisFrag = state.fragManager.buildSMILES(groupValue, groupType, groupSubType, group.getAttributeValue(LABELS_ATR)); } else{ thisFrag = state.fragManager.buildSMILES(groupValue, groupType, groupSubType, ""); } } else{ throw new StructureBuildingException("Group tag has bad or missing valType: " + group.toXML()); } //processes groups like cymene and xylene whose structure is determined by the presence of a locant in front e.g. p-xylene processXyleneLikeNomenclature(state, group, thisFrag); setFragmentDefaultInAtomIfSpecified(thisFrag, group); setFragmentFunctionalAtomsIfSpecified(group, thisFrag); applyTraditionalAlkaneNumberingIfAppropriate(group, thisFrag); return thisFrag; } /** * Checks for groups with the addGroup/addBond/addHeteroAtom attributes. For the addGroup attribute adds the group defined by the SMILES described within * e.g. for xylene this function would add two methyls. Xylene is initially generated using the structure of benzene! * See tokenList dtd for more information on the syntax of these attributes if it is not clear from the code * @param state * @param group: The group element * @param parentFrag: The fragment that has been generated from the group element * @throws StructureBuildingException * @throws ComponentGenerationException */ private static void processXyleneLikeNomenclature(BuildState state, Element group, Fragment parentFrag) throws StructureBuildingException, ComponentGenerationException { if(group.getAttribute(ADDGROUP_ATR)!=null) { String addGroupInformation=group.getAttributeValue(ADDGROUP_ATR); String[] groupsToBeAdded = MATCH_SEMICOLON.split(addGroupInformation);//typically only one, but 2 in the case of xylene and quinones ArrayList<HashMap<String, String>> allGroupInformation = new ArrayList<HashMap<String, String>>(); for (String groupToBeAdded : groupsToBeAdded) {//populate allGroupInformation list String[] tempArray = MATCH_SPACE.split(groupToBeAdded); HashMap<String, String> groupInformation = new HashMap<String, String>(); if (tempArray.length != 2 && tempArray.length != 3) { throw new ComponentGenerationException("malformed addGroup tag"); } groupInformation.put("SMILES", tempArray[0]); if (tempArray[1].startsWith("id")) { groupInformation.put("atomReferenceType", "id"); groupInformation.put("atomReference", tempArray[1].substring(2)); } else if (tempArray[1].startsWith("locant")) { groupInformation.put("atomReferenceType", "locant"); groupInformation.put("atomReference", tempArray[1].substring(6)); } else { throw new ComponentGenerationException("malformed addGroup tag"); } if (tempArray.length == 3) {//labels may optionally be specified for the group to be added groupInformation.put("labels", tempArray[2]); } allGroupInformation.add(groupInformation); } Element previousEl =(Element) XOMTools.getPreviousSibling(group); if (previousEl !=null && previousEl.getLocalName().equals(LOCANT_EL)){//has the name got specified locants to override the default ones List<String> locantValues =StringTools.arrayToList(MATCH_COMMA.split(previousEl.getValue())); if ((locantValues.size()==groupsToBeAdded.length || locantValues.size() +1 ==groupsToBeAdded.length) && locantAreAcceptableForXyleneLikeNomenclatures(locantValues, group)){//one locant can be implicit in some cases boolean assignlocants =true; if (locantValues.size()!=groupsToBeAdded.length){ //check that the firstGroup by default will be added to the atom with locant 1. If this is not the case then as many locants as there were groups should of been specified //or no locants should have been specified, which is what will be assumed (i.e. the locants will be left unassigned) HashMap<String, String> groupInformation =allGroupInformation.get(0); String locant; if (groupInformation.get("atomReferenceType").equals("locant")){ locant =parentFrag.getAtomByLocantOrThrow(groupInformation.get("atomReference")).getFirstLocant(); } else if (groupInformation.get("atomReferenceType").equals("id") ){ locant =parentFrag.getAtomByIDOrThrow(parentFrag.getIdOfFirstAtom() + Integer.parseInt(groupInformation.get("atomReference")) -1 ).getFirstLocant(); } else{ throw new ComponentGenerationException("malformed addGroup tag"); } if (locant ==null || !locant.equals("1")){ assignlocants=false; } } if (assignlocants){ for (int i = groupsToBeAdded.length -1; i >=0 ; i //if less locants than expected are specified the locants of only the later groups will be changed //e.g. 4-xylene will transform 1,2-xylene to 1,4-xylene HashMap<String, String> groupInformation =allGroupInformation.get(i); if (locantValues.size() >0){ groupInformation.put("atomReferenceType", "locant"); groupInformation.put("atomReference", locantValues.get(locantValues.size()-1)); locantValues.remove(locantValues.size()-1); } else{ break; } } group.removeAttribute(group.getAttribute(FRONTLOCANTSEXPECTED_ATR)); previousEl.detach(); } } } for (int i = 0; i < groupsToBeAdded.length; i++) { HashMap<String, String> groupInformation =allGroupInformation.get(i); String smilesOfGroupToBeAdded = groupInformation.get("SMILES"); Fragment newFrag; if (groupInformation.get("labels")!=null){ newFrag = state.fragManager.buildSMILES(smilesOfGroupToBeAdded, parentFrag.getType(), parentFrag.getSubType(), groupInformation.get("labels")); } else{ newFrag = state.fragManager.buildSMILES(smilesOfGroupToBeAdded, parentFrag.getType(), parentFrag.getSubType(), NONE_LABELS_VAL); } Atom atomOnParentFrag =null; if (groupInformation.get("atomReferenceType").equals("locant")){ atomOnParentFrag=parentFrag.getAtomByLocantOrThrow(groupInformation.get("atomReference")); } else if (groupInformation.get("atomReferenceType").equals("id") ){ atomOnParentFrag= parentFrag.getAtomByIDOrThrow(parentFrag.getIdOfFirstAtom() + Integer.parseInt(groupInformation.get("atomReference")) -1); } else{ throw new ComponentGenerationException("malformed addGroup tag"); } if (newFrag.getOutAtomCount() >1){ throw new ComponentGenerationException("too many outAtoms on group to be added"); } if (newFrag.getOutAtomCount() ==1) { OutAtom newFragOutAtom = newFrag.getOutAtom(0); newFrag.removeOutAtom(newFragOutAtom); state.fragManager.incorporateFragment(newFrag, newFragOutAtom.getAtom(), parentFrag, atomOnParentFrag, newFragOutAtom.getValency()); } else{ Atom atomOnNewFrag = newFrag.getDefaultInAtom(); state.fragManager.incorporateFragment(newFrag, atomOnNewFrag, parentFrag, atomOnParentFrag, 1); } } } if(group.getAttributeValue(ADDHETEROATOM_ATR)!=null) { String addHeteroAtomInformation=group.getAttributeValue(ADDHETEROATOM_ATR); String[] heteroAtomsToBeAdded = MATCH_SEMICOLON.split(addHeteroAtomInformation); ArrayList<HashMap<String, String>> allHeteroAtomInformation = new ArrayList<HashMap<String, String>>(); for (String heteroAtomToBeAdded : heteroAtomsToBeAdded) {//populate allHeteroAtomInformation list String[] tempArray = MATCH_SPACE.split(heteroAtomToBeAdded); HashMap<String, String> heteroAtomInformation = new HashMap<String, String>(); if (tempArray.length != 2) { throw new ComponentGenerationException("malformed addHeteroAtom tag"); } heteroAtomInformation.put("SMILES", tempArray[0]); if (tempArray[1].startsWith("id")) { heteroAtomInformation.put("atomReferenceType", "id"); heteroAtomInformation.put("atomReference", tempArray[1].substring(2)); } else if (tempArray[1].startsWith("locant")) { heteroAtomInformation.put("atomReferenceType", "locant"); heteroAtomInformation.put("atomReference", tempArray[1].substring(6)); } else { throw new ComponentGenerationException("malformed addHeteroAtom tag"); } allHeteroAtomInformation.add(heteroAtomInformation); } Element previousEl =(Element) XOMTools.getPreviousSibling(group); if (previousEl !=null && previousEl.getLocalName().equals(LOCANT_EL)){//has the name got specified locants to override the default ones List<String> locantValues =StringTools.arrayToList(MATCH_COMMA.split(previousEl.getValue())); if (locantValues.size() ==heteroAtomsToBeAdded.length && locantAreAcceptableForXyleneLikeNomenclatures(locantValues, group)){ for (int i = heteroAtomsToBeAdded.length -1; i >=0 ; i--) {//all heteroatoms must have a locant or default locants will be used HashMap<String, String> groupInformation =allHeteroAtomInformation.get(i); groupInformation.put("atomReferenceType", "locant"); groupInformation.put("atomReference", locantValues.get(locantValues.size()-1)); locantValues.remove(locantValues.size()-1); } group.removeAttribute(group.getAttribute(FRONTLOCANTSEXPECTED_ATR)); previousEl.detach(); } } for (int i = 0; i < heteroAtomsToBeAdded.length; i++) { HashMap<String, String> heteroAtomInformation =allHeteroAtomInformation.get(i); Atom atomOnParentFrag =null; if (heteroAtomInformation.get("atomReferenceType").equals("locant")){ atomOnParentFrag=parentFrag.getAtomByLocantOrThrow(heteroAtomInformation.get("atomReference")); } else if (heteroAtomInformation.get("atomReferenceType").equals("id") ){ atomOnParentFrag= parentFrag.getAtomByIDOrThrow(parentFrag.getIdOfFirstAtom() + Integer.parseInt(heteroAtomInformation.get("atomReference")) -1); } else{ throw new ComponentGenerationException("malformed addHeteroAtom tag"); } state.fragManager.replaceAtomWithSmiles(atomOnParentFrag, heteroAtomInformation.get("SMILES")); } } if(group.getAttributeValue(ADDBOND_ATR)!=null && !HANTZSCHWIDMAN_SUBTYPE_VAL.equals(group.getAttributeValue(SUBTYPE_ATR))) {//HW add bond is handled later String addBondInformation=group.getAttributeValue(ADDBOND_ATR); String[] bondsToBeAdded = MATCH_SEMICOLON.split(addBondInformation); ArrayList<HashMap<String, String>> allBondInformation = new ArrayList<HashMap<String, String>>(); for (String bondToBeAdded : bondsToBeAdded) {//populate allBondInformation list String[] tempArray = MATCH_SPACE.split(bondToBeAdded); HashMap<String, String> bondInformation = new HashMap<String, String>(); if (tempArray.length != 2) { throw new ComponentGenerationException("malformed addBond tag"); } bondInformation.put("bondOrder", tempArray[0]); if (tempArray[1].startsWith("id")) { bondInformation.put("atomReferenceType", "id"); bondInformation.put("atomReference", tempArray[1].substring(2)); } else if (tempArray[1].startsWith("locant")) { bondInformation.put("atomReferenceType", "locant"); bondInformation.put("atomReference", tempArray[1].substring(6)); } else { throw new ComponentGenerationException("malformed addBond tag"); } allBondInformation.add(bondInformation); } boolean locanted = false; Element previousEl =(Element) XOMTools.getPreviousSibling(group); if (previousEl !=null && previousEl.getLocalName().equals(LOCANT_EL)){//has the name got specified locants to override the default ones List<String> locantValues =StringTools.arrayToList(MATCH_COMMA.split(previousEl.getValue())); if (locantValues.size() ==bondsToBeAdded.length && locantAreAcceptableForXyleneLikeNomenclatures(locantValues, group)){ for (int i = bondsToBeAdded.length -1; i >=0 ; i--) {//all bond order changes must have a locant or default locants will be used HashMap<String, String> bondInformation =allBondInformation.get(i); bondInformation.put("atomReferenceType", "locant"); bondInformation.put("atomReference", locantValues.get(locantValues.size()-1)); locantValues.remove(locantValues.size()-1); } group.removeAttribute(group.getAttribute(FRONTLOCANTSEXPECTED_ATR)); previousEl.detach(); locanted = true; } } for (int i = 0; i < bondsToBeAdded.length; i++) { HashMap<String, String> bondInformation =allBondInformation.get(i); Atom atomOnParentFrag =null; if (bondInformation.get("atomReferenceType").equals("locant")){ atomOnParentFrag=parentFrag.getAtomByLocantOrThrow(bondInformation.get("atomReference")); } else if (bondInformation.get("atomReferenceType").equals("id") ){ atomOnParentFrag= parentFrag.getAtomByIDOrThrow(parentFrag.getIdOfFirstAtom() + Integer.parseInt(bondInformation.get("atomReference")) -1); } else{ throw new ComponentGenerationException("malformed addBond tag"); } Bond b = FragmentTools.unsaturate(atomOnParentFrag, Integer.parseInt(bondInformation.get("bondOrder")) , parentFrag); if (!locanted && b.getOrder() ==2 && parentFrag.getAtomCount()==5 && b.getFromAtom().getAtomIsInACycle() && b.getToAtom().getAtomIsInACycle()){ //special case just that substitution of groups like imidazoline may actually remove the double bond... b.setOrder(1); b.getFromAtom().setSpareValency(true); b.getToAtom().setSpareValency(true); } } } } /** * Checks that all locants are present within the front locants expected attribute of the group * @param locantValues * @param group * @return */ private static boolean locantAreAcceptableForXyleneLikeNomenclatures(List<String> locantValues, Element group) { if (group.getAttribute(FRONTLOCANTSEXPECTED_ATR)==null){ throw new IllegalArgumentException("Group must have frontLocantsExpected to implement xylene-like nomenclature"); } List<String> allowedLocants = Arrays.asList(MATCH_COMMA.split(group.getAttributeValue(FRONTLOCANTSEXPECTED_ATR))); for (String locant : locantValues) { if (!allowedLocants.contains(locant)){ return false; } } return true; } /** * Looks for the presence of DEFAULTINLOCANT_ATR and DEFAULTINID_ATR on the group and applies them to the fragment * Also sets the default in atom for alkanes so that say methylethyl is prop-2-yl rather than propyl * @param thisFrag * @param group * @throws StructureBuildingException */ private static void setFragmentDefaultInAtomIfSpecified(Fragment thisFrag, Element group) throws StructureBuildingException { String groupSubType = group.getAttributeValue(SUBTYPE_ATR); if (group.getAttribute(DEFAULTINLOCANT_ATR)!=null){//sets the atom at which substitution will occur to by default thisFrag.setDefaultInAtom(thisFrag.getAtomByLocantOrThrow(group.getAttributeValue(DEFAULTINLOCANT_ATR))); } else if (group.getAttribute(DEFAULTINID_ATR)!=null){ thisFrag.setDefaultInAtom(thisFrag.getAtomByIDOrThrow(thisFrag.getIdOfFirstAtom() + Integer.parseInt(group.getAttributeValue(DEFAULTINID_ATR)) -1)); } else if ("yes".equals(group.getAttributeValue(USABLEASJOINER_ATR)) && group.getAttribute(SUFFIXAPPLIESTO_ATR)==null){//makes linkers by default attach end to end int chainLength =thisFrag.getChainLength(); if (chainLength >1){ boolean connectEndToEndWithPreviousSub =true; if (groupSubType.equals(ALKANESTEM_SUBTYPE_VAL)){//don't do this if the group is preceded by another alkaneStem e.g. methylethyl makes more sense as prop-2-yl rather than propyl Element previousSubstituent =(Element) XOMTools.getPreviousSibling(group.getParent()); if (previousSubstituent!=null){ Elements groups = previousSubstituent.getChildElements(GROUP_EL); if (groups.size()==1 && groups.get(0).getAttributeValue(SUBTYPE_ATR).equals(ALKANESTEM_SUBTYPE_VAL) && !groups.get(0).getAttributeValue(TYPE_ATR).equals(RING_TYPE_VAL)){ connectEndToEndWithPreviousSub = false; } } } if (connectEndToEndWithPreviousSub){ Element parent =(Element) group.getParent(); while (parent.getLocalName().equals(BRACKET_EL)){ parent = (Element) parent.getParent(); } if (parent.getLocalName().equals(ROOT_EL)){ Element previous = (Element) XOMTools.getPrevious(group); if (previous==null || !previous.getLocalName().equals(MULTIPLIER_EL)){ connectEndToEndWithPreviousSub=false; } } } if (connectEndToEndWithPreviousSub){ group.addAttribute(new Attribute(DEFAULTINID_ATR, Integer.toString(chainLength))); thisFrag.setDefaultInAtom(thisFrag.getAtomByLocantOrThrow(Integer.toString(chainLength))); } } } } /** * Looks for the presence of FUNCTIONALIDS_ATR on the group and applies them to the fragment * @param group * @param thisFrag * @throws StructureBuildingException */ private static void setFragmentFunctionalAtomsIfSpecified(Element group, Fragment thisFrag) throws StructureBuildingException { if (group.getAttribute(FUNCTIONALIDS_ATR)!=null){ String[] functionalIDs = MATCH_COMMA.split(group.getAttributeValue(FUNCTIONALIDS_ATR)); for (String functionalID : functionalIDs) { thisFrag.addFunctionalAtom(thisFrag.getAtomByIDOrThrow(thisFrag.getIdOfFirstAtom() + Integer.parseInt(functionalID) - 1)); } } } private static void applyTraditionalAlkaneNumberingIfAppropriate(Element group, Fragment thisFrag) { String groupType = group.getAttributeValue(TYPE_ATR); if (groupType.equals(ACIDSTEM_TYPE_VAL)){ List<Atom> atomList = thisFrag.getAtomList(); Atom startingAtom = thisFrag.getFirstAtom(); if (group.getAttribute(SUFFIXAPPLIESTO_ATR)!=null){ String suffixAppliesTo = group.getAttributeValue(SUFFIXAPPLIESTO_ATR); String suffixAppliesToArr[] = MATCH_COMMA.split(suffixAppliesTo); if (suffixAppliesToArr.length!=1){ return; } startingAtom = atomList.get(Integer.parseInt(suffixAppliesToArr[0])-1); } List<Atom> neighbours = startingAtom.getAtomNeighbours(); int counter =-1; Atom previousAtom = startingAtom; for (int i = neighbours.size()-1; i >=0; i--) {//only consider carbon atoms if (!neighbours.get(i).getElement().equals("C")){ neighbours.remove(i); } } while (neighbours.size()==1){ counter++; if (counter>5){ break; } Atom nextAtom = neighbours.get(0); if (nextAtom.getAtomIsInACycle()){ break; } nextAtom.addLocant(traditionalAlkanePositionNames[counter]); neighbours = nextAtom.getAtomNeighbours(); neighbours.remove(previousAtom); for (int i = neighbours.size()-1; i >=0; i--) {//only consider carbon atoms if (!neighbours.get(i).getElement().equals("C")){ neighbours.remove(i); } } previousAtom = nextAtom; } } else if (groupType.equals(CHAIN_TYPE_VAL) && ALKANESTEM_SUBTYPE_VAL.equals(group.getAttributeValue(SUBTYPE_ATR))){ List<Atom> atomList = thisFrag.getAtomList(); if (atomList.size()==1){ return; } Element possibleSuffix = (Element) XOMTools.getNextSibling(group, SUFFIX_EL); Boolean terminalSuffixWithNoSuffixPrefixPresent =false; if (possibleSuffix!=null && TERMINAL_SUBTYPE_VAL.equals(possibleSuffix.getAttributeValue(SUBTYPE_ATR)) && possibleSuffix.getAttribute(SUFFIXPREFIX_ATR)==null){ terminalSuffixWithNoSuffixPrefixPresent =true; } for (Atom atom : atomList) { String firstLocant = atom.getFirstLocant(); if (!atom.getAtomIsInACycle() && firstLocant!=null && firstLocant.length()==1 && Character.isDigit(firstLocant.charAt(0))){ int locantNumber = Integer.parseInt(firstLocant); if (terminalSuffixWithNoSuffixPrefixPresent){ if (locantNumber>1 && locantNumber<=7){ atom.addLocant(traditionalAlkanePositionNames[locantNumber-2]); } } else{ if (locantNumber>0 && locantNumber<=6){ atom.addLocant(traditionalAlkanePositionNames[locantNumber-1]); } } } } } } private void processChargeAndOxidationNumberSpecification(Element group, Fragment frag) { Element nextEl = (Element) XOMTools.getNextSibling(group); if (nextEl!=null){ if(nextEl.getLocalName().equals(CHARGESPECIFIER_EL)){ frag.getFirstAtom().setCharge(Integer.parseInt(nextEl.getAttributeValue(VALUE_ATR))); nextEl.detach(); } if(nextEl.getLocalName().equals(OXIDATIONNUMBERSPECIFIER_EL)){ frag.getFirstAtom().setProperty(Atom.OXIDATION_NUMBER, Integer.parseInt(nextEl.getAttributeValue(VALUE_ATR))); nextEl.detach(); } } } /** * Removes substituents which are just a hydro/perhydro element and moves their contents to be in front of the next in scope ring * @param substituent * @return true is the substituent was a hydro substituent and hence was removed * @throws ComponentGenerationException */ private boolean removeAndMoveToAppropriateGroupIfHydroSubstituent(Element substituent) throws ComponentGenerationException { Elements hydroElements = substituent.getChildElements(HYDRO_EL); if (hydroElements.size() > 0 && substituent.getChildElements(GROUP_EL).size()==0){ Element hydroSubstituent = substituent; if (hydroElements.size()!=1){ throw new ComponentGenerationException("Unexpected number of hydro elements found in substituent"); } Element hydroElement = hydroElements.get(0); String hydroValue = hydroElement.getValue(); if (hydroValue.equals("hydro")){ Element multiplier = (Element) XOMTools.getPreviousSibling(hydroElement); if (multiplier == null || !multiplier.getLocalName().equals(MULTIPLIER_EL) ){ throw new ComponentGenerationException("Multiplier expected but not found before hydro subsituent"); } if (Integer.parseInt(multiplier.getAttributeValue(VALUE_ATR)) %2 !=0){ throw new ComponentGenerationException("Hydro can only be added in pairs but multiplier was odd: " + multiplier.getAttributeValue(VALUE_ATR)); } } Element targetRing =null; Node nextSubOrRootOrBracket = XOMTools.getNextSibling(hydroSubstituent); //first check adjacent substituent/root. If the hydroelement has one locant or the ring is locantless then we can assume the hydro is acting as a nondetachable prefix Element potentialRing =((Element)nextSubOrRootOrBracket).getFirstChildElement(GROUP_EL); if (potentialRing!=null && containsCyclicAtoms(potentialRing)){ Element possibleLocantInFrontOfHydro = XOMTools.getPreviousSiblingIgnoringCertainElements(hydroElement, new String[]{MULTIPLIER_EL}); if (possibleLocantInFrontOfHydro !=null && possibleLocantInFrontOfHydro.getLocalName().equals(LOCANT_EL) && MATCH_COMMA.split(possibleLocantInFrontOfHydro.getValue()).length==1){ //e.g.4-decahydro-1-naphthalenyl targetRing =potentialRing; } else{ Element possibleLocantInFrontOfRing =(Element) XOMTools.getPreviousSibling(potentialRing, LOCANT_EL); if (possibleLocantInFrontOfRing !=null){ if (potentialRing.getAttribute(FRONTLOCANTSEXPECTED_ATR)!=null){//check whether the group was expecting a locant e.g. 2-furyl String locantValue = possibleLocantInFrontOfRing.getValue(); String[] expectedLocants = MATCH_COMMA.split(potentialRing.getAttributeValue(FRONTLOCANTSEXPECTED_ATR)); for (String expectedLocant : expectedLocants) { if (locantValue.equals(expectedLocant)){ targetRing =potentialRing; break; } } } //check whether the group is a HW system e.g. 1,3-thiazole if (potentialRing.getAttributeValue(SUBTYPE_ATR).equals(HANTZSCHWIDMAN_SUBTYPE_VAL)){ String locantValue = possibleLocantInFrontOfRing.getValue(); int locants = MATCH_COMMA.split(locantValue).length; int heteroCount = 0; Element currentElem = (Element) XOMTools.getNextSibling(possibleLocantInFrontOfRing); while(!currentElem.equals(potentialRing)){ if(currentElem.getLocalName().equals(HETEROATOM_EL)) { heteroCount++; } else if (currentElem.getLocalName().equals(MULTIPLIER_EL)){ heteroCount += Integer.parseInt(currentElem.getAttributeValue(VALUE_ATR)) -1; } currentElem = (Element)XOMTools.getNextSibling(currentElem); } if (heteroCount==locants){//number of locants must match number targetRing =potentialRing; } } //check whether the group is a benzofused ring e.g. 1,4-benzodioxin if (FUSIONRING_SUBTYPE_VAL.equals(potentialRing.getAttributeValue(SUBTYPE_ATR)) && (potentialRing.getValue().equals("benzo")|| potentialRing.getValue().equals("benz")) && !((Element)XOMTools.getNextSibling(potentialRing)).getLocalName().equals(FUSION_EL)){ targetRing =potentialRing; } } else{ targetRing =potentialRing; } } } //that didn't match so the hydro appears to be a detachable prefix. detachable prefixes attach in preference to the rightmost applicable group so search any remaining substituents/roots from right to left if (targetRing ==null){ Element nextSubOrRootOrBracketFromLast = (Element) hydroSubstituent.getParent().getChild(hydroSubstituent.getParent().getChildCount()-1);//the last sibling while (!nextSubOrRootOrBracketFromLast.equals(hydroSubstituent)){ potentialRing = nextSubOrRootOrBracketFromLast.getFirstChildElement(GROUP_EL); if (potentialRing!=null && containsCyclicAtoms(potentialRing)){ targetRing =potentialRing; break; } else{ nextSubOrRootOrBracketFromLast = (Element) XOMTools.getPreviousSibling(nextSubOrRootOrBracketFromLast); } } } if (targetRing ==null){ throw new ComponentGenerationException("Cannot find ring for hydro substituent to apply to"); } //move the children of the hydro substituent Elements children =hydroSubstituent.getChildElements(); for (int i = children.size()-1; i >=0 ; i Element child =children.get(i); if (!child.getLocalName().equals(HYPHEN_EL)){ child.detach(); targetRing.getParent().insertChild(child, 0); } } hydroSubstituent.detach(); return true; } return false; } /** * Removes substituents which are just a subtractivePrefix element e.g. deoxy and moves their contents to be in front of the next in scope biochemical fragment (or failing that group) * @param substituent * @return true is the substituent was a subtractivePrefix substituent and hence was removed * @throws ComponentGenerationException */ static boolean removeAndMoveToAppropriateGroupIfSubtractivePrefix(Element substituent) throws ComponentGenerationException { Elements subtractivePrefixes = substituent.getChildElements(SUBTRACTIVEPREFIX_EL); if (subtractivePrefixes.size() > 0){ if (subtractivePrefixes.size()!=1){ throw new RuntimeException("Unexpected number of subtractive prefixes found in substituent"); } Element subtractivePrefix = subtractivePrefixes.get(0); Element biochemicalGroup =null;//preferred Element standardGroup =null; Node nextSubOrRootOrBracket = XOMTools.getNextSibling(substituent); if (nextSubOrRootOrBracket == null){ throw new ComponentGenerationException("Unable to find group for: " + subtractivePrefix.getValue() +" to apply to!"); } //prefer the nearest (unlocanted) biochemical group or the rightmost standard group while (nextSubOrRootOrBracket != null){ Element groupToConsider = ((Element) nextSubOrRootOrBracket).getFirstChildElement(GROUP_EL); if (groupToConsider!=null){ if (BIOCHEMICAL_SUBTYPE_VAL.equals(groupToConsider.getAttributeValue(SUBTYPE_ATR)) || groupToConsider.getAttributeValue(TYPE_ATR).equals(CARBOHYDRATE_TYPE_VAL)){ biochemicalGroup = groupToConsider; if (XOMTools.getPreviousSiblingsOfType(biochemicalGroup, LOCANT_EL).size() == 0){ break; } } else { standardGroup = groupToConsider; } } nextSubOrRootOrBracket = (Element) XOMTools.getNextSibling(nextSubOrRootOrBracket); } Element targetGroup = biochemicalGroup!=null ? biochemicalGroup : standardGroup; if (targetGroup == null){ throw new ComponentGenerationException("Unable to find group for: " + subtractivePrefix.getValue() +" to apply to!"); } if (subtractivePrefix.getAttributeValue(TYPE_ATR).equals(ANHYDRO_TYPE_VAL)){ Element locant = (Element) XOMTools.getPreviousSibling(subtractivePrefix); if (locant == null || !locant.getLocalName().equals(LOCANT_EL)){ throw new ComponentGenerationException("Two locants are required before an anhydro prefix"); } String locantStr = locant.getValue(); if (MATCH_COMMA.split(locantStr).length != 2){ throw new ComponentGenerationException("Two locants are required before an anhydro prefix, but found: "+ locantStr); } subtractivePrefix.addAttribute(new Attribute(LOCANT_ATR, locantStr)); locant.detach(); } //move the children of the subtractivePrefix substituent Elements children =substituent.getChildElements(); for (int i = children.size()-1; i >=0 ; i Element child =children.get(i); if (!child.getLocalName().equals(HYPHEN_EL)){ child.detach(); targetGroup.getParent().insertChild(child, 0); } } substituent.detach(); return true; } return false; } private boolean containsCyclicAtoms(Element potentialRing) { Fragment potentialRingFrag = state.xmlFragmentMap.get(potentialRing); List<Atom> atomList = potentialRingFrag.getAtomList(); for (Atom atom : atomList) { if (atom.getAtomIsInACycle()){ return true; } } return false; } /** * Checks for agreement between the number of locants and multipliers. * If a locant element contains multiple elements and is not next to a multiplier the various cases where this is the case will be checked for * This may result in a locant being moved if it is more convenient for subsequent processing * @param subOrBracketOrRoot The substituent/root/bracket to looks for locants in. * @param finalSubOrRootInWord : used to check if a locant is referring to the root as in multiplicative nomenclature * @throws ComponentGenerationException * @throws StructureBuildingException */ private void determineLocantMeaning(Element subOrBracketOrRoot, Element finalSubOrRootInWord) throws StructureBuildingException, ComponentGenerationException { List<Element> locants = XOMTools.getChildElementsWithTagName(subOrBracketOrRoot, LOCANT_EL); Element group =subOrBracketOrRoot.getFirstChildElement(GROUP_EL);//will be null if element is a bracket for (Element locant : locants) { String[] locantValues = MATCH_COMMA.split(locant.getValue()); if(locantValues.length > 1) { Element afterLocant = (Element)XOMTools.getNextSibling(locant); int structuralBracketDepth = 0; Element multiplierEl = null; while (afterLocant !=null){ String elName = afterLocant.getLocalName(); if (elName.equals(STRUCTURALOPENBRACKET_EL)){ structuralBracketDepth++; } else if (elName.equals(STRUCTURALCLOSEBRACKET_EL)){ structuralBracketDepth } if (structuralBracketDepth!=0){ afterLocant = (Element)XOMTools.getNextSibling(afterLocant); continue; } if(elName.equals(LOCANT_EL)) { break; } else if (elName.equals(MULTIPLIER_EL)){ if (locantValues.length == Integer.parseInt(afterLocant.getAttributeValue(VALUE_ATR))){ if (afterLocant.equals(XOMTools.getNextSiblingIgnoringCertainElements(locant, new String[]{INDICATEDHYDROGEN_EL}))){ //direct locant, typical case. An exception is made for indicated hydrogen e.g. 1,2,4-1H-triazole multiplierEl = afterLocant; break; } else{ Element afterMultiplier = (Element) XOMTools.getNextSibling(afterLocant); if (afterMultiplier!=null && (afterMultiplier.getLocalName().equals(SUFFIX_EL) || afterMultiplier.getLocalName().equals(INFIX_EL) || afterMultiplier.getLocalName().equals(UNSATURATOR_EL) || afterMultiplier.getLocalName().equals(GROUP_EL))){ multiplierEl = afterLocant; //indirect locant break; } } } if (afterLocant.equals(XOMTools.getNextSibling(locant))){//if nothing better can be found report this as a locant/multiplier mismatch multiplierEl = afterLocant; } } else if (elName.equals(RINGASSEMBLYMULTIPLIER_EL)&& afterLocant.equals(XOMTools.getNextSibling(locant))){//e.g. 1,1'-biphenyl multiplierEl = afterLocant; if (!FragmentTools.allAtomsInRingAreIdentical(state.xmlFragmentMap.get(group))){//if all atoms are identical then the locant may refer to suffixes break; } } else if (elName.equals(FUSEDRINGBRIDGE_EL)&& locantValues.length ==2 && afterLocant.equals(XOMTools.getNextSibling(locant))){//e.g. 1,8-methano break; } afterLocant = (Element)XOMTools.getNextSibling(afterLocant); } if(multiplierEl != null) { if(Integer.parseInt(multiplierEl.getAttributeValue(VALUE_ATR)) == locantValues.length ) { // number of locants and multiplier agree boolean locantModified =false;//did determineLocantMeaning do something? if (locantValues[locantValues.length-1].endsWith("'") && group!=null && subOrBracketOrRoot.indexOf(group) > subOrBracketOrRoot.indexOf(locant)){//quite possible that this is referring to a multiplied root if (group.getAttribute(OUTIDS_ATR)!=null && MATCH_COMMA.split(group.getAttributeValue(OUTIDS_ATR)).length>1){ locantModified = checkSpecialLocantUses(locant, locantValues, finalSubOrRootInWord); } else{ Element afterGroup = (Element)XOMTools.getNextSibling(group); int inlineSuffixCount =0; int multiplier=1; while (afterGroup !=null){ if(afterGroup.getLocalName().equals(MULTIPLIER_EL)){ multiplier =Integer.parseInt(afterGroup.getAttributeValue(VALUE_ATR)); } else if(afterGroup.getLocalName().equals(SUFFIX_EL) && afterGroup.getAttributeValue(TYPE_ATR).equals(INLINE_TYPE_VAL)){ inlineSuffixCount +=(multiplier); multiplier=1; } afterGroup = (Element)XOMTools.getNextSibling(afterGroup); } if (inlineSuffixCount >=2){ locantModified = checkSpecialLocantUses(locant, locantValues, finalSubOrRootInWord); } } } if (!locantModified && !XOMTools.getNextSibling(locant).equals(multiplierEl)){//the locants apply indirectly the multiplier e.g. 2,3-butandiol //move the locant to be next to the multiplier. locant.detach(); XOMTools.insertBefore(multiplierEl, locant); } } else { if(!checkSpecialLocantUses(locant, locantValues, finalSubOrRootInWord)) { throw new ComponentGenerationException("Mismatch between locant and multiplier counts (" + Integer.toString(locantValues.length) + " and " + multiplierEl.getAttributeValue(VALUE_ATR) + "):" + locant.getValue()); } } } else { /* Multiple locants without a multiplier */ if(!checkSpecialLocantUses(locant, locantValues, finalSubOrRootInWord)) { throw new ComponentGenerationException("Multiple locants without a multiplier: " + locant.toXML()); } } } } } /**Looks for Hantzch-Widman systems, and sees if the number of locants * agrees with the number of heteroatoms. * If this is not the case alternative possibilities are tested: * The locants could be intended to indicate the position of outAtoms e.g. 1,4-phenylene * The locants could be intended to indicate the attachement points of the root groups in multiplicative nomenclature e.g. 4,4'-methylenedibenzoic acid * @param locant The element corresponding to the locant group to be tested * @param locantValues The locant values; * @param finalSubOrRootInWord : used to check if a locant is referring to the root as in multiplicative nomenclatures) * @return true if there's a HW system, and agreement; or if the locants conform to one of the alternative possibilities, otherwise false. * @throws StructureBuildingException */ private boolean checkSpecialLocantUses(Element locant, String[] locantValues, Element finalSubOrRootInWord) throws StructureBuildingException { int count =locantValues.length; Element currentElem = (Element)XOMTools.getNextSibling(locant); int heteroCount = 0; int multiplierValue = 1; while(currentElem != null && !currentElem.getLocalName().equals(GROUP_EL)){ if(currentElem.getLocalName().equals(HETEROATOM_EL)) { heteroCount+=multiplierValue; multiplierValue =1; } else if (currentElem.getLocalName().equals(MULTIPLIER_EL)){ multiplierValue = Integer.parseInt(currentElem.getAttributeValue(VALUE_ATR)); } else{ break; } currentElem = (Element)XOMTools.getNextSibling(currentElem); } if(currentElem != null && currentElem.getLocalName().equals(GROUP_EL)){ if (currentElem.getAttributeValue(SUBTYPE_ATR).equals(HANTZSCHWIDMAN_SUBTYPE_VAL)) { if(heteroCount == count) { return true; } else if (heteroCount > 1){ return false;//there is a case where locants don't apply to heteroatoms in a HW system, but in that case only one locant is expected so this function would not be called } } if (heteroCount==0 && currentElem.getAttribute(OUTIDS_ATR)!=null ) {//e.g. 1,4-phenylene String[] outIDs = MATCH_COMMA.split(currentElem.getAttributeValue(OUTIDS_ATR), -1); Fragment groupFragment =state.xmlFragmentMap.get(currentElem); if (count ==outIDs.length && groupFragment.getAtomCount()>1){//things like oxy do not need to have their outIDs specified int idOfFirstAtomInFrag =groupFragment.getIdOfFirstAtom(); boolean foundLocantNotPresentOnFragment = false; for (int i = outIDs.length-1; i >=0; i Atom a =groupFragment.getAtomByLocant(locantValues[i]); if (a==null){ foundLocantNotPresentOnFragment = true; break; } outIDs[i]=Integer.toString(a.getID() -idOfFirstAtomInFrag +1);//convert to relative id } if (!foundLocantNotPresentOnFragment){ currentElem.getAttribute(OUTIDS_ATR).setValue(StringTools.arrayToString(outIDs, ",")); locant.detach(); return true; } } } else if(currentElem.getValue().equals("benz") || currentElem.getValue().equals("benzo")){ Node potentialGroupAfterBenzo = XOMTools.getNextSibling(currentElem, GROUP_EL);//need to make sure this isn't benzyl if (potentialGroupAfterBenzo!=null){ return true;//e.g. 1,2-benzothiazole } } } if(currentElem != null) { String name = currentElem.getLocalName(); if (name.equals(POLYCYCLICSPIRO_EL)){ return true; } else if (name.equals(FUSEDRINGBRIDGE_EL) && count == 2){ return true; } else if (name.equals(SUFFIX_EL) && CYCLEFORMER_SUBTYPE_VAL.equals(currentElem.getAttributeValue(SUBTYPE_ATR)) && count == 2){ currentElem.addAttribute(new Attribute(LOCANT_ATR, locant.getValue())); locant.detach(); return true; } } boolean detectedMultiplicativeNomenclature = detectMultiplicativeNomenclature(locant, locantValues, finalSubOrRootInWord); if (detectedMultiplicativeNomenclature){ return true; } if (currentElem != null && count ==2 && currentElem.getLocalName().equals(GROUP_EL) && EPOXYLIKE_SUBTYPE_VAL.equals(currentElem.getAttributeValue(SUBTYPE_ATR))){ return true; } Element parentElem = (Element) locant.getParent(); if (count==2 && parentElem.getLocalName().equals(BRACKET_EL)){//e.g. 3,4-(dichloromethylenedioxy) this is changed to (dichloro3,4-methylenedioxy) List<Element> substituents = XOMTools.getChildElementsWithTagName(parentElem, SUBSTITUENT_EL); if (substituents.size()>0){ Element finalSub = substituents.get(substituents.size()-1); Element group = finalSub.getFirstChildElement(GROUP_EL); if (EPOXYLIKE_SUBTYPE_VAL.equals(group.getAttributeValue(SUBTYPE_ATR))){ locant.detach(); XOMTools.insertBefore(group, locant); return true; } } } return false; } /** * Detects multiplicative nomenclature. If it does then the locant will be moved, changed to a multiplicative locant and true will be returned * @param locant * @param locantValues * @param finalSubOrRootInWord * @return */ private boolean detectMultiplicativeNomenclature(Element locant, String[] locantValues, Element finalSubOrRootInWord) { int count =locantValues.length; Element multiplier =(Element) finalSubOrRootInWord.getChild(0); if (((Element)finalSubOrRootInWord.getParent()).getLocalName().equals(BRACKET_EL)){//e.g. 1,1'-ethynediylbis(1-cyclopentanol) if (!multiplier.getLocalName().equals(MULTIPLIER_EL)){ multiplier =(Element) finalSubOrRootInWord.getParent().getChild(0); } else{ Element elAfterMultiplier = (Element) XOMTools.getNextSibling(multiplier); String elName = elAfterMultiplier.getLocalName(); if (elName.equals(HETEROATOM_EL) || elName.equals(SUBTRACTIVEPREFIX_EL)|| (elName.equals(HYDRO_EL) && !elAfterMultiplier.getValue().startsWith("per"))|| elName.equals(FUSEDRINGBRIDGE_EL)) { multiplier =(Element) finalSubOrRootInWord.getParent().getChild(0); } } } Node commonParent =locant.getParent().getParent();//this should be a common parent of the multiplier in front of the root. If it is not, then this locant is in a different scope Node parentOfMultiplier =multiplier.getParent(); while (parentOfMultiplier!=null){ if (commonParent.equals(parentOfMultiplier)){ if (locantValues[count-1].endsWith("'") && multiplier.getLocalName().equals(MULTIPLIER_EL) && !((Element)XOMTools.getNextSibling(multiplier)).getLocalName().equals(MULTIPLICATIVELOCANT_EL) && Integer.parseInt(multiplier.getAttributeValue(VALUE_ATR)) == count ){//multiplicative nomenclature locant.setLocalName(MULTIPLICATIVELOCANT_EL); locant.detach(); XOMTools.insertAfter(multiplier, locant); return true; } } parentOfMultiplier=parentOfMultiplier.getParent(); } return false; } private void applyDLPrefixes(Element subOrRoot) throws ComponentGenerationException { Elements dlStereochemistryEls = subOrRoot.getChildElements(DLSTEREOCHEMISTRY_EL); for (int i = 0; i < dlStereochemistryEls.size(); i++) { Element dlStereochemistry = dlStereochemistryEls.get(i); String dlStereochemistryValue = dlStereochemistry.getAttributeValue(VALUE_ATR); Element elementToApplyTo = (Element) XOMTools.getNextSibling(dlStereochemistry); if (elementToApplyTo ==null){ throw new RuntimeException("OPSIN bug: DL stereochemistry found in inappropriate position"); } if (AMINOACID_TYPE_VAL.equals(elementToApplyTo.getAttributeValue(TYPE_ATR))){ applyDlStereochemistryToAminoAcid(elementToApplyTo, dlStereochemistryValue); } else if (elementToApplyTo.getAttributeValue(TYPE_ATR).equals(CARBOHYDRATE_TYPE_VAL)){ applyDlStereochemistryToCarbohydrate(elementToApplyTo, dlStereochemistryValue); } else if (CARBOHYDRATECONFIGURATIONPREFIX_TYPE_VAL.equals(elementToApplyTo.getAttributeValue(TYPE_ATR))){ applyDlStereochemistryToCarbohydrateConfigurationalPrefix(elementToApplyTo, dlStereochemistryValue); } else{ throw new RuntimeException("OPSIN bug: Unrecognised element after DL stereochemistry: " +elementToApplyTo.toXML()); } dlStereochemistry.detach(); } } void applyDlStereochemistryToAminoAcid(Element aminoAcidEl, String dlStereochemistryValue) throws ComponentGenerationException { Fragment aminoAcid = state.xmlFragmentMap.get(aminoAcidEl); List<Atom> atomList = aminoAcid.getAtomList(); List<Atom> atomsWithParities = new ArrayList<Atom>(); for (Atom atom : atomList) { if (atom.getAtomParity()!=null){ atomsWithParities.add(atom); } } if (atomsWithParities.isEmpty()){ throw new ComponentGenerationException("D/L stereochemistry :" +dlStereochemistryValue + " found before achiral amino acid"); } if (dlStereochemistryValue.equals("dl")){ for (Atom atom : atomsWithParities) { atom.setAtomParity(null); } } else{ boolean invert; if (dlStereochemistryValue.equals("l") || dlStereochemistryValue.equals("ls")){ invert = false; } else if (dlStereochemistryValue.equals("d") || dlStereochemistryValue.equals("ds")){ invert = true; } else{ throw new ComponentGenerationException("Unexpected value for D/L stereochemistry found before amino acid: " + dlStereochemistryValue ); } if ("yes".equals(aminoAcidEl.getAttributeValue(NATURALENTISOPPOSITE_ATR))){ invert = !invert; } if (invert) { for (Atom atom : atomsWithParities) { atom.getAtomParity().setParity(-atom.getAtomParity().getParity()); } } } } void applyDlStereochemistryToCarbohydrate(Element carbohydrateEl, String dlStereochemistryValue) throws ComponentGenerationException { Fragment carbohydrate = state.xmlFragmentMap.get(carbohydrateEl); List<Atom> atomList = carbohydrate.getAtomList(); List<Atom> atomsWithParities = new ArrayList<Atom>(); for (Atom atom : atomList) { if (atom.getAtomParity()!=null){ atomsWithParities.add(atom); } } if (atomsWithParities.isEmpty()){ throw new ComponentGenerationException("D/L stereochemistry :" + dlStereochemistryValue + " found before achiral carbohydrate");//sounds like a vocab bug... } if (dlStereochemistryValue.equals("dl")){ for (Atom atom : atomsWithParities) { atom.setAtomParity(null); } } else{ boolean invert; if (dlStereochemistryValue.equals("d") || dlStereochemistryValue.equals("dg")){ invert = false; } else if (dlStereochemistryValue.equals("l") || dlStereochemistryValue.equals("lg")){ invert = true; } else{ throw new ComponentGenerationException("Unexpected value for D/L stereochemistry found before carbohydrate: " + dlStereochemistryValue ); } if ("yes".equals(carbohydrateEl.getAttributeValue(NATURALENTISOPPOSITE_ATR))){ invert = !invert; } if (invert) { for (Atom atom : atomsWithParities) { atom.getAtomParity().setParity(-atom.getAtomParity().getParity()); } } } } static void applyDlStereochemistryToCarbohydrateConfigurationalPrefix(Element elementToApplyTo, String dlStereochemistryValue) throws ComponentGenerationException { if (dlStereochemistryValue.equals("d") || dlStereochemistryValue.equals("dg")){ //do nothing, D- is implicit } else if (dlStereochemistryValue.equals("l") || dlStereochemistryValue.equals("lg")){ String[] values = MATCH_SLASH.split(elementToApplyTo.getAttributeValue(VALUE_ATR), -1); StringBuilder sb = new StringBuilder(); for (String value : values) { if (value.equals("r")){ sb.append("l"); } else if (value.equals("l")){ sb.append("r"); } else{ throw new RuntimeException("OPSIN Bug: Invalid carbohydrate prefix value: " + elementToApplyTo.getAttributeValue(VALUE_ATR)); } sb.append("/"); } String newVal = sb.toString().substring(0, sb.length()-1); elementToApplyTo.getAttribute(VALUE_ATR).setValue(newVal); } else if (dlStereochemistryValue.equals("dl")){ String[] values = MATCH_SLASH.split(elementToApplyTo.getAttributeValue(VALUE_ATR)); String newVal = "?" + StringTools.multiplyString("/?", values.length-1); elementToApplyTo.getAttribute(VALUE_ATR).setValue(newVal); } else{ throw new ComponentGenerationException("Unexpected value for D/L stereochemistry found before carbohydrate prefix: " + dlStereochemistryValue ); } } /** * Cyclises carbohydrates and regularises their suffixes * @param subOrRoot * @throws StructureBuildingException */ private void processCarbohydrates(Element subOrRoot) throws StructureBuildingException { List<Element> carbohydrates = XOMTools.getChildElementsWithTagNameAndAttribute(subOrRoot, GROUP_EL, TYPE_ATR, CARBOHYDRATE_TYPE_VAL); for (Element carbohydrate : carbohydrates) { String subtype = carbohydrate.getAttributeValue(SUBTYPE_ATR); boolean isAldose; if (CARBOHYDRATESTEMKETOSE_SUBTYPE_VAL.equals(subtype)){ isAldose = false; } else if (CARBOHYDRATESTEMALDOSE_SUBTYPE_VAL.equals(subtype) || SYSTEMATICCARBOHYDRATESTEMALDOSE_SUBTYPE_VAL.equals(subtype)){ isAldose = true; } else{ //trivial carbohydrates don't have suffixes continue; } boolean cyclisationPerformed = false; Fragment carbohydrateFrag = state.xmlFragmentMap.get(carbohydrate); Attribute anomericId = carbohydrate.getAttribute(SUFFIXAPPLIESTO_ATR); if (anomericId == null){ throw new StructureBuildingException("OPSIN bug: Missing suffixAppliesTo on: " + carbohydrate.getValue()); } Atom potentialCarbonyl = carbohydrateFrag.getAtomByID(carbohydrateFrag.getIdOfFirstAtom() + Integer.parseInt(anomericId.getValue()) -1); if (potentialCarbonyl == null){ throw new StructureBuildingException("OPSIN bug: " + anomericId.getValue() + " did not point to an atom on: " + carbohydrate.getValue()); } carbohydrate.removeAttribute(anomericId); Element nextSibling = (Element) XOMTools.getNextSibling(carbohydrate); while (nextSibling !=null){ Element nextNextSibling = (Element) XOMTools.getNextSibling(nextSibling); String elName = nextSibling.getLocalName(); if (elName.equals(SUFFIX_EL)){ Element suffix = nextSibling; String value = suffix.getAttributeValue(VALUE_ATR); if (value.equals("dialdose") || value.equals("aric acid") || value.equals("arate")){ if (!isAldose){ throw new StructureBuildingException(value + " may only be used with aldoses"); } if (cyclisationPerformed){ throw new StructureBuildingException("OPSIN bug: " + value + " not expected after carbohydrate cycliser"); } processAldoseDiSuffix(value, carbohydrate, potentialCarbonyl); suffix.detach(); } else if (value.startsWith("uron")){ //strictly these are also aldose di suffixes but in practice they are also used on ketoses suffix.addAttribute(new Attribute(LOCANT_ATR, String.valueOf(carbohydrateFrag.getChainLength()))); } else if (!cyclisationPerformed && (value.equals("ulose") || value.equals("osulose"))){ if (value.equals("ulose")){ isAldose = false; if (SYSTEMATICCARBOHYDRATESTEMALDOSE_SUBTYPE_VAL.equals(subtype)){ carbohydrate.getAttribute(SUBTYPE_ATR).setValue(SYSTEMATICCARBOHYDRATESTEMKETOSE_SUBTYPE_VAL); carbohydrateFrag.setSubType(SYSTEMATICCARBOHYDRATESTEMKETOSE_SUBTYPE_VAL); } } potentialCarbonyl = processUloseSuffix(carbohydrate, suffix, potentialCarbonyl); suffix.detach(); } else if (value.equals("itol") || value.equals("yl") || value.equals("glycoside")){ suffix.addAttribute(new Attribute(LOCANT_ATR, potentialCarbonyl.getFirstLocant())); if (value.equals("glycoside") && OpsinTools.getParentWordRule(subOrRoot).getAttributeValue(WORDRULE_ATR).equals(WordRule.simple.toString())){ throw new StructureBuildingException("A glycoside requires a space seperated substituent e.g. methyl alpha-D-glucopyranoside"); } } } else if (elName.equals(CARBOHYDRATERINGSIZE_EL)){ if (cyclisationPerformed){ throw new StructureBuildingException("OPSIN bug: Carbohydate cyclised twice!"); } Element ringSize = nextSibling; cycliseCarbohydrate(carbohydrate, ringSize, potentialCarbonyl); ringSize.detach(); cyclisationPerformed = true; } else if (!elName.equals(LOCANT_EL) && !elName.equals(MULTIPLIER_ATR) && !elName.equals(UNSATURATOR_EL)){ break; } nextSibling = nextNextSibling; } if (!cyclisationPerformed){ applyUnspecifiedRingSizeCyclisationIfPresent(carbohydrate, potentialCarbonyl); } } } private void applyUnspecifiedRingSizeCyclisationIfPresent(Element group, Atom potentialCarbonyl) throws StructureBuildingException { boolean cyclise = false; Element possibleYl = (Element) XOMTools.getNextSibling(group); if (possibleYl != null && possibleYl.getLocalName().equals(SUFFIX_EL) && possibleYl.getValue().equals("yl")){ cyclise = true; } else{ Element alphaOrBetaLocantEl = (Element) XOMTools.getPreviousSiblingIgnoringCertainElements(group, new String[]{STEREOCHEMISTRY_EL}); if (alphaOrBetaLocantEl != null && alphaOrBetaLocantEl.getLocalName().equals(LOCANT_EL) ){ String value = alphaOrBetaLocantEl.getValue(); if (value.equals("alpha") || value.equals("beta") || value.equals("alpha,beta") || value.equals("beta,alpha")){ cyclise = true; } } } if (cyclise) { Element ringSize = new Element(CARBOHYDRATERINGSIZE_EL); String sugarStem = group.getValue(); if (state.xmlFragmentMap.get(group).hasLocant("5") && !sugarStem.equals("rib") && !sugarStem.equals("fruct")){ ringSize.addAttribute(new Attribute(VALUE_ATR, "6")); } else{ ringSize.addAttribute(new Attribute(VALUE_ATR, "5")); } XOMTools.insertAfter(group, ringSize); cycliseCarbohydrate(group, ringSize, potentialCarbonyl); ringSize.detach(); } } /** * Indicates that the compound is a ketose. * This may take the form of replacement of the aldose functionality with ketose functionality or the additon of ketose functionality * The carbonyl may be subsequently used in cyclisation e.g. non-2-ulopyranose * A potentialcarbonyl is returned * @param group * @param suffix * @param potentialCarbonyl * @return * @throws StructureBuildingException */ private Atom processUloseSuffix(Element group, Element suffix, Atom potentialCarbonyl) throws StructureBuildingException { List<String> locantsToConvertToKetones = new ArrayList<String>(); Element potentialLocantOrMultiplier = (Element) XOMTools.getPreviousSibling(suffix); if (potentialLocantOrMultiplier.getLocalName().equals(MULTIPLIER_ATR)){ int multVal = Integer.parseInt(potentialLocantOrMultiplier.getAttributeValue(VALUE_ATR)); Element locant = (Element) XOMTools.getPreviousSibling(potentialLocantOrMultiplier); if (locant != null && locant.getLocalName().equals(LOCANT_EL)){ String[] locantStrs = MATCH_COMMA.split(locant.getValue()); if (locantStrs.length != multVal) { throw new StructureBuildingException("Mismatch between locant and multiplier counts (" + locantStrs.length + " and " + multVal + "):" + locant.getValue()); } for (String locantStr : locantStrs) { locantsToConvertToKetones.add(locantStr); } locant.detach(); } else{ for (int i = 0; i < multVal; i++) { locantsToConvertToKetones.add(String.valueOf(i + 2)); } } potentialLocantOrMultiplier.detach(); } else { Element locant = potentialLocantOrMultiplier; if (!locant.getLocalName().equals(LOCANT_EL)){ locant = (Element) XOMTools.getPreviousSibling(group); } if (locant !=null && locant.getLocalName().equals(LOCANT_EL)){ String locantStr = locant.getValue(); if (MATCH_COMMA.split(locantStr).length==1){ locantsToConvertToKetones.add(locantStr); } else{ throw new StructureBuildingException("Incorrect number of locants for ul suffix: " + locantStr); } locant.detach(); } else{ locantsToConvertToKetones.add("2"); } } Fragment frag = state.xmlFragmentMap.get(group); if (suffix.getAttributeValue(VALUE_ATR).equals("ulose")) {//convert aldose to ketose Atom aldehydeAtom = potentialCarbonyl; boolean foundBond = false; for (Bond bond : aldehydeAtom.getBonds()) { if (bond.getOrder() ==2){ Atom otherAtom = bond.getOtherAtom(aldehydeAtom); if (otherAtom.getElement().equals("O") && otherAtom.getCharge()==0 && otherAtom.getBonds().size()==1){ bond.setOrder(1); foundBond = true; break; } } } if (!foundBond){ throw new StructureBuildingException("OPSIN bug: Unable to convert aldose to ketose"); } Atom backboneAtom = frag.getAtomByLocantOrThrow(locantsToConvertToKetones.get(0)); potentialCarbonyl = backboneAtom; } for (String locantStr : locantsToConvertToKetones) { Atom backboneAtom = frag.getAtomByLocantOrThrow(locantStr); boolean foundBond = false; for (Bond bond : backboneAtom.getBonds()) { if (bond.getOrder() ==1){ Atom otherAtom = bond.getOtherAtom(backboneAtom); if (otherAtom.getElement().equals("O") && otherAtom.getCharge()==0 && otherAtom.getBonds().size()==1){ bond.setOrder(2); foundBond = true; break; } } } if (!foundBond){ throw new StructureBuildingException("Failed to find hydroxy group at position:" + locantStr); } backboneAtom.setAtomParity(null); } return potentialCarbonyl; } /** * Cyclises carbohydrate configuration prefixes according to the ring size indicator * Alpha/beta stereochemistry is then applied if present * @param carbohydrateGroup * @param ringSize * @param potentialCarbonyl * @throws StructureBuildingException */ private void cycliseCarbohydrate(Element carbohydrateGroup, Element ringSize, Atom potentialCarbonyl) throws StructureBuildingException { Fragment frag = state.xmlFragmentMap.get(carbohydrateGroup); String ringSizeVal = ringSize.getAttributeValue(VALUE_ATR); Element potentialLocant = (Element) XOMTools.getPreviousSibling(ringSize); Atom carbonylCarbon = null; Atom atomToJoinWith = null; if (potentialLocant.getLocalName().equals(LOCANT_EL)){ String[] locants = MATCH_COMMA.split(potentialLocant.getValue()); if (locants.length != 2){ throw new StructureBuildingException("Expected 2 locants in front of sugar ring size specifier but found: " + potentialLocant.getValue()); } try{ int firstLocant = Integer.parseInt(locants[0]); int secondLocant = Integer.parseInt(locants[1]); if (Math.abs(secondLocant - firstLocant) != (Integer.parseInt(ringSizeVal) -2)){ throw new StructureBuildingException("Mismatch between ring size: " + ringSizeVal + " and ring size specified by locants: " + (Math.abs(secondLocant - firstLocant) + 2) ); } } catch (NumberFormatException e){ throw new StructureBuildingException("Locants for ring should be numeric but were: " + potentialLocant.getValue()); } carbonylCarbon = frag.getAtomByLocantOrThrow(locants[0]); atomToJoinWith = frag.getAtomByLocantOrThrow("O" + locants[1]); potentialLocant.detach(); } if (carbonylCarbon == null){ carbonylCarbon = potentialCarbonyl; if (carbonylCarbon ==null){ throw new RuntimeException("OPSIN bug: Could not find carbonyl carbon in carbohydrate"); } } for (Bond b: carbonylCarbon.getBonds()) { if (b.getOrder()==2){ b.setOrder(1); break; } } int locantOfCarbonyl; try{ locantOfCarbonyl = Integer.parseInt(carbonylCarbon.getFirstLocant()); } catch (Exception e) { throw new RuntimeException("OPSIN bug: Could not determine locant of carbonyl carbon in carbohydrate", e); } if (atomToJoinWith ==null){ String locantToJoinWith = String.valueOf(locantOfCarbonyl + Integer.parseInt(ringSizeVal) -2); atomToJoinWith =frag.getAtomByLocant("O" +locantToJoinWith); if (atomToJoinWith ==null){ throw new StructureBuildingException("Carbohydrate was not an inappropriate length to form a ring of size: " + ringSizeVal); } } state.fragManager.createBond(carbonylCarbon, atomToJoinWith, 1); CycleDetector.assignWhetherAtomsAreInCycles(frag); Element alphaOrBetaLocantEl = (Element) XOMTools.getPreviousSiblingIgnoringCertainElements(carbohydrateGroup, new String[]{STEREOCHEMISTRY_EL}); if (alphaOrBetaLocantEl !=null && alphaOrBetaLocantEl.getLocalName().equals(LOCANT_EL)){ Element stereoPrefixAfterAlphaBeta = (Element) XOMTools.getNextSibling(alphaOrBetaLocantEl); Atom anomericReferenceAtom = getAnomericReferenceAtom(frag); if (anomericReferenceAtom ==null){ throw new RuntimeException("OPSIN bug: Unable to determine anomeric reference atom in: " +carbohydrateGroup.getValue()); } applyAnomerStereochemistryIfPresent(alphaOrBetaLocantEl, carbonylCarbon, anomericReferenceAtom); if (carbonylCarbon.getAtomParity() !=null && (SYSTEMATICCARBOHYDRATESTEMALDOSE_SUBTYPE_VAL.equals(carbohydrateGroup.getAttributeValue(SUBTYPE_ATR)) || SYSTEMATICCARBOHYDRATESTEMKETOSE_SUBTYPE_VAL.equals(carbohydrateGroup.getAttributeValue(SUBTYPE_ATR)))){ //systematic chains only have their stereochemistry defined after structure building to account for the fact that some stereocentres may be removed //hence inspect the stereoprefix to see if it is L and flip if so String val = stereoPrefixAfterAlphaBeta.getAttributeValue(VALUE_ATR); if (val.substring(val.length() -1 , val.length()).equals("l")){//"r" if D, "l" if L //flip if L AtomParity atomParity = carbonylCarbon.getAtomParity(); atomParity.setParity(-atomParity.getParity()); } } } carbonylCarbon.setProperty(Atom.ISANOMERIC, true); } private void processAldoseDiSuffix(String suffixValue, Element group, Atom aldehydeAtom) throws StructureBuildingException { Fragment frag = state.xmlFragmentMap.get(group); Atom alcoholAtom = frag.getAtomByLocantOrThrow(String.valueOf(frag.getChainLength())); if (suffixValue.equals("aric acid") || suffixValue.equals("arate")){ removeTerminalOxygen(alcoholAtom, 1); Fragment f = state.fragManager.buildSMILES("O", frag.getType(), frag.getSubType(), NONE_LABELS_VAL); state.fragManager.incorporateFragment(f, f.getFirstAtom(), frag, alcoholAtom, 2); f = state.fragManager.buildSMILES("O", frag.getType(), frag.getSubType(), NONE_LABELS_VAL); Atom hydroxyAtom = f.getFirstAtom(); if (suffixValue.equals("arate")){ hydroxyAtom.addChargeAndProtons(-1, -1); } state.fragManager.incorporateFragment(f, f.getFirstAtom(), frag, alcoholAtom, 1); frag.addFunctionalAtom(hydroxyAtom); f = state.fragManager.buildSMILES("O", frag.getType(), frag.getSubType(), NONE_LABELS_VAL); hydroxyAtom = f.getFirstAtom(); if (suffixValue.equals("arate")){ hydroxyAtom.addChargeAndProtons(-1, -1); } state.fragManager.incorporateFragment(f, f.getFirstAtom(), frag, aldehydeAtom, 1); frag.addFunctionalAtom(hydroxyAtom); } else if (suffixValue.equals("dialdose")){ removeTerminalOxygen(alcoholAtom, 1); Fragment f = state.fragManager.buildSMILES("O", frag.getType(), frag.getSubType(), NONE_LABELS_VAL); state.fragManager.incorporateFragment(f, f.getFirstAtom(), frag, alcoholAtom, 2); } else{ throw new IllegalArgumentException("OPSIN Bug: Unexpected suffix value: " + suffixValue); } } /** * Gets the configurationalAtom currently i.e. the defined stereocentre with the highest locant * @param frag * @return */ private Atom getAnomericReferenceAtom(Fragment frag){ List<Atom> atomList = frag.getAtomList(); int highestLocantfound = Integer.MIN_VALUE; Atom configurationalAtom = null; for (Atom a : atomList) { if (a.getAtomParity()==null){ continue; } try{ String locant = a.getFirstLocant(); int intVal = Integer.parseInt(locant); if (intVal > highestLocantfound){ highestLocantfound = intVal; configurationalAtom = a; } } catch (Exception e) { //may throw null pointer exceptions or number format exceptions } } return configurationalAtom; } private void applyAnomerStereochemistryIfPresent(Element alphaOrBetaLocantEl, Atom anomericAtom, Atom anomericReferenceAtom) { String value = alphaOrBetaLocantEl.getValue(); if (value.equals("alpha") || value.equals("beta")){ Atom[] referenceAtomRefs4 = getDeterministicAtomRefs4ForReferenceAtom(anomericReferenceAtom); boolean flip = StereochemistryHandler.checkEquivalencyOfAtomsRefs4AndParity(referenceAtomRefs4, 1, anomericReferenceAtom.getAtomParity().getAtomRefs4(), anomericReferenceAtom.getAtomParity().getParity()); Atom[] atomRefs4 = getDeterministicAtomRefs4ForAnomericAtom(anomericAtom); if (flip){ if (value.equals("alpha")){ anomericAtom.setAtomParity(atomRefs4, 1); } else{ anomericAtom.setAtomParity(atomRefs4, -1); } } else{ if (value.equals("alpha")){ anomericAtom.setAtomParity(atomRefs4, -1); } else{ anomericAtom.setAtomParity(atomRefs4, 1); } } alphaOrBetaLocantEl.detach(); } else if (value.equals("alpha,beta") || value.equals("beta,alpha")){ //unspecified stereochemistry alphaOrBetaLocantEl.detach(); } } private Atom[] getDeterministicAtomRefs4ForReferenceAtom(Atom referenceAtom) { List<Atom> neighbours = referenceAtom.getAtomNeighbours(); if (neighbours.size()!=3){ throw new RuntimeException("OPSIN bug: Unexpected number of atoms connected to anomeric reference atom of carbohydrate"); } String nextLowestLocant = String.valueOf(Integer.parseInt(referenceAtom.getFirstLocant()) -1); Atom[] atomRefs4 = new Atom[4]; for (Atom neighbour : neighbours) { if (neighbour.getElement().equals("O")){ atomRefs4[0] = neighbour; } else if (neighbour.getElement().equals("C")){ if (neighbour.getFirstLocant().equals(nextLowestLocant)){ atomRefs4[1] = neighbour; } else { atomRefs4[2] = neighbour; } } else{ throw new RuntimeException("OPSIN bug: Unexpected atom element type connected to for anomeric reference atom"); } } atomRefs4[3] = AtomParity.hydrogen; for (Atom atom : atomRefs4) { if (atom ==null){ throw new RuntimeException("OPSIN bug: Unable to determine atomRefs4 for anomeric reference atom"); } } return atomRefs4; } private Atom[] getDeterministicAtomRefs4ForAnomericAtom(Atom anomericAtom) { List<Atom> neighbours = anomericAtom.getAtomNeighbours(); if (neighbours.size()!=3 && neighbours.size()!=4){ throw new RuntimeException("OPSIN bug: Unexpected number of atoms connected to anomeric atom of carbohydrate"); } Atom[] atomRefs4 = new Atom[4]; for (Atom neighbour : neighbours) { if (neighbour.getElement().equals("C")){ if (neighbour.getAtomIsInACycle()){ atomRefs4[0] = neighbour; } else{ atomRefs4[3] = neighbour; } } else if (neighbour.getElement().equals("O")){ int incomingVal =neighbour.getIncomingValency(); if (incomingVal ==1){ atomRefs4[1] = neighbour; } else if (incomingVal ==2){ atomRefs4[2] = neighbour; } else{ throw new RuntimeException("OPSIN bug: Unexpected valency on oxygen in carbohydrate"); } } else{ throw new RuntimeException("OPSIN bug: Unexpected atom element type connected to anomeric atom of carbohydrate"); } } if (atomRefs4[3]==null){ atomRefs4[3] = AtomParity.hydrogen; } for (Atom atom : atomRefs4) { if (atom ==null){ throw new RuntimeException("OPSIN bug: Unable to assign anomeric carbon stereochemistry on carbohydrate"); } } return atomRefs4; } /** Look for multipliers, and multiply out suffixes/unsaturators/heteroatoms/hydros. * Locants are assigned if the number of locants matches the multiplier * associated with them. Eg. triol - > ololol. * Note that infix multiplication is handled seperately as resolution of suffixes is required to perform this unambiguously * @param subOrRoot The substituent/root to looks for multipliers in. */ private void processMultipliers(Element subOrRoot) { List<Element> multipliers = XOMTools.getChildElementsWithTagName(subOrRoot, MULTIPLIER_EL); for (Element multiplier : multipliers) { Element possibleLocant =(Element)XOMTools.getPreviousSibling(multiplier); String[] locants = null; if (possibleLocant !=null && possibleLocant.getLocalName().equals(LOCANT_EL)){ locants = MATCH_COMMA.split(possibleLocant.getValue()); } Element featureToMultiply = (Element)XOMTools.getNextSibling(multiplier); String nextName = featureToMultiply.getLocalName(); if(nextName.equals(UNSATURATOR_EL) || nextName.equals(SUFFIX_EL) || nextName.equals(SUBTRACTIVEPREFIX_EL) || (nextName.equals(HETEROATOM_EL) && !GROUP_TYPE_VAL.equals(multiplier.getAttributeValue(TYPE_ATR))) || nextName.equals(HYDRO_EL)) { int mvalue = Integer.parseInt(multiplier.getAttributeValue(VALUE_ATR)); if (mvalue>1){ featureToMultiply.addAttribute(new Attribute(MULTIPLIED_ATR, "multiplied")); } for(int i= mvalue -1; i >=1; i Element newElement = new Element(featureToMultiply); if (locants !=null && locants.length==mvalue){ newElement.addAttribute(new Attribute(LOCANT_ATR, locants[i])); } XOMTools.insertAfter(featureToMultiply, newElement); } multiplier.detach(); if (locants !=null && locants.length==mvalue){ featureToMultiply.addAttribute(new Attribute(LOCANT_ATR, locants[0])); possibleLocant.detach(); } } } } /** * Converts group elements that are identified as being conjunctive suffixes to CONJUNCTIVESUFFIXGROUP_EL * and labels them appropriately. Any suffixes that the conjunctive suffix may have are resolved onto it * @param subOrRoot * @param allGroups * @throws ComponentGenerationException * @throws StructureBuildingException */ private void detectConjunctiveSuffixGroups(Element subOrRoot, List<Element> allGroups) throws ComponentGenerationException, StructureBuildingException { List<Element> groups = XOMTools.getChildElementsWithTagName(subOrRoot, GROUP_EL); if (groups.size()>1){ List<Element> conjunctiveGroups = new ArrayList<Element>(); Element ringGroup =null; for (int i = groups.size() -1 ; i >=0; i Element group =groups.get(i); if (!group.getAttributeValue(TYPE_ATR).equals(RING_TYPE_VAL)){//e.g. the methanol in benzenemethanol. conjunctiveGroups.add(group); } else{ ringGroup =group; break; } } if (conjunctiveGroups.size() ==0){ return; } if (ringGroup ==null){ throw new ComponentGenerationException("OPSIN bug: unable to find ring associated with conjunctive suffix group"); } if (conjunctiveGroups.size()!=1){ throw new ComponentGenerationException("OPSIN Bug: Two groups exactly should be present at this point when processing conjunctive nomenclature"); } Element primaryConjunctiveGroup =conjunctiveGroups.get(0); Fragment primaryConjunctiveFrag = state.xmlFragmentMap.get(primaryConjunctiveGroup); //remove all locants List<Atom> atomList = primaryConjunctiveFrag.getAtomList(); for (Atom atom : atomList) { atom.clearLocants(); } List<Element> suffixes = new ArrayList<Element>(); Element possibleSuffix = (Element) XOMTools.getNextSibling(primaryConjunctiveGroup); while (possibleSuffix !=null){ if (possibleSuffix.getLocalName().equals(SUFFIX_EL)){ suffixes.add(possibleSuffix); } possibleSuffix = (Element) XOMTools.getNextSibling(possibleSuffix); } preliminaryProcessSuffixes(primaryConjunctiveGroup, suffixes); resolveSuffixes(primaryConjunctiveGroup, suffixes); for (Element suffix : suffixes) { suffix.detach(); } primaryConjunctiveGroup.setLocalName(CONJUNCTIVESUFFIXGROUP_EL); allGroups.remove(primaryConjunctiveGroup); Element possibleMultiplier = (Element) XOMTools.getPreviousSibling(primaryConjunctiveGroup); //label atoms appropriately boolean alphaIsPosition1 = atomList.get(0).getIncomingValency() < 3; int counter =0; for (int i = (alphaIsPosition1 ? 0 : 1); i < atomList.size(); i++) { Atom a = atomList.get(i); if (counter==0){ a.addLocant("alpha"); } else if (counter==1){ a.addLocant("beta"); } else if (counter==2){ a.addLocant("gamma"); } else if (counter==3){ a.addLocant("delta"); } else if (counter==4){ a.addLocant("epsilon"); } else if (counter==5){ a.addLocant("zeta"); } else if (counter==6){ a.addLocant("eta"); } counter++; } if (MULTIPLIER_EL.equals(possibleMultiplier.getLocalName())){ int multiplier = Integer.parseInt(possibleMultiplier.getAttributeValue(VALUE_ATR)); for (int i = 1; i < multiplier; i++) { Element conjunctiveSuffixGroup = new Element(primaryConjunctiveGroup); Fragment newFragment = state.fragManager.copyAndRelabelFragment(primaryConjunctiveFrag, i); state.xmlFragmentMap.put(conjunctiveSuffixGroup, newFragment); conjunctiveGroups.add(conjunctiveSuffixGroup); XOMTools.insertAfter(primaryConjunctiveGroup, conjunctiveSuffixGroup); } Element possibleLocant =(Element)XOMTools.getPreviousSibling(possibleMultiplier); possibleMultiplier.detach(); if (possibleLocant.getLocalName().equals(LOCANT_EL)){ String[] locants = MATCH_COMMA.split(possibleLocant.getValue()); if (locants.length!=multiplier){ throw new ComponentGenerationException("mismatch between number of locants and multiplier in conjunctive nomenclature routine"); } for (int i = 0; i < locants.length; i++) { conjunctiveGroups.get(i).addAttribute(new Attribute(LOCANT_ATR, locants[i])); } possibleLocant.detach(); } } } } /** Match each locant to the next applicable "feature". Assumes that processLocants * has done a good job and rejected cases where no match can be made. * Handles cases where the locant is next to the feature it refers to * * @param subOrRoot The substituent/root to look for locants in. * @throws ComponentGenerationException */ private void matchLocantsToDirectFeatures(Element subOrRoot) throws ComponentGenerationException { List<Element> locants = XOMTools.getChildElementsWithTagName(subOrRoot, LOCANT_EL); List<Element> groups = XOMTools.getChildElementsWithTagName(subOrRoot, GROUP_EL); for (Element group : groups) { if (group.getAttributeValue(SUBTYPE_ATR).equals(HANTZSCHWIDMAN_SUBTYPE_VAL)){//handle Hantzch-widman systems if (group.getAttribute(ADDBOND_ATR)!=null){//special case for partunsatring //exception for where a locant is supposed to indicate the location of a double bond... Elements deltas = subOrRoot.getChildElements(DELTA_EL); if (deltas.size()==0){ Element delta =new Element(DELTA_EL); Element appropriateLocant = XOMTools.getPreviousSiblingIgnoringCertainElements(group, new String[]{HETEROATOM_EL, MULTIPLIER_EL}); if (appropriateLocant !=null && appropriateLocant.getLocalName().equals(LOCANT_EL) && MATCH_COMMA.split(appropriateLocant.getValue()).length == 1){ delta.appendChild(appropriateLocant.getValue()); XOMTools.insertBefore(appropriateLocant, delta); appropriateLocant.detach(); locants.remove(appropriateLocant); } else{ delta.appendChild(""); subOrRoot.insertChild(delta, 0);//no obvious attempt to set double bond position, potentially ambiguous, valency will be used to choose later } } } if (locants.size()>0 ){ Element locantBeforeHWSystem = null; List<Element> heteroAtoms = new ArrayList<Element>(); int indexOfGroup =subOrRoot.indexOf(group); for (int j = indexOfGroup -1; j >= 0; j String elName=((Element)subOrRoot.getChild(j)).getLocalName(); if (elName.equals(LOCANT_EL)){ locantBeforeHWSystem = (Element)subOrRoot.getChild(j); break; } else if(elName.equals(HETEROATOM_EL)){ Element heteroAtom = (Element)subOrRoot.getChild(j); heteroAtoms.add(heteroAtom); if (heteroAtom.getAttribute(LOCANT_ATR)!=null){//locants already assigned, assumedly by process multipliers break; } } else{ break; } } Collections.reverse(heteroAtoms); if (locantBeforeHWSystem !=null){ String[] locantValues = MATCH_COMMA.split(locantBeforeHWSystem.getValue()); //detect a solitary locant in front of a HW system and prevent it being assigned. //something like 1-aziridin-1-yl never means the N is at position 1 as it is at position 1 by convention //this special case is not applied to pseudo HW like systems e.g. [1]oxacyclotetradecine if (locantValues.length ==1 && state.xmlFragmentMap.get(group).getAtomCount() <=10){ locants.remove(locantBeforeHWSystem);//don't assign this locant } else { if (locantValues.length == heteroAtoms.size()){ for (int j = 0; j < locantValues.length; j++) { String locantValue = locantValues[j]; heteroAtoms.get(j).addAttribute(new Attribute(LOCANT_ATR, locantValue)); } locantBeforeHWSystem.detach(); locants.remove(locantBeforeHWSystem); } else if (heteroAtoms.size()>1){ throw new ComponentGenerationException("Mismatch between number of locants and HW heteroatoms"); } } } } } } assignSingleLocantsToAdjacentFeatures(locants); } /** * Looks for a suffix/suffix/heteroatom/hydro element adjacent to the given locant * and if the locant element describes just 1 locant asssigns it * @param locants */ private void assignSingleLocantsToAdjacentFeatures(List<Element> locants) { for (Element locant : locants) { String[] locantValues = MATCH_COMMA.split(locant.getValue()); Element referent = (Element)XOMTools.getNextSibling(locant); if (referent!=null && locantValues.length==1){ String refName = referent.getLocalName(); if(referent.getAttribute(LOCANT_ATR) == null && referent.getAttribute(MULTIPLIED_ATR) == null && (refName.equals(UNSATURATOR_EL) || refName.equals(SUFFIX_EL) || refName.equals(HETEROATOM_EL) || refName.equals(CONJUNCTIVESUFFIXGROUP_EL) || refName.equals(SUBTRACTIVEPREFIX_EL) || (refName.equals(HYDRO_EL) && !referent.getValue().startsWith("per") ))) {//not perhydro referent.addAttribute(new Attribute(LOCANT_ATR, locantValues[0])); locant.detach(); } } } } /** * Handles suffixes, passes them to resolveGroupAddingSuffixes. * Processes the suffixAppliesTo command which multiplies a suffix and attaches the suffixes to the atoms described by the given IDs * @param group * @param suffixes * @throws ComponentGenerationException * @throws StructureBuildingException */ private void preliminaryProcessSuffixes(Element group, List<Element> suffixes) throws ComponentGenerationException, StructureBuildingException{ Fragment suffixableFragment =state.xmlFragmentMap.get(group); if (group.getAttribute(SUFFIXAPPLIESTO_ATR)!=null){//typically a trivial polyAcid or aminoAcid processSuffixAppliesTo(group, suffixes,suffixableFragment); } else{ for (Element suffix : suffixes) { if (suffix.getAttribute(ADDITIONALVALUE_ATR)!=null){ throw new ComponentGenerationException("suffix: " + suffix.getValue() + " used on an inappropriate group"); } } } applyDefaultLocantsToSuffixesIfApplicable(group, suffixableFragment); List<Fragment> suffixFragments =resolveGroupAddingSuffixes(suffixes, suffixableFragment); state.xmlSuffixMap.put(group, suffixFragments); boolean suffixesResolved =false; if (group.getAttributeValue(TYPE_ATR).equals(CHALCOGENACIDSTEM_TYPE_VAL)){//merge the suffix into the chalcogen acid stem e.g sulfonoate needs to be one fragment for infix replacement resolveSuffixes(group, suffixes); suffixesResolved =true; } processSuffixPrefixes(suffixes);//e.g. carbox amide FunctionalReplacement.processInfixFunctionalReplacementNomenclature(state, suffixes, suffixFragments); processRemovalOfHydroxyGroupsRules(suffixes, suffixableFragment); if (group.getValue().equals("oxal")){//oxalic acid is treated as a non carboxylic acid for the purposes of functional replacment. See P-65.2.3 resolveSuffixes(group, suffixes); group.getAttribute(TYPE_ATR).setValue(NONCARBOXYLICACID_TYPE_VAL); suffixableFragment.setType(NONCARBOXYLICACID_TYPE_VAL); suffixesResolved =true; } if (suffixesResolved){ //suffixes have already been resolved so need to be detached to avoid being passed to resolveSuffixes later for (int i = suffixes.size() -1; i>=0; i Element suffix =suffixes.remove(i); suffix.detach(); } } if (group.getAttribute(NUMBEROFFUNCTIONALATOMSTOREMOVE_ATR)!=null){ int numberToRemove = Integer.parseInt(group.getAttributeValue(NUMBEROFFUNCTIONALATOMSTOREMOVE_ATR)); if (numberToRemove > suffixableFragment.getFunctionalAtomCount()){ throw new ComponentGenerationException("Too many hydrogen for the number of positions on non carboxylic acid"); } for (int i = 0; i< numberToRemove; i++) { Atom functionalAtom = suffixableFragment.removeFunctionalAtom(0).getAtom(); functionalAtom.neutraliseCharge(); } } } private void applyDefaultLocantsToSuffixesIfApplicable(Element group, Fragment suffixableFragment) { String defaultLocantsAtrValue = group.getAttributeValue(SUFFIXAPPLIESTOBYDEFAULT_ATR); if (defaultLocantsAtrValue != null){ String[] suffixInstructions = MATCH_COMMA.split(defaultLocantsAtrValue); int firstIdInFragment = suffixableFragment.getIdOfFirstAtom(); Element suffix = OpsinTools.getNextNonChargeSuffix(group); for (String suffixInstruction : suffixInstructions) { if (suffix !=null){ suffix.addAttribute(new Attribute(DEFAULTLOCANTID_ATR, Integer.toString(firstIdInFragment + Integer.parseInt(suffixInstruction) -1))); suffix = OpsinTools.getNextNonChargeSuffix(suffix); } } } } /** * Processes the effects of the suffixAppliesTo attribute * @param group * @param suffixes * @param suffixableFragment * @throws ComponentGenerationException */ private void processSuffixAppliesTo(Element group, List<Element> suffixes, Fragment suffixableFragment) throws ComponentGenerationException { //suffixAppliesTo attribute contains instructions for number/positions of suffix //this is of the form comma sepeated ids with the number of ids corresponding to the number of instances of the suffix Element suffix =OpsinTools.getNextNonChargeSuffix(group); if (suffix ==null){ if (group.getAttributeValue(TYPE_ATR).equals(ACIDSTEM_TYPE_VAL)){ throw new ComponentGenerationException("No suffix where suffix was expected"); } } else{ if (suffixes.size()>1 && group.getAttributeValue(TYPE_ATR).equals(ACIDSTEM_TYPE_VAL)){ throw new ComponentGenerationException("More than one suffix detected on trivial polyAcid. Not believed to be allowed"); } String suffixInstruction =group.getAttributeValue(SUFFIXAPPLIESTO_ATR); String[] suffixInstructions = MATCH_COMMA.split(suffixInstruction); if (CYCLEFORMER_SUBTYPE_VAL.equals(suffix.getAttributeValue(SUBTYPE_ATR))){ if (suffixInstructions.length !=2){ throw new ComponentGenerationException("suffix: " + suffix.getValue() + " used on an inappropriate group"); } suffix.addAttribute(new Attribute(LOCANTID_ATR, suffixInstruction)); return; } boolean symmetricSuffixes =true; if (suffix.getAttribute(ADDITIONALVALUE_ATR)!=null){//handles amic, aldehydic, anilic and amoyl suffixes properly if (suffixInstructions.length < 2){ throw new ComponentGenerationException("suffix: " + suffix.getValue() + " used on an inappropriate group"); } symmetricSuffixes = false; } int firstIdInFragment=suffixableFragment.getIdOfFirstAtom(); if (suffix.getAttribute(LOCANT_ATR)==null){ suffix.addAttribute(new Attribute(LOCANTID_ATR, Integer.toString(firstIdInFragment + Integer.parseInt(suffixInstructions[0]) -1))); } for (int i = 1; i < suffixInstructions.length; i++) { Element newSuffix = new Element(SUFFIX_EL); if (symmetricSuffixes){ newSuffix.addAttribute(new Attribute(VALUE_ATR, suffix.getAttributeValue(VALUE_ATR))); newSuffix.addAttribute(new Attribute(TYPE_ATR, suffix.getAttributeValue(TYPE_ATR))); if (suffix.getAttribute(SUBTYPE_ATR)!=null){ newSuffix.addAttribute(new Attribute(SUBTYPE_ATR, suffix.getAttributeValue(SUBTYPE_ATR))); } if (suffix.getAttribute(INFIX_ATR)!=null && suffix.getAttributeValue(INFIX_ATR).startsWith("=")){//clone infixes that effect double bonds but not single bonds e.g. maleamidate still should have one functional atom newSuffix.addAttribute(new Attribute(INFIX_ATR, suffix.getAttributeValue(INFIX_ATR))); } } else{ newSuffix.addAttribute(new Attribute(VALUE_ATR, suffix.getAttributeValue(ADDITIONALVALUE_ATR))); newSuffix.addAttribute(new Attribute(TYPE_ATR, ROOT_EL)); } newSuffix.addAttribute(new Attribute(LOCANTID_ATR, Integer.toString(firstIdInFragment + Integer.parseInt(suffixInstructions[i]) -1))); XOMTools.insertAfter(suffix, newSuffix); suffixes.add(newSuffix); } } } /**Processes a suffix and returns any fragment the suffix intends to add to the molecule * @param suffixes The suffix elements for a fragment. * @param frag The fragment to which the suffix will be applied * @return An arrayList containing the generated fragments * @throws StructureBuildingException If the suffixes can't be resolved properly. * @throws ComponentGenerationException */ private List<Fragment> resolveGroupAddingSuffixes(List<Element> suffixes, Fragment frag) throws StructureBuildingException, ComponentGenerationException { List<Fragment> suffixFragments =new ArrayList<Fragment>(); String groupType = frag.getType(); String subgroupType = frag.getSubType(); String suffixTypeToUse =null; if (suffixRules.isGroupTypeWithSpecificSuffixRules(groupType)){ suffixTypeToUse =groupType; } else{ suffixTypeToUse = STANDARDGROUP_TYPE_VAL; } for (Element suffix : suffixes) { String suffixValue = suffix.getAttributeValue(VALUE_ATR); boolean cyclic;//needed for addSuffixPrefixIfNonePresentAndCyclic rule Atom atomLikelyToBeUsedBySuffix = null; String locant = suffix.getAttributeValue(LOCANT_ATR); String locantId = suffix.getAttributeValue(LOCANTID_ATR); if (locant != null && locant.indexOf(',') == -1) { atomLikelyToBeUsedBySuffix = frag.getAtomByLocant(locant); } else if (locantId != null && locantId.indexOf(',') == -1) { atomLikelyToBeUsedBySuffix = frag.getAtomByIDOrThrow(Integer.parseInt(locantId)); } if (atomLikelyToBeUsedBySuffix==null){ //a locant has not been specified //also can happen in the cases of things like fused rings where the final numbering is not available so lookup by locant fails (in which case all the atoms will be cyclic anyway) atomLikelyToBeUsedBySuffix = frag.getFirstAtom(); } cyclic = atomLikelyToBeUsedBySuffix.getAtomIsInACycle(); Elements suffixRuleTags = suffixRules.getSuffixRuleTags(suffixTypeToUse, suffixValue, subgroupType); Fragment suffixFrag = null; /* * Temp fragments are build for each addGroup rule and then merged into suffixFrag */ for (int j = 0; j < suffixRuleTags.size(); j++) { Element suffixRuleTag = suffixRuleTags.get(j); String suffixRuleTagName = suffixRuleTag.getLocalName(); if (suffixRuleTagName.equals(SUFFIXRULES_ADDGROUP_EL)) { String labels = NONE_LABELS_VAL; if (suffixRuleTag.getAttribute(SUFFIXRULES_LABELS_ATR) != null) { labels = suffixRuleTag.getAttributeValue(SUFFIXRULES_LABELS_ATR); } suffixFrag = state.fragManager.buildSMILES(suffixRuleTag.getAttributeValue(SUFFIXRULES_SMILES_ATR), SUFFIX_TYPE_VAL, SUFFIX_SUBTYPE_VAL, labels); List<Atom> atomList = suffixFrag.getAtomList(); if (suffixRuleTag.getAttribute(SUFFIXRULES_FUNCTIONALIDS_ATR) != null) { String[] relativeIdsOfFunctionalAtoms = MATCH_COMMA.split(suffixRuleTag.getAttributeValue(SUFFIXRULES_FUNCTIONALIDS_ATR)); for (String relativeId : relativeIdsOfFunctionalAtoms) { int atomIndice = Integer.parseInt(relativeId) -1; if (atomIndice >=atomList.size()){ throw new StructureBuildingException("Check suffixRules.xml: Atom requested to have a functionalAtom was not within the suffix fragment"); } suffixFrag.addFunctionalAtom(atomList.get(atomIndice)); } } if (suffixRuleTag.getAttribute(SUFFIXRULES_OUTIDS_ATR) != null) { String[] relativeIdsOfOutAtoms = MATCH_COMMA.split(suffixRuleTag.getAttributeValue(SUFFIXRULES_OUTIDS_ATR)); for (String relativeId : relativeIdsOfOutAtoms) { int atomIndice = Integer.parseInt(relativeId) -1; if (atomIndice >=atomList.size()){ throw new StructureBuildingException("Check suffixRules.xml: Atom requested to have a outAtom was not within the suffix fragment"); } suffixFrag.addOutAtom(atomList.get(atomIndice), 1 , true); } } } else if (suffixRuleTagName.equals(SUFFIXRULES_ADDSUFFIXPREFIXIFNONEPRESENTANDCYCLIC_EL)){ if (cyclic && suffix.getAttribute(SUFFIXPREFIX_ATR)==null){ suffix.addAttribute(new Attribute(SUFFIXPREFIX_ATR, suffixRuleTag.getAttributeValue(SUFFIXRULES_SMILES_ATR))); } } else if (suffixRuleTagName.equals(SUFFIXRULES_ADDFUNCTIONALATOMSTOHYDROXYGROUPS_EL)){ if (suffixFrag != null){ throw new ComponentGenerationException("addFunctionalAtomsToHydroxyGroups is not currently compatable with the addGroup suffix rule"); } addFunctionalAtomsToHydroxyGroups(atomLikelyToBeUsedBySuffix); } else if (suffixRuleTagName.equals(SUFFIXRULES_CHARGEHYDROXYGROUPS_EL)){ if (suffixFrag != null){ throw new ComponentGenerationException("chargeHydroxyGroups is not currently compatable with the addGroup suffix rule"); } chargeHydroxyGroups(atomLikelyToBeUsedBySuffix); } else if (suffixRuleTagName.equals(SUFFIXRULES_REMOVETERMINALOXYGEN_EL)){ if (suffixFrag != null){ throw new ComponentGenerationException("removeTerminalOxygen is not currently compatible with the addGroup suffix rule"); } int bondOrder = Integer.parseInt(suffixRuleTag.getAttributeValue(SUFFIXRULES_ORDER_ATR)); removeTerminalOxygen(atomLikelyToBeUsedBySuffix, bondOrder); } } if (suffixFrag != null) { suffixFragments.add(suffixFrag); state.xmlFragmentMap.put(suffix, suffixFrag); } } return suffixFragments; } /**Processes any convertHydroxyGroupsToOutAtoms and convertHydroxyGroupsToPositiveCharge instructions * This is not handled as part of resolveGroupAddingSuffixes as something like carbonochloridoyl involves infix replacement * on a hydroxy that would otherwise actually be removed by this rule! * @param suffixes The suffix elements for a fragment. * @param frag The fragment to which the suffix will be applied * @throws ComponentGenerationException * @throws StructureBuildingException */ private void processRemovalOfHydroxyGroupsRules(List<Element> suffixes, Fragment frag) throws ComponentGenerationException, StructureBuildingException{ String groupType = frag.getType(); String subgroupType = frag.getSubType(); String suffixTypeToUse =null; if (suffixRules.isGroupTypeWithSpecificSuffixRules(groupType)){ suffixTypeToUse =groupType; } else{ suffixTypeToUse = STANDARDGROUP_TYPE_VAL; } for (Element suffix : suffixes) { String suffixValue = suffix.getAttributeValue(VALUE_ATR); Elements suffixRuleTags = suffixRules.getSuffixRuleTags(suffixTypeToUse, suffixValue, subgroupType); for (int j = 0; j < suffixRuleTags.size(); j++) { Element suffixRuleTag = suffixRuleTags.get(j); String suffixRuleTagName = suffixRuleTag.getLocalName(); if (suffixRuleTagName.equals(SUFFIXRULES_CONVERTHYDROXYGROUPSTOOUTATOMS_EL)){ convertHydroxyGroupsToOutAtoms(frag); } else if (suffixRuleTagName.equals(SUFFIXRULES_CONVERTHYDROXYGROUPSTOPOSITIVECHARGE_EL)){ convertHydroxyGroupsToPositiveCharge(frag); } } } } /** * Finds all hydroxy groups connected to a given atom and adds a functionalAtom to each of them * @param atom * @throws StructureBuildingException */ private void addFunctionalAtomsToHydroxyGroups(Atom atom) throws StructureBuildingException { List<Atom> neighbours = atom.getAtomNeighbours(); for (Atom neighbour : neighbours) { if (neighbour.getElement().equals("O") && neighbour.getCharge()==0 && neighbour.getAtomNeighbours().size()==1 && atom.getBondToAtomOrThrow(neighbour).getOrder()==1){ neighbour.getFrag().addFunctionalAtom(neighbour); } } } /** * Finds all hydroxy groups connected to a given atom and makes them negatively charged * @param atom * @throws StructureBuildingException */ private void chargeHydroxyGroups(Atom atom) throws StructureBuildingException { List<Atom> neighbours = atom.getAtomNeighbours(); for (Atom neighbour : neighbours) { if (neighbour.getElement().equals("O") && neighbour.getCharge()==0 && neighbour.getAtomNeighbours().size()==1 && atom.getBondToAtomOrThrow(neighbour).getOrder()==1){ neighbour.addChargeAndProtons(-1, -1); } } } /** * Removes a terminal oxygen from the atom * An exception is thrown if no suitable oxygen could be found connected to the atom * Note that [N+][O-] is treated as N=O * @param atom * @throws StructureBuildingException */ private void removeTerminalOxygen(Atom atom, int desiredBondOrder) throws StructureBuildingException { //TODO prioritise [N+][O-] List<Atom> neighbours = atom.getAtomNeighbours(); for (Atom neighbour : neighbours) { if (neighbour.getElement().equals("O") && neighbour.getAtomNeighbours().size()==1){ Bond b = atom.getBondToAtomOrThrow(neighbour); if (b.getOrder()==desiredBondOrder && neighbour.getCharge()==0){ FragmentTools.removeTerminalAtom(state, neighbour); if (atom.getLambdaConventionValency()!=null){//corrects valency for phosphin/arsin/stibin atom.setLambdaConventionValency(atom.getLambdaConventionValency()-desiredBondOrder); } if (atom.getMinimumValency()!=null){//corrects valency for phosphin/arsin/stibin atom.setMinimumValency(atom.getMinimumValency()-desiredBondOrder); } return; } else if (neighbour.getCharge() ==-1 && b.getOrder()==1 && desiredBondOrder == 2){ if (atom.getCharge() ==1 && atom.getElement().equals("N")){ FragmentTools.removeTerminalAtom(state, neighbour); atom.neutraliseCharge(); return; } } } } if (desiredBondOrder ==2){ throw new StructureBuildingException("Double bonded oxygen not found at suffix attachment position. Perhaps a suffix has been used inappropriately"); } else if (desiredBondOrder ==1){ throw new StructureBuildingException("Hydroxy oxygen not found at suffix attachment position. Perhaps a suffix has been used inappropriately"); } else { throw new StructureBuildingException("Suitable oxygen not found at suffix attachment position Perhaps a suffix has been used inappropriately"); } } /** * Given a fragment removes all hydroxy groups and adds a valency 1 outAtom to the adjacent atom for each hydroxy group * Note that O[OH] is not considered a hydroxy c.f. carbonoperoxoyl * @param frag * @throws StructureBuildingException */ private void convertHydroxyGroupsToOutAtoms(Fragment frag) throws StructureBuildingException { List<Atom> atomList = frag.getAtomList(); for (Atom atom : atomList) { if (atom.getElement().equals("O") && atom.getCharge()==0 && atom.getBonds().size()==1 && atom.getFirstBond().getOrder()==1 && atom.getOutValency() == 0){ Atom adjacentAtom = atom.getAtomNeighbours().get(0); if (!adjacentAtom.getElement().equals("O")){ state.fragManager.removeAtomAndAssociatedBonds(atom); frag.addOutAtom(adjacentAtom, 1, true); } } } } /** * Given a fragment removes all hydroxy groups and applies ylium to the adjacent atom (+1 charge -1 proton) * Note that O[OH] is not considered a hydroxy * @param frag * @throws StructureBuildingException */ private void convertHydroxyGroupsToPositiveCharge(Fragment frag) throws StructureBuildingException { List<Atom> atomList = frag.getAtomList(); for (Atom atom : atomList) { if (atom.getElement().equals("O") && atom.getCharge()==0 && atom.getBonds().size()==1 && atom.getFirstBond().getOrder()==1 && atom.getOutValency() == 0){ Atom adjacentAtom = atom.getAtomNeighbours().get(0); if (!adjacentAtom.getElement().equals("O")){ state.fragManager.removeAtomAndAssociatedBonds(atom); adjacentAtom.addChargeAndProtons(1, -1); } } } } /** * Searches for suffix elements with the suffixPrefix attribute set * A suffixPrefix is something like sulfon in sulfonamide. It would in this case take the value S(=O) * @param suffixes * @throws StructureBuildingException */ private void processSuffixPrefixes(List<Element> suffixes) throws StructureBuildingException{ for (Element suffix : suffixes) { if (suffix.getAttribute(SUFFIXPREFIX_ATR)!=null){ Fragment suffixPrefixFrag = state.fragManager.buildSMILES(suffix.getAttributeValue(SUFFIXPREFIX_ATR), SUFFIX_TYPE_VAL, NONE_LABELS_VAL); addFunctionalAtomsToHydroxyGroups(suffixPrefixFrag.getFirstAtom()); if (suffix.getValue().endsWith("ate") || suffix.getValue().endsWith("at")){ chargeHydroxyGroups(suffixPrefixFrag.getFirstAtom()); } Atom firstAtomOfPrefix = suffixPrefixFrag.getFirstAtom(); firstAtomOfPrefix.addLocant("X");//make sure this atom is not given a locant Fragment suffixFrag = state.xmlFragmentMap.get(suffix); state.fragManager.incorporateFragment(suffixPrefixFrag, suffixFrag); //manipulate suffixFrag such that all the bonds to the first atom (the R) go instead to the first atom of suffixPrefixFrag. //Then reconnect the R to that atom Atom theR = suffixFrag.getFirstAtom(); List<Atom> neighbours = theR.getAtomNeighbours(); for (Atom neighbour : neighbours) { Bond b = theR.getBondToAtomOrThrow(neighbour); state.fragManager.removeBond(b); state.fragManager.createBond(neighbour, firstAtomOfPrefix, b.getOrder()); } state.fragManager.createBond(firstAtomOfPrefix, theR, 1); } } } /** * Checks through the groups accesible from the startingElement taking into account brackets (i.e. those that it is feasible that the group of the startingElement could substitute onto). * It is assumed that one does not intentionally locant onto something in a deeper level of bracketting (not implicit bracketing). e.g. 2-propyl(ethyl)ammonia will give prop-2-yl * @param startingElement * @param locant: the locant string to check for the presence of * @return whether the locant was found * @throws StructureBuildingException */ private boolean checkLocantPresentOnPotentialRoot(Element startingElement, String locant) throws StructureBuildingException { boolean foundSibling =false; Stack<Element> s = new Stack<Element>(); s.add(startingElement); boolean doneFirstIteration =false;//check on index only done on first iteration to only get elements with an index greater than the starting element while (s.size()>0){ Element currentElement =s.pop(); Element parent = (Element)currentElement.getParent(); List<Element> siblings = XOMTools.getChildElementsWithTagNames(parent, new String[]{BRACKET_EL, SUBSTITUENT_EL, ROOT_EL}); int indexOfCurrentElement =parent.indexOf(currentElement); for (Element bracketOrSub : siblings) { if (!doneFirstIteration && parent.indexOf(bracketOrSub) <= indexOfCurrentElement){ continue; } if (bracketOrSub.getLocalName().equals(BRACKET_EL)){//only want to consider implicit brackets, not proper brackets if (bracketOrSub.getAttribute(TYPE_ATR)==null){ continue; } s.push((Element)bracketOrSub.getChild(0)); } else{ Element group = bracketOrSub.getFirstChildElement(GROUP_EL); Fragment groupFrag =state.xmlFragmentMap.get(group); if (groupFrag.hasLocant(locant)){ return true; } List<Fragment> suffixes =state.xmlSuffixMap.get(group); if (suffixes!=null){ for (Fragment suffix : suffixes) { if (suffix.hasLocant(locant)){ return true; } } } List<Element> conjunctiveGroups = XOMTools.getNextSiblingsOfType(group, CONJUNCTIVESUFFIXGROUP_EL); for (Element conjunctiveGroup : conjunctiveGroups) { if (state.xmlFragmentMap.get(conjunctiveGroup).hasLocant(locant)){ return true; } } } foundSibling =true; } doneFirstIteration =true; } if (!foundSibling){//Special case: anything the group could potentially substitute onto is in a bracket. The bracket is checked recursively s = new Stack<Element>(); s.add(startingElement); doneFirstIteration =false;//check on index only done on first iteration to only get elements with an index greater than the starting element while (s.size()>0){ Element currentElement =s.pop(); Element parent = (Element)currentElement.getParent(); List<Element> siblings = XOMTools.getChildElementsWithTagNames(parent, new String[]{BRACKET_EL, SUBSTITUENT_EL, ROOT_EL}); int indexOfCurrentElement =parent.indexOf(currentElement); for (Element bracketOrSub : siblings) { if (!doneFirstIteration && parent.indexOf(bracketOrSub) <= indexOfCurrentElement){ continue; } if (bracketOrSub.getLocalName().equals(BRACKET_EL)){ s.push((Element)bracketOrSub.getChild(0)); } else{ Element group = bracketOrSub.getFirstChildElement(GROUP_EL); Fragment groupFrag =state.xmlFragmentMap.get(group); if (groupFrag.hasLocant(locant)){ return true; } List<Fragment> suffixes =state.xmlSuffixMap.get(group); if (suffixes!=null){ for (Fragment suffix : suffixes) { if (suffix.hasLocant(locant)){ return true; } } } List<Element> conjunctiveGroups = XOMTools.getNextSiblingsOfType(group, CONJUNCTIVESUFFIXGROUP_EL); for (Element conjunctiveGroup : conjunctiveGroups) { if (state.xmlFragmentMap.get(conjunctiveGroup).hasLocant(locant)){ return true; } } } } doneFirstIteration =true; } } return false; } /** Handles special cases in IUPAC nomenclature that are most elegantly solved by modification of the fragment * @param groups * @throws StructureBuildingException * @throws ComponentGenerationException */ private void handleGroupIrregularities(List<Element> groups) throws StructureBuildingException, ComponentGenerationException{ for (Element group : groups) { String groupValue =group.getValue(); if (groupValue.equals("porphyrin")|| groupValue.equals("porphin")){ List<Element> hydrogenAddingEls = XOMTools.getChildElementsWithTagName((Element) group.getParent(), INDICATEDHYDROGEN_EL); boolean implicitHydrogenExplicitlySet =false; for (Element hydrogenAddingEl : hydrogenAddingEls) { String locant = hydrogenAddingEl.getAttributeValue(LOCANT_ATR); if (locant !=null && (locant.equals("21") || locant.equals("22") || locant.equals("23") || locant.equals("24"))){ implicitHydrogenExplicitlySet =true; } } if (!implicitHydrogenExplicitlySet){ //porphyrins implicitly have indicated hydrogen at the 21/23 positions //directly modify the fragment to avoid problems with locants in for example ring assemblies Fragment frag =state.xmlFragmentMap.get(group); frag.getAtomByLocantOrThrow("21").setSpareValency(false); frag.getAtomByLocantOrThrow("23").setSpareValency(false); } } else if (groupValue.equals("xanthate") || groupValue.equals("xanthic acid") || groupValue.equals("xanthicacid")){ //This test needs to be here rather in the ComponentGenerator to correctly reject non substituted thioxanthates Element wordRule = OpsinTools.getParentWordRule(group); if (wordRule.getAttributeValue(WORDRULE_ATR).equals(WordRule.simple.toString())){ if (XOMTools.getDescendantElementsWithTagName(wordRule, SUBSTITUENT_EL).size()==0){ throw new ComponentGenerationException(groupValue +" describes a class of compounds rather than a particular compound"); } } } } } /** * Handles Hantzsch-Widman rings. Adds SMILES to the group corresponding to the ring's structure * @param subOrRoot * @throws StructureBuildingException * @throws ComponentGenerationException */ private void processHW(Element subOrRoot) throws StructureBuildingException, ComponentGenerationException{ List<Element> hwGroups = XOMTools.getChildElementsWithTagNameAndAttribute(subOrRoot, GROUP_EL, SUBTYPE_ATR, HANTZSCHWIDMAN_SUBTYPE_VAL); for (Element group : hwGroups) { Fragment hwRing =state.xmlFragmentMap.get(group); List<Atom> atomList =hwRing.getAtomList(); Element prev = (Element) XOMTools.getPreviousSibling(group); ArrayList<Element> prevs = new ArrayList<Element>(); boolean noLocants = true; while(prev != null && prev.getLocalName().equals(HETEROATOM_EL)) { prevs.add(prev); if(prev.getAttribute(LOCANT_ATR) != null) { noLocants = false; } prev = (Element) XOMTools.getPreviousSibling(prev); } if (atomList.size() == 6 && group.getValue().equals("an")){ boolean hasNitrogen = false; boolean hasSiorGeorSnorPb=false; boolean saturatedRing =true; for(Element heteroatom : prevs){ String heteroAtomElement =heteroatom.getAttributeValue(VALUE_ATR); Matcher m = MATCH_ELEMENT_SYMBOL.matcher(heteroAtomElement); if (!m.find()){ throw new ComponentGenerationException("Failed to extract element from HW heteroatom"); } heteroAtomElement = m.group(); if (heteroAtomElement.equals("N")){ hasNitrogen=true; } if (heteroAtomElement.equals("Si") || heteroAtomElement.equals("Ge") || heteroAtomElement.equals("Sn") || heteroAtomElement.equals("Pb") ){ hasSiorGeorSnorPb =true; } } for (Atom a: atomList) { if (a.hasSpareValency()){ saturatedRing =false; } } if (saturatedRing && !hasNitrogen && hasSiorGeorSnorPb){ throw new ComponentGenerationException("Blocked HW system (6 member saturated ring with no nitrogen but has Si/Ge/Sn/Pb)"); } } StringBuilder nameSB = new StringBuilder(); Collections.reverse(prevs); for(Element heteroatom : prevs){ nameSB.append(heteroatom.getValue()); } nameSB.append(group.getValue()); String name = nameSB.toString().toLowerCase(); if(noLocants && prevs.size() > 0) { if(specialHWRings.containsKey(name)) { String[] specialRingInformation =specialHWRings.get(name); String specialInstruction =specialRingInformation[0]; if (!specialInstruction.equals("")){ if (specialInstruction.equals("blocked")){ throw new ComponentGenerationException("Blocked HW system"); } else if (specialInstruction.equals("saturated")){ for (Atom a: hwRing.getAtomList()) { a.setSpareValency(false); } } else if (specialInstruction.equals("not_icacid")){ if (group.getAttribute(SUBSEQUENTUNSEMANTICTOKEN_ATR)==null){ Element nextEl = (Element) XOMTools.getNextSibling(group); if (nextEl!=null && nextEl.getLocalName().equals(SUFFIX_EL) && nextEl.getAttribute(LOCANT_ATR)==null && nextEl.getAttributeValue(VALUE_ATR).equals("ic")){ throw new ComponentGenerationException(name + nextEl.getValue() +" appears to be a generic class name, not a HW ring"); } } } else if (specialInstruction.equals("not_nothingOrOlate")){ if (group.getAttribute(SUBSEQUENTUNSEMANTICTOKEN_ATR)==null){ Element nextEl = (Element) XOMTools.getNextSibling(group); if (nextEl==null || (nextEl!=null && nextEl.getLocalName().equals(SUFFIX_EL) && nextEl.getAttribute(LOCANT_ATR)==null && nextEl.getAttributeValue(VALUE_ATR).equals("ate"))){ throw new ComponentGenerationException(name +" has the syntax for a HW ring but probably does not mean that in this context"); } } } else{ throw new ComponentGenerationException("OPSIN Bug: Unrecognised special HW ring instruction"); } } //something like oxazole where by convention locants go 1,3 or a inorganic HW-like system for (int j = 1; j < specialRingInformation.length; j++) { Atom a =hwRing.getAtomByLocantOrThrow(Integer.toString(j)); a.setElement(specialRingInformation[j]); } for(Element p : prevs){ p.detach(); } prevs.clear(); } } HashSet<Element> elementsToRemove =new HashSet<Element>(); for(Element heteroatom : prevs){//add locanted heteroatoms if (heteroatom.getAttribute(LOCANT_ATR) !=null){ String locant =heteroatom.getAttributeValue(LOCANT_ATR); String elementReplacement =heteroatom.getAttributeValue(VALUE_ATR); Matcher m = MATCH_ELEMENT_SYMBOL.matcher(elementReplacement); if (!m.find()){ throw new ComponentGenerationException("Failed to extract element from HW heteroatom"); } elementReplacement = m.group(); Atom a =hwRing.getAtomByLocantOrThrow(locant); a.setElement(elementReplacement); if (heteroatom.getAttribute(LAMBDA_ATR)!=null){ a.setLambdaConventionValency(Integer.parseInt(heteroatom.getAttributeValue(LAMBDA_ATR))); } heteroatom.detach(); elementsToRemove.add(heteroatom); } } for(Element p : elementsToRemove){ prevs.remove(p); } //add unlocanted heteroatoms int defaultLocant=1; for(Element heteroatom : prevs){ String elementReplacement =heteroatom.getAttributeValue(VALUE_ATR); Matcher m = MATCH_ELEMENT_SYMBOL.matcher(elementReplacement); if (!m.find()){ throw new ComponentGenerationException("Failed to extract element from HW heteroatom"); } elementReplacement = m.group(); while (!hwRing.getAtomByLocantOrThrow(Integer.toString(defaultLocant)).getElement().equals("C")){ defaultLocant++; } Atom a =hwRing.getAtomByLocantOrThrow(Integer.toString(defaultLocant)); a.setElement(elementReplacement); if (heteroatom.getAttribute(LAMBDA_ATR)!=null){ a.setLambdaConventionValency(Integer.parseInt(heteroatom.getAttributeValue(LAMBDA_ATR))); } heteroatom.detach(); } Elements deltas = subOrRoot.getChildElements(DELTA_EL);//add specified double bonds for (int j = 0; j < deltas.size(); j++) { String locantOfDoubleBond = deltas.get(j).getValue(); if (locantOfDoubleBond.equals("")){ Element newUnsaturator = new Element(UNSATURATOR_EL); newUnsaturator.addAttribute(new Attribute(VALUE_ATR, "2")); XOMTools.insertAfter(group, newUnsaturator); } else{ Atom firstInDoubleBond = hwRing.getAtomByLocantOrThrow(locantOfDoubleBond); Atom secondInDoubleBond = hwRing.getAtomByIDOrThrow(firstInDoubleBond.getID() +1); Bond b = firstInDoubleBond.getBondToAtomOrThrow(secondInDoubleBond); b.setOrder(2); } deltas.get(j).detach(); } XOMTools.setTextChild(group, name); } } /** * Assigns Element symbols to groups, suffixes and conjunctive suffixes. * Suffixes have preference. * @param subOrRoot * @throws StructureBuildingException */ private void assignElementSymbolLocants(Element subOrRoot) throws StructureBuildingException { List<Element> groups = XOMTools.getChildElementsWithTagName(subOrRoot, GROUP_EL); Element lastGroupElementInSubOrRoot =groups.get(groups.size()-1); List<Fragment> suffixFragments = new ArrayList<Fragment>(state.xmlSuffixMap.get(lastGroupElementInSubOrRoot)); Fragment suffixableFragment =state.xmlFragmentMap.get(lastGroupElementInSubOrRoot); //treat conjunctive suffixesas if they were suffixes List<Element> conjunctiveGroups = XOMTools.getChildElementsWithTagName(subOrRoot, CONJUNCTIVESUFFIXGROUP_EL); for (Element group : conjunctiveGroups) { suffixFragments.add(state.xmlFragmentMap.get(group)); } FragmentTools.assignElementLocants(suffixableFragment, suffixFragments); for (int i = groups.size()-2; i>=0; i FragmentTools.assignElementLocants(state.xmlFragmentMap.get(groups.get(i)), new ArrayList<Fragment>()); } } /** * Processes constructs such as biphenyl, 1,1':4',1''-Terphenyl, 2,2'-Bipyridylium, m-Quaterphenyl * @param subOrRoot * @throws ComponentGenerationException * @throws StructureBuildingException */ private void processRingAssemblies(Element subOrRoot) throws ComponentGenerationException, StructureBuildingException { List<Element> ringAssemblyMultipliers = XOMTools.getChildElementsWithTagName(subOrRoot, RINGASSEMBLYMULTIPLIER_EL); for (Element multiplier : ringAssemblyMultipliers) { int mvalue = Integer.parseInt(multiplier.getAttributeValue(VALUE_ATR)); /* * Populate locants with locants. Two locants are required for every pair of rings to be joined. * e.g. bi requires 2, ter requires 4 etc. */ List<List<String>> ringJoiningLocants =new ArrayList<List<String>>(); Element potentialLocant =(Element)XOMTools.getPreviousSibling(multiplier); Element group =(Element)XOMTools.getNextSibling(multiplier, GROUP_EL); if (potentialLocant!=null && (potentialLocant.getLocalName().equals(COLONORSEMICOLONDELIMITEDLOCANT_EL)||potentialLocant.getLocalName().equals(LOCANT_EL)) ){//a locant appears to have been provided to indicate how to connect the rings of the ringAssembly if (ORTHOMETAPARA_TYPE_VAL.equals(potentialLocant.getAttributeValue(TYPE_ATR))){//an OMP locant has been provided to indicate how to connect the rings of the ringAssembly String locant2 =potentialLocant.getValue(); String locant1 ="1"; ArrayList<String> locantArrayList =new ArrayList<String>(); locantArrayList.add("1"); locantArrayList.add("1'"); ringJoiningLocants.add(locantArrayList); for (int j = 1; j < mvalue -1; j++) { locantArrayList =new ArrayList<String>(); locantArrayList.add(locant2 + StringTools.multiplyString("'", j)); locantArrayList.add(locant1 + StringTools.multiplyString("'", j+1)); ringJoiningLocants.add(locantArrayList); } potentialLocant.detach(); } else{ String locantText =StringTools.removeDashIfPresent(potentialLocant.getValue()); //locantText might be something like 1,1':3',1'' String[] perRingLocantArray = MATCH_COLONORSEMICOLON.split(locantText); if (perRingLocantArray.length !=(mvalue -1)){ throw new ComponentGenerationException("Disagreement between number of locants(" + locantText +") and ring assembly multiplier: " + mvalue); } if (perRingLocantArray.length!=1 || MATCH_COMMA.split(perRingLocantArray[0]).length!=1){//not for the case of a single locant for (int j = 0; j < perRingLocantArray.length; j++) { String[] locantArray = MATCH_COMMA.split(perRingLocantArray[j]); if (locantArray.length !=2){ throw new ComponentGenerationException("missing locant, expected 2 locants: " + perRingLocantArray[j]); } ringJoiningLocants.add(Arrays.asList(locantArray)); } potentialLocant.detach(); } } } Fragment fragmentToResolveAndDuplicate =state.xmlFragmentMap.get(group); Element elementToResolve;//temporary element containing elements that should be resolved before the ring is duplicated Element nextEl =(Element) XOMTools.getNextSibling(multiplier); if (nextEl.getLocalName().equals(STRUCTURALOPENBRACKET_EL)){//brackets have been provided to aid disambiguation. These brackets are detached e.g. bi(cyclohexyl) elementToResolve = new Element(SUBSTITUENT_EL); Element currentEl =nextEl; nextEl = (Element) XOMTools.getNextSibling(currentEl); currentEl.detach(); while (nextEl !=null && !nextEl.getLocalName().equals(STRUCTURALCLOSEBRACKET_EL)){ currentEl =nextEl; nextEl = (Element) XOMTools.getNextSibling(currentEl); currentEl.detach(); elementToResolve.appendChild(currentEl); } if (nextEl!=null){ nextEl.detach(); } } else{ elementToResolve = determineElementsToResolveIntoRingAssembly(multiplier, ringJoiningLocants.size(), fragmentToResolveAndDuplicate.getOutAtomCount()); } List<Element> suffixes = XOMTools.getChildElementsWithTagName(elementToResolve, SUFFIX_EL); resolveSuffixes(group, suffixes); StructureBuildingMethods.resolveLocantedFeatures(state, elementToResolve); StructureBuildingMethods.resolveUnLocantedFeatures(state, elementToResolve); group.detach(); XOMTools.insertAfter(multiplier, group); int bondOrder = 1; if (fragmentToResolveAndDuplicate.getOutAtomCount()>0){//e.g. bicyclohexanylidene bondOrder =fragmentToResolveAndDuplicate.getOutAtom(0).getValency(); } if (fragmentToResolveAndDuplicate.getOutAtomCount()>1){ throw new StructureBuildingException("Ring assembly fragment should have one or no OutAtoms; not more than one!"); } List<Fragment> clonedFragments = new ArrayList<Fragment>(); for (int j = 1; j < mvalue; j++) { clonedFragments.add(state.fragManager.copyAndRelabelFragment(fragmentToResolveAndDuplicate, j)); } for (int j = 0; j < mvalue-1; j++) { Fragment clone =clonedFragments.get(j); Atom atomOnParent; Atom atomOnLatestClone; if (ringJoiningLocants.size()>0){//locants defined atomOnParent = fragmentToResolveAndDuplicate.getAtomByLocantOrThrow(ringJoiningLocants.get(j).get(0)); String secondLocant = ringJoiningLocants.get(j).get(1); if (mvalue ==2 && !secondLocant.endsWith("'")){ //Allow prime to be (incorrectly) omitted on second locant in bi ring assemblies e.g. 2,2-bipyridine try { atomOnLatestClone = clone.getAtomByLocantOrThrow(secondLocant); } catch (StructureBuildingException e){ atomOnLatestClone = clone.getAtomByLocant(secondLocant + "'"); if (atomOnLatestClone == null){ throw e; } } } else{ atomOnLatestClone = clone.getAtomByLocantOrThrow(secondLocant); } } else{ if (fragmentToResolveAndDuplicate.getOutAtomCount()>0 && mvalue==2){ atomOnParent = fragmentToResolveAndDuplicate.getOutAtom(0).getAtom(); atomOnLatestClone = clone.getOutAtom(0).getAtom(); } else{ atomOnParent =fragmentToResolveAndDuplicate.getAtomOrNextSuitableAtomOrThrow(fragmentToResolveAndDuplicate.getDefaultInAtom(), bondOrder, true); atomOnLatestClone = clone.getAtomOrNextSuitableAtomOrThrow(clone.getDefaultInAtom(), bondOrder, true); } } if (fragmentToResolveAndDuplicate.getOutAtomCount()>0){ fragmentToResolveAndDuplicate.removeOutAtom(0); } if (clone.getOutAtomCount()>0){ clone.removeOutAtom(0); } state.fragManager.incorporateFragment(clone, atomOnLatestClone, fragmentToResolveAndDuplicate, atomOnParent, bondOrder); fragmentToResolveAndDuplicate.setDefaultInAtom(clone.getDefaultInAtom()); } XOMTools.setTextChild(group, multiplier.getValue() +group.getValue()); Element possibleOpenStructuralBracket = (Element) XOMTools.getPreviousSibling(multiplier); if (possibleOpenStructuralBracket!=null && possibleOpenStructuralBracket.getLocalName().equals(STRUCTURALOPENBRACKET_EL)){//e.g. [2,2'-bipyridin]. //To emphasise there can actually be two sets of structural brackets e.g. [1,1'-bi(cyclohexyl)] XOMTools.getNextSibling(possibleOpenStructuralBracket, STRUCTURALCLOSEBRACKET_EL).detach(); possibleOpenStructuralBracket.detach(); } multiplier.detach(); } } /** * Given the element after the ring assembly multiplier determines which siblings should be resolved by adding them to elementToResolve * @param ringJoiningLocants * @param elementAfterMultiplier * @param elementToResolve * @return * @throws ComponentGenerationException */ private Element determineElementsToResolveIntoRingAssembly(Element multiplier, int ringJoiningLocants, int outAtomCount) throws ComponentGenerationException { Element elementToResolve = new Element(SUBSTITUENT_EL); boolean groupFound = false; boolean inlineSuffixSeen = outAtomCount > 0; Element currentEl = (Element) XOMTools.getNextSibling(multiplier); while (currentEl !=null){ Element nextEl = (Element) XOMTools.getNextSibling(currentEl); if (!groupFound || currentEl.getLocalName().equals(SUFFIX_EL) && currentEl.getAttributeValue(TYPE_ATR).equals(CHARGE_TYPE_VAL)|| currentEl.getLocalName().equals(UNSATURATOR_EL)){ currentEl.detach(); elementToResolve.appendChild(currentEl); } else if (currentEl.getLocalName().equals(SUFFIX_EL)){ state.xmlFragmentMap.get(currentEl); if (!inlineSuffixSeen && currentEl.getAttributeValue(TYPE_ATR).equals(INLINE_TYPE_VAL) && currentEl.getAttributeValue(MULTIPLIED_ATR) ==null && (currentEl.getAttribute(LOCANT_ATR)==null || ("2".equals(multiplier.getAttributeValue(VALUE_ATR)) && ringJoiningLocants==0)) && state.xmlFragmentMap.get(currentEl)==null){ inlineSuffixSeen = true; currentEl.detach(); elementToResolve.appendChild(currentEl); } else{ break; } } else{ break; } if (currentEl.getLocalName().equals(GROUP_EL)){ groupFound = true; } currentEl = nextEl; } Element parent = (Element) multiplier.getParent(); if (!parent.getLocalName().equals(SUBSTITUENT_EL) && XOMTools.getChildElementsWithTagNameAndAttribute(parent, SUFFIX_EL, TYPE_ATR, INLINE_TYPE_VAL).size()!=0){ throw new ComponentGenerationException("Unexpected radical adding suffix on ring assembly"); } return elementToResolve; } private void processPolyCyclicSpiroNomenclature(Element subOrRoot) throws ComponentGenerationException, StructureBuildingException { List<Element> polyCyclicSpiros = XOMTools.getChildElementsWithTagName(subOrRoot, POLYCYCLICSPIRO_EL); if (polyCyclicSpiros.size()>0){ Element polyCyclicSpiroDescriptor = polyCyclicSpiros.get(0); String value = polyCyclicSpiroDescriptor.getAttributeValue(VALUE_ATR); if (value.equals("spiro")){ if (polyCyclicSpiros.size()!=1){ throw new ComponentGenerationException("Nested polyspiro systems are not supported"); } processNonIdenticalPolyCyclicSpiro(polyCyclicSpiroDescriptor); } else if (value.equals("spiroOldMethod")){ processOldMethodPolyCyclicSpiro(polyCyclicSpiros); } else if (value.equals("spirobi")){ if (polyCyclicSpiros.size()!=1){ throw new ComponentGenerationException("Nested polyspiro systems are not supported"); } processSpiroBiOrTer(polyCyclicSpiroDescriptor, 2); } else if (value.equals("spiroter")){ if (polyCyclicSpiros.size()!=1){ throw new ComponentGenerationException("Nested polyspiro systems are not supported"); } processSpiroBiOrTer(polyCyclicSpiroDescriptor, 3); } else if (value.equals("dispiroter")){ if (polyCyclicSpiros.size()!=1){ throw new ComponentGenerationException("Nested polyspiro systems are not supported"); } processDispiroter(polyCyclicSpiroDescriptor); } else{ throw new ComponentGenerationException("Unsupported spiro system encountered"); } polyCyclicSpiroDescriptor.detach(); } } private void processNonIdenticalPolyCyclicSpiro(Element polyCyclicSpiroDescriptor) throws ComponentGenerationException, StructureBuildingException { Element subOrRoot = (Element) polyCyclicSpiroDescriptor.getParent(); List<Element> groups = XOMTools.getChildElementsWithTagName(subOrRoot, GROUP_EL); if (groups.size()<2){ throw new ComponentGenerationException("OPSIN Bug: Atleast two groups were expected in polycyclic spiro system"); } Element openBracket = (Element) XOMTools.getNextSibling(polyCyclicSpiroDescriptor); if (!openBracket.getLocalName().equals(STRUCTURALOPENBRACKET_EL)){ throw new ComponentGenerationException("OPSIN Bug: Open bracket not found where open bracket expeced"); } List<Element> spiroBracketElements = XOMTools.getSiblingsUpToElementWithTagName(openBracket, STRUCTURALCLOSEBRACKET_EL); Element closeBracket = (Element) XOMTools.getNextSibling(spiroBracketElements.get(spiroBracketElements.size()-1)); if (closeBracket == null || !closeBracket.getLocalName().equals(STRUCTURALCLOSEBRACKET_EL)){ throw new ComponentGenerationException("OPSIN Bug: Open bracket not found where open bracket expeced"); } Element firstGroup = groups.get(0); List<Element> firstGroupEls = new ArrayList<Element>(); int indexOfOpenBracket = subOrRoot.indexOf(openBracket); int indexOfFirstGroup = subOrRoot.indexOf(firstGroup); for (int i =indexOfOpenBracket +1; i < indexOfFirstGroup; i++) { firstGroupEls.add((Element) subOrRoot.getChild(i)); } firstGroupEls.add(firstGroup); firstGroupEls.addAll(XOMTools.getNextAdjacentSiblingsOfType(firstGroup, UNSATURATOR_EL)); resolveFeaturesOntoGroup(firstGroupEls); Set<Atom> spiroAtoms = new HashSet<Atom>(); for (int i = 1; i < groups.size(); i++) { Element nextGroup =groups.get(i); Element locant = (Element) XOMTools.getNextSibling(groups.get(i-1), SPIROLOCANT_EL); if (locant ==null){ throw new ComponentGenerationException("Unable to find locantEl for polycyclic spiro system"); } List<Element> nextGroupEls = new ArrayList<Element>(); int indexOfLocant = subOrRoot.indexOf(locant); int indexOfNextGroup = subOrRoot.indexOf(nextGroup); for (int j =indexOfLocant +1; j < indexOfNextGroup; j++) { nextGroupEls.add((Element) subOrRoot.getChild(j)); } nextGroupEls.add(nextGroup); nextGroupEls.addAll(XOMTools.getNextAdjacentSiblingsOfType(nextGroup, UNSATURATOR_EL)); resolveFeaturesOntoGroup(nextGroupEls); String[] locants = MATCH_COMMA.split(StringTools.removeDashIfPresent(locant.getValue())); if (locants.length!=2){ throw new ComponentGenerationException("Incorrect number of locants found before component of polycyclic spiro system"); } for (int j = 0; j < locants.length; j++) { String locantText= locants[j]; Matcher m = matchAddedHydrogenBracket.matcher(locantText); if (m.find()){ Element addedHydrogenElement=new Element(ADDEDHYDROGEN_EL); addedHydrogenElement.addAttribute(new Attribute(LOCANT_ATR, m.group(1))); XOMTools.insertBefore(locant, addedHydrogenElement); locant.addAttribute(new Attribute(TYPE_ATR, ADDEDHYDROGENLOCANT_TYPE_VAL)); locants[j] = m.replaceAll(""); } } locant.detach(); Fragment nextFragment = state.xmlFragmentMap.get(nextGroup); FragmentTools.relabelNumericLocants(nextFragment.getAtomList(), StringTools.multiplyString("'", i)); Atom atomToBeReplaced = nextFragment.getAtomByLocantOrThrow(locants[1]); Atom atomOnParentFrag = null; for (int j = 0; j < i; j++) { atomOnParentFrag = state.xmlFragmentMap.get(groups.get(j)).getAtomByLocant(locants[0]); if (atomOnParentFrag!=null){ break; } } if (atomOnParentFrag==null){ throw new ComponentGenerationException("Could not find the atom with locant " + locants[0] +" for use in polycyclic spiro system"); } spiroAtoms.add(atomOnParentFrag); state.fragManager.replaceAtomWithAnotherAtomPreservingConnectivity(atomToBeReplaced, atomOnParentFrag); if (atomToBeReplaced.hasSpareValency()){ atomOnParentFrag.setSpareValency(true); } } if (spiroAtoms.size()>1){ Element expectedMultiplier = (Element) XOMTools.getPreviousSibling(polyCyclicSpiroDescriptor); if (expectedMultiplier!=null && expectedMultiplier.getLocalName().equals(MULTIPLIER_EL) && Integer.parseInt(expectedMultiplier.getAttributeValue(VALUE_ATR))==spiroAtoms.size()){ expectedMultiplier.detach(); } } Element rootGroup = groups.get(groups.size()-1); Fragment rootFrag = state.xmlFragmentMap.get(rootGroup); String name = rootGroup.getValue(); for (int i = 0; i < groups.size() -1; i++) { Element group =groups.get(i); state.fragManager.incorporateFragment(state.xmlFragmentMap.get(group), rootFrag); name = group.getValue() + name; group.detach(); } XOMTools.setTextChild(rootGroup, polyCyclicSpiroDescriptor.getValue() + name); openBracket.detach(); closeBracket.detach(); } /** * Processes spiro systems described using the now deprectated method described in the 1979 guidelines Rule A-42 * @param spiroElements * @throws ComponentGenerationException * @throws StructureBuildingException */ private void processOldMethodPolyCyclicSpiro(List<Element> spiroElements) throws ComponentGenerationException, StructureBuildingException { Element firstSpiro =spiroElements.get(0); Element subOrRoot = (Element) firstSpiro.getParent(); Element firstEl = (Element) subOrRoot.getChild(0); List<Element> elementsToResolve = XOMTools.getSiblingsUpToElementWithTagName(firstEl, POLYCYCLICSPIRO_EL); elementsToResolve.add(0, firstEl); resolveFeaturesOntoGroup(elementsToResolve); for (int i = 0; i < spiroElements.size(); i++) { Element currentSpiro = spiroElements.get(i); Element previousGroup = (Element) XOMTools.getPreviousSibling(currentSpiro, GROUP_EL); if (previousGroup==null){ throw new ComponentGenerationException("OPSIN bug: unable to locate group before polycylic spiro descriptor"); } Element nextGroup = (Element) XOMTools.getNextSibling(currentSpiro, GROUP_EL); if (nextGroup==null){ throw new ComponentGenerationException("OPSIN bug: unable to locate group after polycylic spiro descriptor"); } Fragment parentFrag = state.xmlFragmentMap.get(nextGroup); Fragment previousFrag = state.xmlFragmentMap.get(previousGroup); FragmentTools.relabelNumericLocants(parentFrag.getAtomList(), StringTools.multiplyString("'",i+1)); elementsToResolve = XOMTools.getSiblingsUpToElementWithTagName(currentSpiro, POLYCYCLICSPIRO_EL); resolveFeaturesOntoGroup(elementsToResolve); String locant1 =null; Element possibleFirstLocant = (Element) XOMTools.getPreviousSibling(currentSpiro); if (possibleFirstLocant !=null && possibleFirstLocant.getLocalName().equals(LOCANT_EL)){ if (MATCH_COMMA.split(possibleFirstLocant.getValue()).length==1){ locant1 = possibleFirstLocant.getValue(); possibleFirstLocant.detach(); } else{ throw new ComponentGenerationException("Malformed locant before polycyclic spiro descriptor"); } } Atom atomToBeReplaced; if (locant1 != null){ atomToBeReplaced = previousFrag.getAtomByLocantOrThrow(locant1); } else{ atomToBeReplaced = previousFrag.getAtomOrNextSuitableAtomOrThrow(previousFrag.getFirstAtom(), 2, true); } Atom atomOnParentFrag; String locant2 =null; Element possibleSecondLocant = (Element) XOMTools.getNextSibling(currentSpiro); if (possibleSecondLocant !=null && possibleSecondLocant.getLocalName().equals(LOCANT_EL)){ if (MATCH_COMMA.split(possibleSecondLocant.getValue()).length==1){ locant2 = possibleSecondLocant.getValue(); possibleSecondLocant.detach(); } else{ throw new ComponentGenerationException("Malformed locant after polycyclic spiro descriptor"); } } if (locant2!=null){ atomOnParentFrag = parentFrag.getAtomByLocantOrThrow(locant2); } else{ atomOnParentFrag = parentFrag.getAtomOrNextSuitableAtomOrThrow(parentFrag.getFirstAtom(), 2, true); } state.fragManager.replaceAtomWithAnotherAtomPreservingConnectivity(atomToBeReplaced, atomOnParentFrag); if (atomToBeReplaced.hasSpareValency()){ atomOnParentFrag.setSpareValency(true); } if (atomToBeReplaced.getCharge()!=0 && atomOnParentFrag.getCharge()==0){ atomOnParentFrag.setCharge(atomToBeReplaced.getCharge()); atomOnParentFrag.setProtonsExplicitlyAddedOrRemoved(atomToBeReplaced.getProtonsExplicitlyAddedOrRemoved()); } state.fragManager.incorporateFragment(previousFrag, parentFrag); XOMTools.setTextChild(nextGroup, previousGroup.getValue() + currentSpiro.getValue() + nextGroup.getValue()); previousGroup.detach(); } } /** * Two or three copies of the fragment after polyCyclicSpiroDescriptor are spiro fused at one centre * @param polyCyclicSpiroDescriptor * @param components * @throws ComponentGenerationException * @throws StructureBuildingException */ private void processSpiroBiOrTer(Element polyCyclicSpiroDescriptor, int components) throws ComponentGenerationException, StructureBuildingException { Element locant = (Element) XOMTools.getPreviousSibling(polyCyclicSpiroDescriptor); String locantText; if (locant ==null || !locant.getLocalName().equals(LOCANT_EL)){ if (components==2){ locantText ="1,1'"; } else{ throw new ComponentGenerationException("Unable to find locant indicating atoms to form polycyclic spiro system!"); } } else{ locantText = locant.getValue(); locant.detach(); } String[] locants = MATCH_COMMA.split(locantText); if (locants.length!=components){ throw new ComponentGenerationException("Mismatch between spiro descriptor and number of locants provided"); } Element group = (Element) XOMTools.getNextSibling(polyCyclicSpiroDescriptor, GROUP_EL); if (group==null){ throw new ComponentGenerationException("Cannot find group to which spirobi/ter descriptor applies"); } determineFeaturesToResolveInSingleComponentSpiro(polyCyclicSpiroDescriptor); Fragment fragment = state.xmlFragmentMap.get(group); List<Fragment> clones = new ArrayList<Fragment>(); for (int i = 1; i < components ; i++) { clones.add(state.fragManager.copyAndRelabelFragment(fragment, i)); } for (Fragment clone : clones) { state.fragManager.incorporateFragment(clone, fragment); } Atom atomOnOriginalFragment = fragment.getAtomByLocantOrThrow(locants[0]); for (int i = 1; i < components ; i++) { Atom atomToBeReplaced = fragment.getAtomByLocantOrThrow(locants[i]); state.fragManager.replaceAtomWithAnotherAtomPreservingConnectivity(atomToBeReplaced, atomOnOriginalFragment); if (atomToBeReplaced.hasSpareValency()){ atomOnOriginalFragment.setSpareValency(true); } } XOMTools.setTextChild(group, polyCyclicSpiroDescriptor.getValue() + group.getValue()); } /** * Three copies of the fragment after polyCyclicSpiroDescriptor are spiro fused at two centres * @param polyCyclicSpiroDescriptor * @throws StructureBuildingException * @throws ComponentGenerationException */ private void processDispiroter(Element polyCyclicSpiroDescriptor) throws StructureBuildingException, ComponentGenerationException { String value = polyCyclicSpiroDescriptor.getValue(); value = value.substring(0, value.length()-10);//remove dispiroter value = StringTools.removeDashIfPresent(value); String[] locants = MATCH_COLON.split(value); Element group = (Element) XOMTools.getNextSibling(polyCyclicSpiroDescriptor, GROUP_EL); if (group==null){ throw new ComponentGenerationException("Cannot find group to which dispiroter descriptor applies"); } determineFeaturesToResolveInSingleComponentSpiro(polyCyclicSpiroDescriptor); Fragment fragment = state.xmlFragmentMap.get(group); List<Fragment> clones = new ArrayList<Fragment>(); for (int i = 1; i < 3 ; i++) { clones.add(state.fragManager.copyAndRelabelFragment(fragment, i)); } for (Fragment clone : clones) { state.fragManager.incorporateFragment(clone, fragment); } Atom atomOnLessPrimedFragment = fragment.getAtomByLocantOrThrow(MATCH_COMMA.split(locants[0])[0]); Atom atomToBeReplaced = fragment.getAtomByLocantOrThrow(MATCH_COMMA.split(locants[0])[1]); state.fragManager.replaceAtomWithAnotherAtomPreservingConnectivity(atomToBeReplaced, atomOnLessPrimedFragment); if (atomToBeReplaced.hasSpareValency()){ atomOnLessPrimedFragment.setSpareValency(true); } atomOnLessPrimedFragment = fragment.getAtomByLocantOrThrow(MATCH_COMMA.split(locants[1])[0]); atomToBeReplaced = fragment.getAtomByLocantOrThrow(MATCH_COMMA.split(locants[1])[1]); state.fragManager.replaceAtomWithAnotherAtomPreservingConnectivity(atomToBeReplaced, atomOnLessPrimedFragment); if (atomToBeReplaced.hasSpareValency()){ atomOnLessPrimedFragment.setSpareValency(true); } XOMTools.setTextChild(group, "dispiroter" + group.getValue()); } /** * The features between the polyCyclicSpiroDescriptor and the first group element, or beween the STRUCTURALOPENBRACKET_EL and STRUCTURALCLOSEBRACKET_EL * are found and then passed to resolveFeaturesOntoGroup * @param polyCyclicSpiroDescriptor * @throws StructureBuildingException * @throws ComponentGenerationException */ private void determineFeaturesToResolveInSingleComponentSpiro(Element polyCyclicSpiroDescriptor) throws StructureBuildingException, ComponentGenerationException { Element possibleOpenBracket = (Element) XOMTools.getNextSibling(polyCyclicSpiroDescriptor); List<Element> elementsToResolve; if (possibleOpenBracket.getLocalName().equals(STRUCTURALOPENBRACKET_EL)){ possibleOpenBracket.detach(); elementsToResolve = XOMTools.getSiblingsUpToElementWithTagName(polyCyclicSpiroDescriptor, STRUCTURALCLOSEBRACKET_EL); XOMTools.getNextSibling(elementsToResolve.get(elementsToResolve.size()-1)).detach();//detach close bracket } else{ elementsToResolve = XOMTools.getSiblingsUpToElementWithTagName(polyCyclicSpiroDescriptor, GROUP_EL); } resolveFeaturesOntoGroup(elementsToResolve); } /** * Given some elements including a group element resolves all locanted and unlocanted features. * If suffixes are present these are resolved and detached * @param elementsToResolve * @throws StructureBuildingException * @throws ComponentGenerationException */ private void resolveFeaturesOntoGroup(List<Element> elementsToResolve) throws StructureBuildingException, ComponentGenerationException{ if (elementsToResolve.size()==0){ return; } Element substituentToResolve = new Element(SUBSTITUENT_EL);//temporary element containing elements that should be resolved before the ring is cloned Element parent = (Element) elementsToResolve.get(0).getParent(); int index = parent.indexOf(elementsToResolve.get(0)); Element group =null; List<Element> suffixes = new ArrayList<Element>(); Element locant =null; for (Element element : elementsToResolve) { String elName =element.getLocalName(); if (elName.equals(GROUP_EL)){ group = element; } else if (elName.equals(SUFFIX_EL)){ suffixes.add(element); } else if (elName.equals(LOCANT_EL) && group==null){ locant = element; } element.detach(); substituentToResolve.appendChild(element); } if (group ==null){ throw new ComponentGenerationException("OPSIN bug: group element should of been given to method"); } if (locant !=null){//locant is probably an indirect locant, try and assign it List<Element> locantAble = findElementsMissingIndirectLocants(substituentToResolve, locant); String[] locantValues = MATCH_COMMA.split(locant.getValue()); if (locantAble.size() >= locantValues.length){ for (int i = 0; i < locantValues.length; i++) { String locantValue = locantValues[i]; locantAble.get(i).addAttribute(new Attribute(LOCANT_ATR, locantValue)); } locant.detach(); } } if (!suffixes.isEmpty()){ resolveSuffixes(group, suffixes); for (Element suffix : suffixes) { suffix.detach(); } } if (substituentToResolve.getChildElements().size()!=0){ StructureBuildingMethods.resolveLocantedFeatures(state, substituentToResolve); StructureBuildingMethods.resolveUnLocantedFeatures(state, substituentToResolve); Elements children = substituentToResolve.getChildElements(); for (int i = children.size() -1; i>=0; i Element child = children.get(i); child.detach(); parent.insertChild(child, index); } } } /** * Processes bridges e.g. 4,7-methanoindene * Resolves and attaches said bridges to the adjacent ring fragment * @param subOrRoot * @throws StructureBuildingException */ private void processFusedRingBridges(Element subOrRoot) throws StructureBuildingException { List<Element> bridges = XOMTools.getChildElementsWithTagName(subOrRoot, FUSEDRINGBRIDGE_EL); for (Element bridge : bridges) { Fragment ringFrag = state.xmlFragmentMap.get(XOMTools.getNextSibling(bridge, GROUP_EL)); Fragment bridgeFrag =state.fragManager.buildSMILES(bridge.getAttributeValue(VALUE_ATR), ringFrag.getType(), ringFrag.getSubType(), NONE_LABELS_VAL);//TODO label bridges List<Atom> bridgeAtomList =bridgeFrag.getAtomList(); bridgeFrag.addOutAtom(bridgeAtomList.get(0), 1, true); bridgeFrag.addOutAtom(bridgeAtomList.get(bridgeAtomList.size()-1), 1, true); Element possibleLocant = (Element) XOMTools.getPreviousSibling(bridge); if (possibleLocant !=null && possibleLocant.getLocalName().equals(LOCANT_EL)){ String[] locantArray = MATCH_COMMA.split(possibleLocant.getValue()); if (locantArray.length==2){ bridgeFrag.getOutAtom(0).setLocant(locantArray[0]); bridgeFrag.getOutAtom(1).setLocant(locantArray[1]); possibleLocant.detach(); } StructureBuildingMethods.formEpoxide(state, bridgeFrag, ringFrag.getDefaultInAtom()); } else{ StructureBuildingMethods.formEpoxide(state, bridgeFrag, ringFrag.getAtomOrNextSuitableAtomOrThrow(ringFrag.getDefaultInAtom(), 1, true)); } state.fragManager.incorporateFragment(bridgeFrag, ringFrag); bridge.detach(); } } /** * Searches for lambdaConvention elements and applies the valency they specify to the atom * they specify on the substituent/root's fragment * @param subOrRoot * @throws StructureBuildingException */ private void applyLambdaConvention(Element subOrRoot) throws StructureBuildingException { List<Element> lambdaConventionEls = XOMTools.getChildElementsWithTagName(subOrRoot, LAMBDACONVENTION_EL); for (Element lambdaConventionEl : lambdaConventionEls) { Fragment frag = state.xmlFragmentMap.get(subOrRoot.getFirstChildElement(GROUP_EL)); if (lambdaConventionEl.getAttribute(LOCANT_ATR)!=null){ frag.getAtomByLocantOrThrow(lambdaConventionEl.getAttributeValue(LOCANT_ATR)).setLambdaConventionValency(Integer.parseInt(lambdaConventionEl.getAttributeValue(LAMBDA_ATR))); } else{ if (frag.getAtomCount()!=1){ throw new StructureBuildingException("Ambiguous use of lambda convention. Fragment has more than 1 atom but no locant was specified for the lambda"); } frag.getFirstAtom().setLambdaConventionValency(Integer.parseInt(lambdaConventionEl.getAttributeValue(LAMBDA_ATR))); } lambdaConventionEl.detach(); } } /** * Uses the number of outAtoms that are present to assign the number of outAtoms on substituents that can have a variable number of outAtoms * Hence at this point it can be determined if a multi radical susbtituent is present in the name * This would be expected in multiplicative nomenclature and is noted in the state so that the StructureBuilder knows to resolve the * section of the name from that point onwards in a left to right manner rather than right to left * @param subOrRoot: The sub/root to look in * @throws ComponentGenerationException * @throws StructureBuildingException */ private void handleMultiRadicals(Element subOrRoot) throws ComponentGenerationException, StructureBuildingException{ Element group =subOrRoot.getFirstChildElement(GROUP_EL); String groupValue =group.getValue(); Fragment thisFrag = state.xmlFragmentMap.get(group); if (groupValue.equals("methylene") || groupValue.equals("oxy")|| matchChalcogenReplacement.matcher(groupValue).matches()){//resolves for example trimethylene to propan-1,3-diyl or dithio to disulfan-1,2-diyl. Locants may not be specified before the multiplier Element beforeGroup =(Element) XOMTools.getPreviousSibling(group); if (beforeGroup!=null && beforeGroup.getLocalName().equals(MULTIPLIER_ATR) && beforeGroup.getAttributeValue(TYPE_ATR).equals(BASIC_TYPE_VAL) && XOMTools.getPreviousSibling(beforeGroup)==null){ int multiplierVal = Integer.parseInt(beforeGroup.getAttributeValue(VALUE_ATR)); if (!unsuitableForFormingChainMultiradical(group, beforeGroup)){ if (groupValue.equals("methylene")){ group.getAttribute(VALUE_ATR).setValue(StringTools.multiplyString("C", multiplierVal)); } else if (groupValue.equals("oxy")){ group.getAttribute(VALUE_ATR).setValue(StringTools.multiplyString("O", multiplierVal)); } else if (groupValue.equals("thio")){ group.getAttribute(VALUE_ATR).setValue(StringTools.multiplyString("S", multiplierVal)); } else if (groupValue.equals("seleno")){ group.getAttribute(VALUE_ATR).setValue(StringTools.multiplyString("[SeH?]", multiplierVal)); } else if (groupValue.equals("telluro")){ group.getAttribute(VALUE_ATR).setValue(StringTools.multiplyString("[TeH?]", multiplierVal)); } else{ throw new ComponentGenerationException("unexpected group value"); } group.getAttribute(OUTIDS_ATR).setValue("1,"+Integer.parseInt(beforeGroup.getAttributeValue(VALUE_ATR))); XOMTools.setTextChild(group, beforeGroup.getValue() + groupValue); beforeGroup.detach(); if (group.getAttribute(LABELS_ATR)!=null){//use numeric numbering group.getAttribute(LABELS_ATR).setValue(NUMERIC_LABELS_VAL); } else{ group.addAttribute(new Attribute(LABELS_ATR, NUMERIC_LABELS_VAL)); } state.fragManager.removeFragment(thisFrag); thisFrag =resolveGroup(state, group); state.xmlFragmentMap.put(group, thisFrag); group.removeAttribute(group.getAttribute(USABLEASJOINER_ATR)); } } } if (group.getAttribute(OUTIDS_ATR)!=null){//adds outIDs at the specified atoms String[] radicalPositions = MATCH_COMMA.split(group.getAttributeValue(OUTIDS_ATR)); int firstIdInFrag =thisFrag.getIdOfFirstAtom(); for (String radicalID : radicalPositions) { thisFrag.addOutAtom(firstIdInFrag + Integer.parseInt(radicalID) - 1, 1, true); } } int outAtomCount = thisFrag.getOutAtomCount(); if (outAtomCount >=2){ if (groupValue.equals("amine")){//amine is a special case as it shouldn't technically be allowed but is allowed due to it's common usage in EDTA Element previousGroup =(Element) OpsinTools.getPreviousGroup(group); Element nextGroup =(Element) OpsinTools.getNextGroup(group); if (previousGroup==null || state.xmlFragmentMap.get(previousGroup).getOutAtomCount() < 2 || nextGroup==null){//must be preceded by a multi radical throw new ComponentGenerationException("Invalid use of amine as a substituent!"); } } if (state.currentWordRule == WordRule.polymer){ if (outAtomCount >=3){//In poly mode nothing may have more than 2 outAtoms e.g. nitrilo is -N= or =N- int valency =0; for (int i = 2; i < outAtomCount; i++) { OutAtom nextOutAtom = thisFrag.getOutAtom(i); valency += nextOutAtom.getValency(); thisFrag.removeOutAtom(nextOutAtom); } thisFrag.getOutAtom(1).setValency(thisFrag.getOutAtom(1).getValency() + valency); } } } if (outAtomCount ==2 && EPOXYLIKE_SUBTYPE_VAL.equals(group.getAttributeValue(SUBTYPE_ATR))){ Element possibleLocant =(Element) XOMTools.getPreviousSibling(group); if (possibleLocant !=null){ String[] locantValues = MATCH_COMMA.split(possibleLocant.getValue()); if (locantValues.length==2){ thisFrag.getOutAtom(0).setLocant(locantValues[0]); thisFrag.getOutAtom(1).setLocant(locantValues[1]); possibleLocant.detach(); subOrRoot.addAttribute(new Attribute(LOCANT_ATR, locantValues[0])); } } } int totalOutAtoms = outAtomCount + calculateOutAtomsToBeAddedFromInlineSuffixes(group, subOrRoot.getChildElements(SUFFIX_EL)); if (totalOutAtoms >= 2){ group.addAttribute(new Attribute (ISAMULTIRADICAL_ATR, Integer.toString(totalOutAtoms))); } } /** * Checks for cases where multiplier(methylene) or multiplier(thio) and the like should not be interpreted as one fragment * Something like nitrilotrithiotriacetic acid or oxetane-3,3-diyldimethylene * @param group * @param multiplierBeforeGroup * @return */ private boolean unsuitableForFormingChainMultiradical(Element group, Element multiplierBeforeGroup) { Element previousGroup = (Element) OpsinTools.getPreviousGroup(group); if (previousGroup!=null){ if (previousGroup.getAttribute(ISAMULTIRADICAL_ATR)!=null){ if (previousGroup.getAttributeValue(ACCEPTSADDITIVEBONDS_ATR)!=null && XOMTools.getPreviousSibling(previousGroup.getParent())!=null){ return false; } //the initial multiplier is proceded by another multiplier e.g. bis(dithio) if (((Element)XOMTools.getPrevious(multiplierBeforeGroup)).getLocalName().equals(MULTIPLIER_EL)){ return false; } if (previousGroup.getAttributeValue(ISAMULTIRADICAL_ATR).equals(multiplierBeforeGroup.getAttributeValue(VALUE_ATR))){ return true;//probably multiplicative } else{ return false; } } else if (XOMTools.getPreviousSibling(previousGroup, MULTIPLIER_EL)==null){ //This is a 99% solution to the detection of cases such as ethylidenedioxy == ethan-1,1-diyldioxy Fragment previousGroupFrag =state.xmlFragmentMap.get(previousGroup); int outAtomValency =0; if (previousGroupFrag.getOutAtomCount()==1){ outAtomValency = previousGroupFrag.getOutAtom(0).getValency(); } else{ Element suffix = (Element) XOMTools.getNextSibling(previousGroup, SUFFIX_EL); if (suffix!=null && suffix.getAttributeValue(VALUE_ATR).equals("ylidene")){ outAtomValency =2; } if (suffix!=null && suffix.getAttributeValue(VALUE_ATR).equals("ylidyne")){ outAtomValency =3; } } if (outAtomValency==Integer.parseInt(multiplierBeforeGroup.getAttributeValue(VALUE_ATR))){ return true; } } } return false; } /** * Calculates number of OutAtoms that the resolveSuffixes method will add. * @param group * @param suffixes * @return numberOfOutAtoms that will be added by resolveSuffixes * @throws ComponentGenerationException */ private int calculateOutAtomsToBeAddedFromInlineSuffixes(Element group, Elements suffixes) throws ComponentGenerationException { int outAtomsThatWillBeAdded = 0; Fragment frag = state.xmlFragmentMap.get(group); String groupType = frag.getType(); String subgroupType = frag.getSubType(); String suffixTypeToUse =null; if (suffixRules.isGroupTypeWithSpecificSuffixRules(groupType)){ suffixTypeToUse =groupType; } else{ suffixTypeToUse = STANDARDGROUP_TYPE_VAL; } List<Fragment> suffixList =state.xmlSuffixMap.get(group); for (Fragment suffix : suffixList) { outAtomsThatWillBeAdded += suffix.getOutAtomCount(); } for(int i=0;i<suffixes.size();i++) { Element suffix = suffixes.get(i); String suffixValue = suffix.getAttributeValue(VALUE_ATR); Elements suffixRuleTags = suffixRules.getSuffixRuleTags(suffixTypeToUse, suffixValue, subgroupType); for(int j=0;j<suffixRuleTags.size();j++) { Element suffixRuleTag = suffixRuleTags.get(j); String suffixRuleTagName =suffixRuleTag.getLocalName(); if(suffixRuleTagName.equals(SUFFIXRULES_SETOUTATOM_EL)) { outAtomsThatWillBeAdded +=1; } } } return outAtomsThatWillBeAdded; } /** * Corrects something like L-alanyl-L-glutaminyl-L-arginyl-O-phosphono-L-seryl-L-alanyl-L-proline to: * ((((L-alanyl-L-glutaminyl)-L-arginyl)-O-phosphono-L-seryl)-L-alanyl)-L-proline * i.e. substituents go onto the last mentioned amino acid; amino acids chain together to form peptides * @param groups * @param brackets */ private void addImplicitBracketsToAminoAcids(List<Element> groups, List<Element> brackets) { for (int i = groups.size() -1; i >=0; i Element group = groups.get(i); if (group.getAttributeValue(TYPE_ATR).equals(AMINOACID_TYPE_VAL) && OpsinTools.getNextGroup(group)!=null){ Element possibleLocant = (Element) XOMTools.getPreviousSiblingIgnoringCertainElements(group, new String[]{MULTIPLIER_EL}); if (possibleLocant != null && possibleLocant.getLocalName().equals(LOCANT_EL)){ continue; } Element subOrRoot = (Element) group.getParent(); //now find the brackets/substituents before this element Element previous = (Element) XOMTools.getPreviousSibling(subOrRoot); List<Element> previousElements = new ArrayList<Element>(); while( previous !=null){ if (!previous.getLocalName().equals(SUBSTITUENT_EL) && !previous.getLocalName().equals(BRACKET_EL)){ break; } previousElements.add(previous); previous = (Element) XOMTools.getPreviousSibling(previous); } if (previousElements.size()>0){//an implicit bracket is needed Collections.reverse(previousElements); Element bracket = new Element(BRACKET_EL); bracket.addAttribute(new Attribute(TYPE_ATR, IMPLICIT_TYPE_VAL)); Element parent = (Element) subOrRoot.getParent(); int indexToInsertAt = parent.indexOf(previousElements.get(0)); for (Element element : previousElements) { element.detach(); bracket.appendChild(element); } subOrRoot.detach(); bracket.appendChild(subOrRoot); parent.insertChild(bracket, indexToInsertAt); brackets.add(bracket); } } } } /**Looks for places where brackets should have been, and does the same * as findAndStructureBrackets. E.g. dimethylaminobenzene -> (dimethylamino)benzene. * The bracketting in the above case occurs when the substituent that is being procesed is the amino group * @param brackets * @param substituents: An arraylist of substituent elements * @return Whether the method did something, and so needs to be called again. * @throws StructureBuildingException * @throws ComponentGenerationException */ private void findAndStructureImplictBrackets(List<Element> substituents, List<Element> brackets) throws ComponentGenerationException, StructureBuildingException { for (Element substituent : substituents) {//will attempt to bracket this substituent with the substituent before it String firstElInSubName =((Element)substituent.getChild(0)).getLocalName(); if (firstElInSubName.equals(LOCANT_EL) ||firstElInSubName.equals(MULTIPLIER_EL)){ continue; } Element substituentGroup = substituent.getFirstChildElement(GROUP_EL); //Only some substituents are valid joiners (e.g. no rings are valid joiners). Need to be atleast bivalent. if (substituentGroup.getAttribute(USABLEASJOINER_ATR)==null){ continue; } //checks that the element before is a substituent or a bracket which will obviously include substituent/s //this makes sure there's more than just a substituent in the bracket Element elementBeforeSubstituent =(Element)XOMTools.getPreviousSibling(substituent); if (elementBeforeSubstituent ==null|| !elementBeforeSubstituent.getLocalName().equals(SUBSTITUENT_EL) && !elementBeforeSubstituent.getLocalName().equals(BRACKET_EL)){ continue; } Element elementAftersubstituent =(Element)XOMTools.getNextSibling(substituent); if (elementAftersubstituent != null){ //Not preceded and succeded by a bracket e.g. Not (benzyl)methyl(phenyl)amine c.f. P-16.4.1.3 (draft 2004) if (elementBeforeSubstituent.getLocalName().equals(BRACKET_EL) && !IMPLICIT_TYPE_VAL.equals(elementBeforeSubstituent.getAttributeValue(TYPE_ATR)) && elementAftersubstituent.getLocalName().equals(BRACKET_EL)){ Element firstChildElementOfElementAfterSubstituent = (Element) elementAftersubstituent.getChild(0); if ((firstChildElementOfElementAfterSubstituent.getLocalName().equals(SUBSTITUENT_EL) || firstChildElementOfElementAfterSubstituent.getLocalName().equals(BRACKET_EL)) && !((Element)XOMTools.getPrevious(firstChildElementOfElementAfterSubstituent)).getLocalName().equals(HYPHEN_EL)){ continue; } } } //there must be an element after the substituent (or the substituent is being used for locanted ester formation) for the implicit bracket to be required if (elementAftersubstituent ==null || !elementAftersubstituent.getLocalName().equals(SUBSTITUENT_EL) && !elementAftersubstituent.getLocalName().equals(BRACKET_EL) && !elementAftersubstituent.getLocalName().equals(ROOT_EL)){ if (elementAftersubstituent == null && ((Element)substituent.getParent()).getLocalName().equals(WORD_EL) && ( state.currentWordRule == WordRule.ester || state.currentWordRule == WordRule.functionalClassEster || state.currentWordRule == WordRule.multiEster || state.currentWordRule == WordRule.acetal)){ //special case to allow bracketting for locanted esters } else{ continue; } } //look for hyphen between substituents, this seems to indicate implicit bracketing was not desired e.g. dimethylaminomethane vs dimethyl-aminomethane Element elementDirectlyBeforeSubstituent = (Element) XOMTools.getPrevious(substituent.getChild(0));//can't return null as we know elementBeforeSubstituent is not null if (elementDirectlyBeforeSubstituent.getLocalName().equals(HYPHEN_EL)){ continue; } Fragment frag =state.xmlFragmentMap.get(substituentGroup); String theSubstituentSubType = substituentGroup.getAttributeValue(SUBTYPE_ATR); String theSubstituentType = substituentGroup.getAttributeValue(TYPE_ATR); //prevents alkyl chains being bracketed together e.g. ethylmethylamine //...unless it's something like 2-methylethyl where the first appears to be locanted onto the second List<Element> groupElements = XOMTools.getDescendantElementsWithTagName(elementBeforeSubstituent, GROUP_EL);//one for a substituent, possibly more for a bracket Element lastGroupOfElementBeforeSub =groupElements.get(groupElements.size()-1); if (lastGroupOfElementBeforeSub==null){throw new ComponentGenerationException("No group where group was expected");} if (theSubstituentType.equals(CHAIN_TYPE_VAL) && theSubstituentSubType.equals(ALKANESTEM_SUBTYPE_VAL) && lastGroupOfElementBeforeSub.getAttributeValue(TYPE_ATR).equals(CHAIN_TYPE_VAL) && lastGroupOfElementBeforeSub.getAttributeValue(SUBTYPE_ATR).equals(ALKANESTEM_SUBTYPE_VAL)){ boolean placeInImplicitBracket =false; Element suffixAfterGroup=(Element)XOMTools.getNextSibling(lastGroupOfElementBeforeSub, SUFFIX_EL); //if the alkane ends in oxy, sulfinyl, sulfonyl etc. it's not a pure alkane (other suffixes don't need to be considered as they would produce silly structures) if (suffixAfterGroup !=null && matchInlineSuffixesThatAreAlsoGroups.matcher(suffixAfterGroup.getValue()).matches()){ placeInImplicitBracket =true; } //look for locants and check whether they appear to be referring to the other chain if (!placeInImplicitBracket){ Elements childrenOfElementBeforeSubstituent =elementBeforeSubstituent.getChildElements(); Boolean foundLocantNotReferringToChain =null; for (int i = 0; i < childrenOfElementBeforeSubstituent.size(); i++) { String currentElementName = childrenOfElementBeforeSubstituent.get(i).getLocalName(); if (currentElementName.equals(LOCANT_EL)){ String locantText =childrenOfElementBeforeSubstituent.get(i).getValue(); if(!frag.hasLocant(locantText)){ foundLocantNotReferringToChain=true; break; } else{ foundLocantNotReferringToChain=false; } } else if (currentElementName.equals(STEREOCHEMISTRY_EL)){ } else{ break; } } if (foundLocantNotReferringToChain !=null && !foundLocantNotReferringToChain){//a locant was found and it appeared to refer to the other chain placeInImplicitBracket=true; } } if (!placeInImplicitBracket){ continue; } } //prevent bracketing to multi radicals unless through substitution they are likely to cease being multiradicals if (lastGroupOfElementBeforeSub.getAttribute(ISAMULTIRADICAL_ATR)!=null && lastGroupOfElementBeforeSub.getAttribute(ACCEPTSADDITIVEBONDS_ATR)==null && lastGroupOfElementBeforeSub.getAttribute(IMINOLIKE_ATR)==null){ continue; } if (substituentGroup.getAttribute(ISAMULTIRADICAL_ATR)!=null && substituentGroup.getAttribute(ACCEPTSADDITIVEBONDS_ATR)==null && substituentGroup.getAttribute(IMINOLIKE_ATR)==null){ continue; } if (lastGroupOfElementBeforeSub.getAttribute(IMINOLIKE_ATR)!=null && substituentGroup.getAttribute(IMINOLIKE_ATR)!=null){ continue;//possibly a multiplicative additive operation } //prevent bracketting perhalogeno terms if (PERHALOGENO_SUBTYPE_VAL.equals(lastGroupOfElementBeforeSub.getAttributeValue(SUBTYPE_ATR))){ continue; } /* * locant may need to be moved. This occurs when the group in elementBeforeSubstituent is not supposed to be locanted onto * theSubstituentGroup * e.g. 2-aminomethyl-1-chlorobenzene where the 2 refers to the benzene NOT the methyl */ List<Element> locantRelatedElements = new ArrayList<Element>();//sometimes moved String[] locantValues = null; ArrayList<Element> stereoChemistryElements =new ArrayList<Element>();//always moved if bracketing occurs Elements childrenOfElementBeforeSubstituent = elementBeforeSubstituent.getChildElements(); for (int i = 0; i < childrenOfElementBeforeSubstituent.size(); i++) { String currentElementName = childrenOfElementBeforeSubstituent.get(i).getLocalName(); if (currentElementName.equals(STEREOCHEMISTRY_EL)){ stereoChemistryElements.add(childrenOfElementBeforeSubstituent.get(i)); } else if (currentElementName.equals(LOCANT_EL)){ if (locantValues !=null){ break; } locantRelatedElements.add(childrenOfElementBeforeSubstituent.get(i)); locantValues = MATCH_COMMA.split(childrenOfElementBeforeSubstituent.get(i).getValue()); } else{ break; } } //either all locants will be moved, or none boolean moveLocants = false; if (locantValues!=null){ Element elAfterLocant = (Element) XOMTools.getNextSibling(locantRelatedElements.get(0)); for (String locantText : locantValues) { if (elAfterLocant !=null && elAfterLocant.getAttribute(FRONTLOCANTSEXPECTED_ATR)!=null && StringTools.arrayToList(MATCH_COMMA.split(elAfterLocant.getAttributeValue(FRONTLOCANTSEXPECTED_ATR))).contains(locantText)){ continue; } //Check the right fragment in the bracket: //if it only has 1 then assume locanted substitution onto it not intended. Or if doesn't have the required locant if (frag.getAtomCount()==1 || !frag.hasLocant(locantText) || matchElementSymbolOrAminoAcidLocant.matcher(locantText).find() || (locantValues.length ==1 && elAfterLocant.getLocalName().equals(MULTIPLIER_EL))){ if (checkLocantPresentOnPotentialRoot(substituent, locantText)){ moveLocants =true;//locant location is present elsewhere break; } else if (findElementsMissingIndirectLocants(elementBeforeSubstituent, locantRelatedElements.get(0)).size()==0 || !state.xmlFragmentMap.get(lastGroupOfElementBeforeSub).hasLocant(locantText)){ if( frag.getAtomCount()==1 && frag.hasLocant(locantText)){ //1 locant was intended to locant onto fragment with 1 atom } else{ moveLocants =true;//the fragment adjacent to the locant doesn't have this locant or doesn't need any indirect locants. Assume it will appear elsewhere later break; } } } } if (moveLocants && locantValues.length >1){ if (elAfterLocant !=null && elAfterLocant.getLocalName().equals(MULTIPLIER_EL)){ Element shouldBeAGroupOrSubOrBracket = (Element)XOMTools.getNextSiblingIgnoringCertainElements(elAfterLocant, new String[]{MULTIPLIER_EL}); if (shouldBeAGroupOrSubOrBracket !=null){ if ((shouldBeAGroupOrSubOrBracket.getLocalName().equals(GROUP_EL) && elAfterLocant.getAttributeValue(TYPE_ATR).equals(GROUP_TYPE_VAL))//e.g. 2,5-bisaminothiobenzene --> 2,5-bis(aminothio)benzene || (frag.getAtomCount()==1)//e.g. 1,3,4-trimethylthiobenzene || (matchInlineSuffixesThatAreAlsoGroups.matcher(substituentGroup.getValue()).matches())){//e.g. 4,4'-dimethoxycarbonyl-2,2'-bioxazole --> 4,4'-di(methoxycarbonyl)-2,2'-bioxazole locantRelatedElements.add(elAfterLocant);//e.g. 1,5-bis-(4-methylphenyl)sulfonyl --> 1,5-bis-((4-methylphenyl)sulfonyl) } else if (ORTHOMETAPARA_TYPE_VAL.equals(locantRelatedElements.get(0).getAttributeValue(TYPE_ATR))){//e.g. p-dimethylamino[ring] XOMTools.setTextChild(locantRelatedElements.get(0), locantValues[1]); } else{//don't bracket other complex multiplied substituents (name hasn't given enough hints if indeed bracketing was expected) continue; } } else{ moveLocants =false; } } else{ moveLocants =false; } } } Element bracket = new Element(BRACKET_EL); bracket.addAttribute(new Attribute(TYPE_ATR, IMPLICIT_TYPE_VAL)); for (Element stereoChemistryElement : stereoChemistryElements) { stereoChemistryElement.detach(); bracket.appendChild(stereoChemistryElement); } if (moveLocants){ for (Element locantElement : locantRelatedElements) { locantElement.detach(); bracket.appendChild(locantElement); } } /* * Case when a multiplier should be moved * e.g. tripropan-2-yloxyphosphane -->tri(propan-2-yloxy)phosphane or trispropan-2-ylaminophosphane --> tris(propan-2-ylamino)phosphane */ if (locantRelatedElements.size()==0){ Element possibleMultiplier =childrenOfElementBeforeSubstituent.get(0); if (possibleMultiplier.getLocalName().equals(MULTIPLIER_EL) && ( matchInlineSuffixesThatAreAlsoGroups.matcher(substituentGroup.getValue()).matches() || possibleMultiplier.getAttributeValue(TYPE_ATR).equals(GROUP_TYPE_VAL))){ Element desiredGroup = XOMTools.getNextSiblingIgnoringCertainElements(possibleMultiplier, new String[]{MULTIPLIER_EL}); if (desiredGroup !=null && desiredGroup.getLocalName().equals(GROUP_EL)){ childrenOfElementBeforeSubstituent.get(0).detach(); bracket.appendChild(childrenOfElementBeforeSubstituent.get(0)); } } } Element parent = (Element)substituent.getParent(); int startIndex=parent.indexOf(elementBeforeSubstituent); int endIndex=parent.indexOf(substituent); for(int i = 0 ; i <= (endIndex-startIndex);i++) { Node n = parent.getChild(startIndex); n.detach(); bracket.appendChild(n); } parent.insertChild(bracket, startIndex); brackets.add(bracket); } } /** * Attempts to match locants to non adjacent suffixes/unsatuators * e.g. 2-propanol, 3-furyl, 2'-Butyronaphthone * @param subOrRoot The substituent/root to look for locants in. * @throws StructureBuildingException */ private void matchLocantsToIndirectFeatures(Element subOrRoot) throws StructureBuildingException { /* Root fragments (or the root in a bracket) can have prefix-locants * that work on suffixes - (2-furyl), 2-propanol, (2-propylmethyl), (2-propyloxy), 2'-Butyronaphthone. */ List<Element> locantEls = findLocantsThatCouldBeIndirectLocants(subOrRoot); if (locantEls.size()>0){ Element group =subOrRoot.getFirstChildElement(GROUP_EL); Element lastLocant = locantEls.get(locantEls.size()-1);//the locant that may apply to an unsaturator/suffix String[] locantValues = MATCH_COMMA.split(lastLocant.getValue()); if (locantValues.length==1 && group.getAttribute(FRONTLOCANTSEXPECTED_ATR)!=null){//some trivial retained names like 2-furyl expect locants to be in front of them. For these the indirect intepretation will always be used rather than checking whether 2-(furyl) even makes sense String[] allowedLocants = MATCH_COMMA.split(group.getAttributeValue(FRONTLOCANTSEXPECTED_ATR)); for (String allowedLocant : allowedLocants) { if (locantValues[0].equals(allowedLocant)){ Element expectedSuffix =(Element) XOMTools.getNextSibling(group); if (expectedSuffix!=null && expectedSuffix.getLocalName().equals(SUFFIX_EL) && expectedSuffix.getAttribute(LOCANT_ATR)==null){ expectedSuffix.addAttribute(new Attribute(LOCANT_ATR, locantValues[0])); lastLocant.detach(); return; } break; } } } boolean allowIndirectLocants =true; if(state.currentWordRule == WordRule.multiEster && !ADDEDHYDROGENLOCANT_TYPE_VAL.equals(lastLocant.getAttributeValue(TYPE_ATR))){//special case e.g. 1-benzyl 4-butyl terephthalate (locants do not apply to yls) Element parentEl=(Element) subOrRoot.getParent(); if (parentEl.getLocalName().equals(WORD_EL) && parentEl.getAttributeValue(TYPE_ATR).equals(SUBSTITUENT_EL) && parentEl.getChildCount()==1 && locantValues.length==1 && !ORTHOMETAPARA_TYPE_VAL.equals(lastLocant.getAttributeValue(TYPE_ATR))){ allowIndirectLocants =false; } } Fragment fragmentAfterLocant =state.xmlFragmentMap.get(group); if (fragmentAfterLocant.getAtomCount()<=1){ allowIndirectLocants =false;//e.g. prevent 1-methyl as meth-1-yl is extremely unlikely to be the intended result } if (allowIndirectLocants){ /* The first locant is most likely a locant indicating where this subsituent should be attached. * If the locant cannot be found on a potential root this cannot be the case though (assuming the name is valid of course) */ if (!ADDEDHYDROGENLOCANT_TYPE_VAL.equals(lastLocant.getAttributeValue(TYPE_ATR)) && locantEls.size() ==1 && group.getAttribute(ISAMULTIRADICAL_ATR)==null && locantValues.length == 1 && checkLocantPresentOnPotentialRoot(subOrRoot, locantValues[0]) && XOMTools.getPreviousSibling(lastLocant, LOCANT_EL)==null){ return; } boolean assignableToIndirectFeatures =true; List<Element> locantAble =findElementsMissingIndirectLocants(subOrRoot, lastLocant); if (locantAble.size() < locantValues.length){ assignableToIndirectFeatures =false; } else{ for (String locantValue : locantValues) { if (!fragmentAfterLocant.hasLocant(locantValue)){//locant is not available on the group adjacent to the locant! assignableToIndirectFeatures =false; } } } if (!assignableToIndirectFeatures){//usually indicates the name will fail unless the suffix has the locant or heteroatom replacement will create the locant if (locantValues.length==1){ List<Fragment> suffixes =state.xmlSuffixMap.get(group); //I do not want to assign element locants as in locants on the suffix as I currently know of no examples where this actually occurs if (matchElementSymbolOrAminoAcidLocant.matcher(locantValues[0]).matches()){ return; } for (Fragment suffix : suffixes) { if (suffix.hasLocant(locantValues[0])){//e.g. 2'-Butyronaphthone Atom dummyRAtom =suffix.getFirstAtom(); List<Atom> neighbours =dummyRAtom.getAtomNeighbours(); Bond b =null; atomLoop: for (Atom atom : neighbours) { List<String> neighbourLocants = atom.getLocants(); for (String neighbourLocant : neighbourLocants) { if (MATCH_NUMERIC_LOCANT.matcher(neighbourLocant).matches()){ b = dummyRAtom.getBondToAtomOrThrow(atom); break atomLoop; } } } if (b!=null){ state.fragManager.removeBond(b);//the current bond between the dummy R and the suffix state.fragManager.createBond(dummyRAtom, suffix.getAtomByLocantOrThrow(locantValues[0]), b.getOrder()); lastLocant.detach(); } } } } } else{ for (int i = 0; i < locantValues.length; i++) { String locantValue = locantValues[i]; locantAble.get(i).addAttribute(new Attribute(LOCANT_ATR, locantValue)); } lastLocant.detach(); } } } } /** * Finds locants that are before a group element and not immediately followed by a multiplier * @param subOrRoot * @return */ private List<Element> findLocantsThatCouldBeIndirectLocants(Element subOrRoot) { Elements children = subOrRoot.getChildElements(); List<Element> locantEls = new ArrayList<Element>(); for (int i = 0; i < children.size(); i++) { Element el = children.get(i); if (el.getLocalName().equals(LOCANT_EL)){ Element afterLocant =(Element) XOMTools.getNextSibling(el); if (afterLocant!=null && afterLocant.getLocalName().equals(MULTIPLIER_EL)){//locant should not be followed by a multiplier. c.f. 1,2,3-tributyl 2-acetyloxypropane-1,2,3-tricarboxylate continue; } locantEls.add(el); } else if (el.getLocalName().equals(GROUP_EL)){ break; } } return locantEls; } /** * Find elements that can have indirect locants but don't currently * This requirement excludes hydro and heteroatoms as it is assumed that locants for these are always adjacent (or handled by the special HW code in the case of heteroatoms) * @param subOrRoot The subOrRoot of interest * @param locantEl the locant, only elements after it will be considered * @return An arrayList of locantable elements */ private List<Element> findElementsMissingIndirectLocants(Element subOrRoot,Element locantEl) { List<Element> locantAble = new ArrayList<Element>(); Elements childrenOfSubOrBracketOrRoot=subOrRoot.getChildElements(); for (int j = 0; j < childrenOfSubOrBracketOrRoot.size(); j++) { Element el =childrenOfSubOrBracketOrRoot.get(j); String name =el.getLocalName(); if (name.equals(SUFFIX_EL) || name.equals(UNSATURATOR_EL) || name.equals(CONJUNCTIVESUFFIXGROUP_EL)){ if (el.getAttribute(LOCANT_ATR) ==null && el.getAttribute(LOCANTID_ATR) ==null && el.getAttribute(MULTIPLIED_ATR)==null){// shouldn't already have a locant or be multiplied (should of already had locants assignd to it if that were the case) if (subOrRoot.indexOf(el)>subOrRoot.indexOf(locantEl)){ if (name.equals(SUFFIX_EL)){//check a few special cases that must not be locanted Element group = (Element) XOMTools.getPreviousSibling(el, GROUP_EL); String type = group.getAttributeValue(TYPE_ATR); if ((type.equals(ACIDSTEM_TYPE_VAL) && !CYCLEFORMER_SUBTYPE_VAL.equals(el.getAttributeValue(SUBTYPE_ATR)))|| type.equals(NONCARBOXYLICACID_TYPE_VAL) || type.equals(CHALCOGENACIDSTEM_TYPE_VAL)){ continue; } } locantAble.add(el); } } } } return locantAble; } /** * Put di-carbon modifying suffixes e.g. oic acids, aldehydes on opposite ends of chain * @param subOrRoot * @throws StructureBuildingException */ private void assignImplicitLocantsToDiTerminalSuffixes(Element subOrRoot) throws StructureBuildingException { Element terminalSuffix1 = subOrRoot.getFirstChildElement(SUFFIX_EL); if (terminalSuffix1!=null){ if (isATerminalSuffix(terminalSuffix1) && XOMTools.getNextSibling(terminalSuffix1) != null){ Element terminalSuffix2 =(Element)XOMTools.getNextSibling(terminalSuffix1); if (isATerminalSuffix(terminalSuffix2)){ Element hopefullyAChain = (Element) XOMTools.getPreviousSibling((Element)terminalSuffix1, GROUP_EL); if (hopefullyAChain != null && hopefullyAChain.getAttributeValue(TYPE_ATR).equals(CHAIN_TYPE_VAL)){ int chainLength = state.xmlFragmentMap.get(hopefullyAChain).getChainLength(); if (chainLength >=2){ terminalSuffix1.addAttribute(new Attribute(LOCANT_ATR, "1")); terminalSuffix2.addAttribute(new Attribute(LOCANT_ATR, Integer.toString(chainLength))); } } } } } } /** * Checks whether a suffix element is: * a suffix, an inline suffix OR terminal root suffix, has no current locant * @param suffix * @return */ private boolean isATerminalSuffix(Element suffix){ return suffix.getLocalName().equals(SUFFIX_EL) && suffix.getAttribute(LOCANT_ATR) == null && (suffix.getAttributeValue(TYPE_ATR).equals(INLINE_TYPE_VAL) || TERMINAL_SUBTYPE_VAL.equals(suffix.getAttributeValue(SUBTYPE_ATR))); } private void processConjunctiveNomenclature(Element subOrRoot) throws ComponentGenerationException, StructureBuildingException { List<Element> conjunctiveGroups = XOMTools.getChildElementsWithTagName(subOrRoot, CONJUNCTIVESUFFIXGROUP_EL); if (conjunctiveGroups.size()>0){ Element ringGroup = subOrRoot.getFirstChildElement(GROUP_EL); Fragment ringFrag = state.xmlFragmentMap.get(ringGroup); if (ringFrag.getOutAtomCount()!=0 ){ throw new ComponentGenerationException("OPSIN Bug: Ring fragment should have no radicals"); } List<Fragment> conjunctiveFragments = new ArrayList<Fragment>(); for (Element group : conjunctiveGroups) { Fragment frag = state.xmlFragmentMap.get(group); conjunctiveFragments.add(frag); } for (int i = 0; i < conjunctiveFragments.size(); i++) { Fragment conjunctiveFragment = conjunctiveFragments.get(i); if (conjunctiveGroups.get(i).getAttribute(LOCANT_ATR)!=null){ state.fragManager.createBond(lastNonSuffixCarbonWithSufficientValency(conjunctiveFragment), ringFrag.getAtomByLocantOrThrow(conjunctiveGroups.get(i).getAttributeValue(LOCANT_ATR)) , 1); } else{ state.fragManager.createBond(lastNonSuffixCarbonWithSufficientValency(conjunctiveFragment), ringFrag.getAtomOrNextSuitableAtomOrThrow(ringFrag.getFirstAtom(), 1, true) , 1); } state.fragManager.incorporateFragment(conjunctiveFragment, ringFrag); } } } private Atom lastNonSuffixCarbonWithSufficientValency(Fragment conjunctiveFragment) throws ComponentGenerationException { List<Atom> atomList = conjunctiveFragment.getAtomList(); for (int i = atomList.size()-1; i >=0; i Atom a = atomList.get(i); if (a.getType().equals(SUFFIX_TYPE_VAL)){ continue; } if (!a.getElement().equals("C")){ continue; } if (ValencyChecker.checkValencyAvailableForBond(a, 1)){ return a; } } throw new ComponentGenerationException("OPSIN Bug: Unable to find non suffix carbon with sufficient valency"); } /**Process the effects of suffixes upon a fragment. * Unlocanted non-terminal suffixes are not attached yet. All other suffix effects are performed * @param group The group element for the fragment to which the suffixes will be added * @param suffixes The suffix elements for a fragment. * @throws StructureBuildingException If the suffixes can't be resolved properly. * @throws ComponentGenerationException */ private void resolveSuffixes(Element group, List<Element> suffixes) throws StructureBuildingException, ComponentGenerationException { Fragment frag = state.xmlFragmentMap.get(group); int firstAtomID = frag.getIdOfFirstAtom();//typically equivalent to locant 1 List<Atom> atomList =frag.getAtomList();//this instance of atomList will not change even once suffixes are merged into the fragment int defaultAtom =0;//indice in atomList String groupType = frag.getType(); String subgroupType = frag.getSubType(); String suffixTypeToUse =null; if (suffixRules.isGroupTypeWithSpecificSuffixRules(groupType)){ suffixTypeToUse =groupType; } else{ suffixTypeToUse =STANDARDGROUP_TYPE_VAL; } List<Fragment> suffixList = state.xmlSuffixMap.get(group); for (Element suffix : suffixes) { String suffixValue = suffix.getAttributeValue(VALUE_ATR); String locant = suffix.getAttributeValue(LOCANT_ATR); String locantId = suffix.getAttributeValue(LOCANTID_ATR); int idOnParentFragToUse = 0; if (locant != null && locant.indexOf(',') == -1) { idOnParentFragToUse = frag.getIDFromLocantOrThrow(locant); } else if (locantId != null && locantId.indexOf(',') == -1) { idOnParentFragToUse = Integer.parseInt(locantId); } else if (suffix.getAttribute(DEFAULTLOCANTID_ATR) != null) { idOnParentFragToUse = Integer.parseInt(suffix.getAttributeValue(DEFAULTLOCANTID_ATR)); } else if (suffixTypeToUse.equals(ACIDSTEM_TYPE_VAL) || suffixTypeToUse.equals(NONCARBOXYLICACID_TYPE_VAL) || suffixTypeToUse.equals(CHALCOGENACIDSTEM_TYPE_VAL)) {//means that e.g. sulfonyl has an explicit outAtom idOnParentFragToUse = firstAtomID; } Fragment suffixFrag = null; Elements suffixRuleTags = suffixRules.getSuffixRuleTags(suffixTypeToUse, suffixValue, subgroupType); for (int j = 0; j < suffixRuleTags.size(); j++) { Element suffixRuleTag = suffixRuleTags.get(j); String suffixRuleTagName = suffixRuleTag.getLocalName(); if (defaultAtom >= atomList.size()) { defaultAtom = 0; } if (suffixRuleTagName.equals(SUFFIXRULES_ADDGROUP_EL)) { if (suffixFrag == null) { if (suffixList.size() <= 0) { throw new ComponentGenerationException("OPSIN Bug: Suffixlist should not be empty"); } suffixFrag = suffixList.remove(0);//take the first suffix out of the list, it should of been added in the same order that it is now being read. Atom firstAtomInSuffix = suffixFrag.getFirstAtom(); if (firstAtomInSuffix.getBonds().size() <= 0) { throw new ComponentGenerationException("OPSIN Bug: Dummy atom in suffix should have at least one bond to it"); } if (CYCLEFORMER_SUBTYPE_VAL.equals(suffix.getAttributeValue(SUBTYPE_ATR))){ processCycleFormingSuffix(suffixFrag, frag, suffix); } else{ int bondOrderRequired = firstAtomInSuffix.getIncomingValency(); Atom parentfragAtom; if (idOnParentFragToUse == 0) { if (suffixRuleTag.getAttribute(SUFFIXRULES_KETONELOCANT_ATR) != null && !atomList.get(defaultAtom).getAtomIsInACycle()) { if (defaultAtom == 0) defaultAtom = FragmentTools.findKetoneAtomIndice(frag, defaultAtom); idOnParentFragToUse = atomList.get(defaultAtom).getID(); defaultAtom++; } else { idOnParentFragToUse = atomList.get(defaultAtom).getID(); } idOnParentFragToUse = frag.getAtomOrNextSuitableAtomOrThrow(frag.getAtomByIDOrThrow(idOnParentFragToUse), bondOrderRequired, true).getID(); parentfragAtom = frag.getAtomByIDOrThrow(idOnParentFragToUse); if (FragmentTools.isCharacteristicAtom(parentfragAtom)){ throw new StructureBuildingException("No suitable atom found to attach suffix"); } } else{ parentfragAtom = frag.getAtomByIDOrThrow(idOnParentFragToUse); } //create a new bond and associate it with the suffixfrag and both atoms. Remember the suffixFrag has not been imported into the frag yet List<Bond> bonds = new ArrayList<Bond>(firstAtomInSuffix.getBonds()); for (Bond bondToSuffix : bonds) { Atom suffixAtom = bondToSuffix.getOtherAtom(firstAtomInSuffix); state.fragManager.createBond(parentfragAtom, suffixAtom, bondToSuffix.getOrder()); state.fragManager.removeBond(bondToSuffix); if (parentfragAtom.getIncomingValency()>2 && (suffixValue.equals("aldehyde") || suffixValue.equals("al")|| suffixValue.equals("aldoxime"))){//formaldehyde/methanal are excluded as they are substitutable if("X".equals(suffixAtom.getFirstLocant())){//carbaldehyde suffixAtom.setProperty(Atom.ISALDEHYDE, true); } else{ parentfragAtom.setProperty(Atom.ISALDEHYDE, true); } } } } } else{ throw new ComponentGenerationException("OPSIN bug: Suffix may only have one addgroup rule: " + suffix.getValue()); } } else if (suffixRuleTagName.equals(SUFFIXRULES_CHANGECHARGE_EL)) { int chargeChange = Integer.parseInt(suffixRuleTag.getAttributeValue(SUFFIXRULES_CHARGE_ATR)); int protonChange = Integer.parseInt(suffixRuleTag.getAttributeValue(SUFFIXRULES_PROTONS_ATR)); if (suffix.getAttribute(SUFFIXPREFIX_ATR) == null) { if (idOnParentFragToUse != 0) { frag.getAtomByIDOrThrow(idOnParentFragToUse).addChargeAndProtons(chargeChange, protonChange); } else{ applyUnlocantedChargeModification(atomList, chargeChange, protonChange); } } else {//a suffix prefixed acylium suffix if (suffixFrag == null) { throw new StructureBuildingException("OPSIN bug: ordering of elements in suffixRules.xml wrong; changeCharge found before addGroup"); } Set<Bond> bonds = state.fragManager.getInterFragmentBonds(suffixFrag); if (bonds.size() != 1) { throw new StructureBuildingException("OPSIN bug: Wrong number of bonds between suffix and group"); } for (Bond bond : bonds) { if (bond.getFromAtom().getFrag() == suffixFrag) { bond.getFromAtom().addChargeAndProtons(chargeChange, protonChange); } else { bond.getToAtom().addChargeAndProtons(chargeChange, protonChange); } } } } else if (suffixRuleTagName.equals(SUFFIXRULES_SETOUTATOM_EL)) { int outValency = suffixRuleTag.getAttribute(SUFFIXRULES_OUTVALENCY_ATR) != null ? Integer.parseInt(suffixRuleTag.getAttributeValue(SUFFIXRULES_OUTVALENCY_ATR)) : 1; if (suffix.getAttribute(SUFFIXPREFIX_ATR) == null) { if (idOnParentFragToUse != 0) { frag.addOutAtom(idOnParentFragToUse, outValency, true); } else { frag.addOutAtom(firstAtomID, outValency, false); } } else {//something like oyl on a ring, which means it is now carbonyl and the outAtom is on the suffix and not frag if (suffixFrag == null) { throw new StructureBuildingException("OPSIN bug: ordering of elements in suffixRules.xml wrong; setOutAtom found before addGroup"); } Set<Bond> bonds = state.fragManager.getInterFragmentBonds(suffixFrag); if (bonds.size() != 1) { throw new StructureBuildingException("OPSIN bug: Wrong number of bonds between suffix and group"); } for (Bond bond : bonds) { if (bond.getFromAtom().getFrag() == suffixFrag) { suffixFrag.addOutAtom(bond.getFromAtom(), outValency, true); } else { suffixFrag.addOutAtom(bond.getToAtom(), outValency, true); } } } } else if (suffixRuleTagName.equals(SUFFIXRULES_ADDSUFFIXPREFIXIFNONEPRESENTANDCYCLIC_EL)) { //already processed } else if (suffixRuleTagName.equals(SUFFIXRULES_ADDFUNCTIONALATOMSTOHYDROXYGROUPS_EL)) { //already processed } else if (suffixRuleTagName.equals(SUFFIXRULES_CHARGEHYDROXYGROUPS_EL)) { //already processed } else if (suffixRuleTagName.equals(SUFFIXRULES_REMOVETERMINALOXYGEN_EL)) { //already processed } else if (suffixRuleTagName.equals(SUFFIXRULES_CONVERTHYDROXYGROUPSTOOUTATOMS_EL)) { //already processed } else if (suffixRuleTagName.equals(SUFFIXRULES_CONVERTHYDROXYGROUPSTOPOSITIVECHARGE_EL)) { //already processed } else { throw new StructureBuildingException("Unknown suffix rule:" + suffixRuleTagName); } } if (suffixFrag != null) {//merge suffix frag and parent fragment state.fragManager.removeAtomAndAssociatedBonds(suffixFrag.getFirstAtom());//the dummy R atom Set<String> suffixLocants = new HashSet<String>(suffixFrag.getLocants()); for (String suffixLocant : suffixLocants) { if (Character.isDigit(suffixLocant.charAt(0))){//check that numeric locants do not conflict with the parent fragment e.g. hydrazide 2' with biphenyl 2' if (frag.hasLocant(suffixLocant)){ suffixFrag.getAtomByLocant(suffixLocant).removeLocant(suffixLocant); } } } state.fragManager.incorporateFragment(suffixFrag, frag); if (CYCLEFORMER_SUBTYPE_VAL.equals(suffix.getAttributeValue(SUBTYPE_ATR))){ CycleDetector.assignWhetherAtomsAreInCycles(frag); } } } } private void processCycleFormingSuffix(Fragment suffixFrag, Fragment suffixableFragment, Element suffix) throws StructureBuildingException, ComponentGenerationException { List<Atom> rAtoms = new ArrayList<Atom>(); for (Atom a : suffixFrag.getAtomList()) { if (a.getElement().equals("R")){ rAtoms.add(a); } } if (rAtoms.size() != 2){ throw new ComponentGenerationException("OPSIN bug: Incorrect number of R atoms associated with cyclic suffix"); } if (rAtoms.get(0).getBonds().size() <= 0 || rAtoms.get(1).getBonds().size() <= 0) { throw new ComponentGenerationException("OPSIN Bug: Dummy atoms in suffix should have at least one bond to them"); } Atom parentAtom1; Atom parentAtom2; String locant = suffix.getAttributeValue(LOCANT_ATR); String locantId = suffix.getAttributeValue(LOCANTID_ATR); if (locant != null){ String[] locants = MATCH_COMMA.split(locant); if (locants.length ==2){ parentAtom1 = suffixableFragment.getAtomByLocantOrThrow(locants[0]); parentAtom2 = suffixableFragment.getAtomByLocantOrThrow(locants[1]); } else if (locants.length ==1){ parentAtom1 = suffixableFragment.getAtomByLocantOrThrow("1"); parentAtom2 = suffixableFragment.getAtomByLocantOrThrow(locants[0]); } else{ throw new ComponentGenerationException("Incorrect number of locants associated with cycle forming suffix, expected 2 found: " + locants.length); } } else if (locantId !=null) { String[] locantIds = MATCH_COMMA.split(locantId); if (locantIds.length !=2){ throw new ComponentGenerationException("OPSIN bug: Should be exactly 2 locants associated with a cyclic suffix"); } int firstIdInFragment = suffixableFragment.getIdOfFirstAtom(); parentAtom1 = suffixableFragment.getAtomByIDOrThrow(firstIdInFragment + Integer.parseInt(locantIds[0]) -1); parentAtom2 = suffixableFragment.getAtomByIDOrThrow(firstIdInFragment + Integer.parseInt(locantIds[1]) -1); } else{ int chainLength = suffixableFragment.getChainLength(); if (chainLength > 1 && chainLength == suffixableFragment.getAtomCount()){ parentAtom1 = suffixableFragment.getAtomByLocantOrThrow("1"); parentAtom2 = suffixableFragment.getAtomByLocantOrThrow(String.valueOf(chainLength)); } else{ throw new ComponentGenerationException("cycle forming suffix: " + suffix.getValue() +" should be locanted!"); } } if (parentAtom1.equals(parentAtom2)){ throw new ComponentGenerationException("cycle forming suffix: " + suffix.getValue() +" attempted to form a cycle involving the same atom twice!"); } if (parentAtom2.getElement().equals("O")){//cyclic suffixes like lactone formally indicate the removal of hydroxy cf. 1979 rule 472.1 //...although in most cases they are used on structures that don't actually have a hydroxy group List<Atom> neighbours = parentAtom2.getAtomNeighbours(); if (neighbours.size()==1){ List<Atom> suffixNeighbours = rAtoms.get(1).getAtomNeighbours(); if (suffixNeighbours.size()==1 && suffixNeighbours.get(0).getElement().equals("O")){ state.fragManager.removeAtomAndAssociatedBonds(parentAtom2); parentAtom2 = neighbours.get(0); } } } makeBondsToSuffix(parentAtom1, rAtoms.get(0)); makeBondsToSuffix(parentAtom2, rAtoms.get(1)); state.fragManager.removeAtomAndAssociatedBonds(rAtoms.get(1)); } /** * Creates bonds between the parentAtom and the atoms connected to the R atoms. * Removes bonds to the R atom * @param parentAtom * @param suffixRAtom */ private void makeBondsToSuffix(Atom parentAtom, Atom suffixRAtom) { List<Bond> bonds = new ArrayList<Bond>(suffixRAtom.getBonds()); for (Bond bondToSuffix : bonds) { Atom suffixAtom = bondToSuffix.getOtherAtom(suffixRAtom); state.fragManager.createBond(parentAtom, suffixAtom, bondToSuffix.getOrder()); state.fragManager.removeBond(bondToSuffix); } } /** * Preference is given to mono cation/anions as they are expected to be more likely * Additionally, Typically if a locant has not been specified then it was intended to refer to a nitrogen even if the nitrogen is not at locant 1 e.g. isoquinolinium * Hence preference is given to nitrogen atoms and then to non carbon atoms * @param atomList * @param chargeChange * @param protonChange */ private void applyUnlocantedChargeModification(List<Atom> atomList, int chargeChange, int protonChange) { Atom likelyAtom = null; Atom possibleHeteroatom = null; Atom possibleCarbonAtom = null; Atom possibleDiOrHigherIon = null; for (Atom a : atomList) { Integer[] stableValencies = ValencyChecker.getPossibleValencies(a.getElement(), a.getCharge() + chargeChange); if (stableValencies == null) {//unstable valency so seems unlikely continue; } String element = a.getElement(); int resultantExpectedValency = (a.getLambdaConventionValency() ==null ? ValencyChecker.getDefaultValency(element) : a.getLambdaConventionValency()) + a.getProtonsExplicitlyAddedOrRemoved() + protonChange; boolean matched = false; for (Integer stableValency : stableValencies) { if (stableValency ==resultantExpectedValency){ matched =true; break; } } if (!matched){//unstable valency so seems unlikely continue; } if (protonChange <0 && StructureBuildingMethods.calculateSubstitutableHydrogenAtoms(a)<=0){ continue; } if (Math.abs(a.getCharge())==0){ if (element.equals("N")){ likelyAtom = a; break; } else if (possibleHeteroatom ==null && !element.equals("C")){ possibleHeteroatom= a; } else if (possibleCarbonAtom ==null){ possibleCarbonAtom = a; } } else if (possibleDiOrHigherIon ==null){ possibleDiOrHigherIon = a; } } if (likelyAtom == null) { if (possibleHeteroatom !=null){ likelyAtom = possibleHeteroatom; } else if (possibleCarbonAtom !=null){ likelyAtom = possibleCarbonAtom; } else if (possibleDiOrHigherIon !=null){ likelyAtom = possibleDiOrHigherIon; } else{ likelyAtom = atomList.get(0); } } likelyAtom.addChargeAndProtons(chargeChange, protonChange); } /** * Converts a biochemical linkage description e.g. (1->4) into an O[1-9] locant * If the carbohydrate is preceded by substituents these are placed into a bracket and the bracket locanted * @param substituents * @param brackets * @throws StructureBuildingException */ private void processBiochemicalLinkageDescriptors(List<Element> substituents, List<Element> brackets) throws StructureBuildingException { for (Element substituent : substituents) { List<Element> bioLinkLocants = XOMTools.getChildElementsWithTagName(substituent, BIOCHEMICALLINKAGE_EL); if (bioLinkLocants.size() > 0){ if (bioLinkLocants.size() > 1){ throw new RuntimeException("OPSIN Bug: More than 1 biochemical linkage locant associated with subsituent"); } Element bioLinkLocant = bioLinkLocants.get(0); String bioLinkLocantStr = bioLinkLocant.getValue(); bioLinkLocantStr = bioLinkLocantStr.substring(1, bioLinkLocantStr.length() -1);//strip brackets checkAndApplyFirstLocantOfBiochemicalLinkage(substituent, bioLinkLocantStr); int secondLocantStartPos = Math.max(bioLinkLocantStr.lastIndexOf('>'), bioLinkLocantStr.lastIndexOf('-')) + 1; String locantToConnectTo = bioLinkLocantStr.substring(secondLocantStartPos); Element parent = (Element) substituent.getParent(); Attribute locantAtr = new Attribute(LOCANT_ATR, "O" + locantToConnectTo); Element elementAfterSubstituent = (Element) XOMTools.getNextSibling(substituent); boolean hasAdjacentGroupToSubstitute = (elementAfterSubstituent !=null && (elementAfterSubstituent.getLocalName().equals(SUBSTITUENT_EL) || elementAfterSubstituent.getLocalName().equals(BRACKET_EL) || elementAfterSubstituent.getLocalName().equals(ROOT_EL))); /* If a biochemical is not at the end of a scope but is preceded by substituents/brackets * these are bracketted and the locant assigned to the bracket. * Else If the group is the only thing in a bracket the locant is assigned to the bracket (this is used to describe branches) * Else the locant is assigned to the substituent */ boolean bracketAdded =false; if (hasAdjacentGroupToSubstitute){ //now find the brackets/substituents before this element Element previous = (Element) XOMTools.getPreviousSibling(substituent); List<Element> previousElements = new ArrayList<Element>(); while( previous !=null){ if (!previous.getLocalName().equals(SUBSTITUENT_EL) && !previous.getLocalName().equals(BRACKET_EL)){ break; } previousElements.add(previous); previous = (Element) XOMTools.getPreviousSibling(previous); } if (previousElements.size() > 0 ){//an explicit bracket is needed Collections.reverse(previousElements); Element bracket = new Element(BRACKET_EL); bracket.addAttribute(locantAtr); int indexToInsertAt = parent.indexOf(previousElements.get(0)); for (Element element : previousElements) { element.detach(); bracket.appendChild(element); } substituent.detach(); bracket.appendChild(substituent); parent.insertChild(bracket, indexToInsertAt); brackets.add(bracket); bracketAdded = true; } } if (!bracketAdded) { Element elToAddAtrTo; if (parent.getLocalName().equals(BRACKET_EL) && !hasAdjacentGroupToSubstitute){ elToAddAtrTo = parent; } else{ elToAddAtrTo = substituent; } if (elToAddAtrTo.getAttribute(LOCANT_ATR) !=null){ throw new StructureBuildingException("Substituent with biochemical linkage descriptor should not also have a locant: " + elToAddAtrTo.getAttributeValue(LOCANT_ATR)); } elToAddAtrTo.addAttribute(locantAtr); } bioLinkLocant.detach(); } } for (Element bracket : brackets) { List<Element> bioLinkLocants = XOMTools.getChildElementsWithTagName(bracket, BIOCHEMICALLINKAGE_EL); if (bioLinkLocants.size() > 0){ if (bioLinkLocants.size() > 1){ throw new RuntimeException("OPSIN Bug: More than 1 biochemical linkage locant associated with bracket"); } Element bioLinkLocant = bioLinkLocants.get(0); Element substituent = (Element) XOMTools.getPreviousSibling(bioLinkLocant); if (substituent == null || !substituent.getLocalName().equals(SUBSTITUENT_EL)){ throw new RuntimeException("OPSIN Bug: Substituent expected before biochemical linkage locant"); } String bioLinkLocantStr = bioLinkLocant.getValue(); bioLinkLocantStr = bioLinkLocantStr.substring(1, bioLinkLocantStr.length() -1); checkAndApplyFirstLocantOfBiochemicalLinkage(substituent, bioLinkLocantStr); int secondLocantStartPos = Math.max(bioLinkLocantStr.lastIndexOf('>'), bioLinkLocantStr.lastIndexOf('-')) + 1; String locantToConnectTo = bioLinkLocantStr.substring(secondLocantStartPos); if (bracket.getAttribute(LOCANT_ATR) !=null){ throw new StructureBuildingException("Substituent with biochemical linkage descriptor should not also have a locant: " + bracket.getAttributeValue(LOCANT_ATR)); } bracket.addAttribute(new Attribute(LOCANT_ATR, "O" + locantToConnectTo)); bioLinkLocant.detach(); } } } private void checkAndApplyFirstLocantOfBiochemicalLinkage(Element substituent, String biochemicalLinkage) throws StructureBuildingException { Element group = substituent.getFirstChildElement(GROUP_EL); Fragment frag = state.xmlFragmentMap.get(group); String firstLocant = biochemicalLinkage.substring(0, biochemicalLinkage.indexOf('-')); if (group.getAttributeValue(TYPE_ATR).equals(CARBOHYDRATE_TYPE_VAL)) { Atom anomericAtom = frag.getAtomByLocantOrThrow(firstLocant); boolean anomericIsOutAtom = false; for (int i = 0; i < frag.getOutAtomCount(); i++) { if (frag.getOutAtom(i).getAtom().equals(anomericAtom)){ anomericIsOutAtom = true; } } if (!anomericIsOutAtom){ throw new StructureBuildingException("Invalid glycoside linkage descriptor. Locant: " + firstLocant + " should point to the anomeric carbon"); } } else{ Atom positionOfPhospho = frag.getAtomByLocantOrThrow("O" + firstLocant); if (positionOfPhospho.getBonds().size() !=1){ throw new StructureBuildingException(firstLocant + " should be the carbon to which a hydroxy group is attached!"); } if (frag.getOutAtomCount()==1){ Atom atomToConnect = frag.getOutAtom(0).getAtom(); state.fragManager.createBond(positionOfPhospho, atomToConnect, 1); } else{ throw new RuntimeException("OPSIN Bug: Biochemical linkage only expected on groups with 1 OutAtom"); } } if (OpsinTools.getNextGroup(group)==null){ throw new StructureBuildingException("Biochemical linkage descriptor should be followed by another biochemical: " + biochemicalLinkage); } } /** * Moves a multiplier out of a bracket if the bracket contains only one substituent * e.g. (trimethyl) --> tri(methyl). * The multiplier may have locants e.g. [N,N-bis(2-hydroxyethyl)] * This is done because OPSIN has no idea what to do with (trimethyl) as there is nothing within the scope to substitute onto! * @param brackets */ private void moveErroneouslyPositionedLocantsAndMultipliers(List<Element> brackets) { for (int i = brackets.size()-1; i >=0; i Element bracket =brackets.get(i); Elements childElements = bracket.getChildElements(); boolean hyphenPresent = false; int childCount = childElements.size(); if (childCount==2){ for (int j = childCount -1; j >=0; j if (childElements.get(j).getLocalName().equals(HYPHEN_EL)){ hyphenPresent=true; } } } if (childCount==1 || hyphenPresent && childCount==2){ Elements substituentContent = childElements.get(0).getChildElements(); if (substituentContent.size()>=2){ Element locant =null; Element multiplier =null; Element possibleMultiplier = substituentContent.get(0); if (substituentContent.get(0).getLocalName().equals(LOCANT_EL)){//probably erroneous locant locant = substituentContent.get(0); possibleMultiplier = substituentContent.get(1); } if (possibleMultiplier.getLocalName().equals(MULTIPLIER_EL)){//erroneously placed multiplier present multiplier = possibleMultiplier; } if (locant!=null){ if (multiplier==null || MATCH_COMMA.split(locant.getValue()).length == Integer.parseInt(multiplier.getAttributeValue(VALUE_ATR))){ locant.detach(); XOMTools.insertBefore(childElements.get(0), locant); } else{ continue; } } if (multiplier !=null){ multiplier.detach(); XOMTools.insertBefore(childElements.get(0), multiplier); } } } } } /** * Given the right most child of a word: * Checks whether this is multiplied e.g. methylenedibenzene * If it is then it checks for the presence of locants e.g. 4,4'-oxydibenzene which has been changed to oxy-4,4'-dibenzene * An attribute called inLocants is then added that is either INLOCANTS_DEFAULT or a comma seperated list of locants * @param rightMostElement * @throws ComponentGenerationException * @throws StructureBuildingException */ private void assignLocantsToMultipliedRootIfPresent(Element rightMostElement) throws ComponentGenerationException, StructureBuildingException { Elements multipliers = rightMostElement.getChildElements(MULTIPLIER_EL); if(multipliers.size() == 1) { Element multiplier =multipliers.get(0); if (XOMTools.getPrevious(multiplier)==null){ throw new StructureBuildingException("OPSIN bug: Unacceptable input to function"); } List<Element> locants = XOMTools.getChildElementsWithTagName(rightMostElement, MULTIPLICATIVELOCANT_EL); if (locants.size()>1){ throw new ComponentGenerationException("OPSIN bug: Only none or one multiplicative locant expected"); } int multiVal = Integer.parseInt(multiplier.getAttributeValue(VALUE_ATR)); if (locants.size()==0){ rightMostElement.addAttribute(new Attribute(INLOCANTS_ATR, INLOCANTS_DEFAULT)); } else{ Element locantEl = locants.get(0); String[] locantValues = MATCH_COMMA.split(locantEl.getValue()); if (locantValues.length == multiVal){ rightMostElement.addAttribute(new Attribute(INLOCANTS_ATR, locantEl.getValue())); locantEl.detach(); } else{ throw new ComponentGenerationException("Mismatch between number of locants and number of roots"); } } } else if (rightMostElement.getLocalName().equals(BRACKET_EL)){ assignLocantsToMultipliedRootIfPresent(((Element) rightMostElement.getChild(rightMostElement.getChildCount()-1))); } } /** * Adds an implicit bracket in the case where two locants have been given. * One for the locanting of substituent on to the next substituent and one * for the locanting of this combined substituent onto a parent group * @param substituents * @param brackets */ private void addImplicitBracketsInCaseWhereSubstituentHasTwoLocants(List<Element> substituents, List<Element> brackets) { for (Element substituent : substituents) { Element siblingSubstituent = (Element) XOMTools.getNextSibling(substituent); if (siblingSubstituent !=null && siblingSubstituent.getLocalName().equals(SUBSTITUENT_EL)){ List<Element> locants = getLocantsAtStartOfSubstituent(substituent); if (locants.size() ==2 && locantsAreSingular(locants) && getLocantsAtStartOfSubstituent(siblingSubstituent).size()==0){//e.g. 5-p-hydroxyphenyl-1,2-dithiole-3-thione Element bracket = new Element(BRACKET_EL); bracket.addAttribute(new Attribute(TYPE_ATR, IMPLICIT_TYPE_VAL)); Element parent = (Element) substituent.getParent(); int indexToInsertAt = parent.indexOf(substituent); int elementsToMove = substituent.indexOf(locants.get(0))+1; for (int i = 0; i < elementsToMove; i++) { Element locantOrStereoToMove =(Element) substituent.getChild(0); locantOrStereoToMove.detach(); bracket.appendChild(locantOrStereoToMove); } substituent.detach(); siblingSubstituent.detach(); bracket.appendChild(substituent); bracket.appendChild(siblingSubstituent); parent.insertChild(bracket, indexToInsertAt); brackets.add(bracket); } } } } /** * Retrieves the first elements of a substituent which are locants skipping over stereochemistry elements * @param substituent * @return */ private List<Element> getLocantsAtStartOfSubstituent(Element substituent) { List<Element> locants = new ArrayList<Element>(); Elements children = substituent.getChildElements(); for (int i = 0; i < children.size(); i++) { String currentElementName = children.get(i).getLocalName(); if (currentElementName.equals(LOCANT_EL)){ locants.add(children.get(i)); } else if (currentElementName.equals(STEREOCHEMISTRY_EL)){ //ignore } else{ break; } } return locants; } /** * Checks that none of the locants contain commas * @param locants * @return */ private boolean locantsAreSingular(List<Element> locants) { for (Element locant : locants) { if (MATCH_COMMA.split(locant.getValue()).length > 1){ return false; } } return true; } /** * Assigns locants and multipliers to substituents/brackets * If both locants and multipliers are present a final check is done that the number of them agree. * WordLevel multipliers are processed e.g. diethyl ethanoate * Adding a locant to a root or any other group that cannot engage in substitive nomenclature will result in an exception being thrown * An exception is made for cases where the locant could be referring to a position on another word * @param subOrBracket * @throws ComponentGenerationException * @throws StructureBuildingException */ private void assignLocantsAndMultipliers(Element subOrBracket) throws ComponentGenerationException, StructureBuildingException { List<Element> locants = XOMTools.getChildElementsWithTagName(subOrBracket, LOCANT_EL); int multiplier =1; List<Element> multipliers = XOMTools.getChildElementsWithTagName(subOrBracket, MULTIPLIER_EL); Element parentElem =(Element)subOrBracket.getParent(); boolean oneBelowWordLevel = parentElem.getLocalName().equals(WORD_EL); Element groupIfPresent = subOrBracket.getFirstChildElement(GROUP_EL); if (multipliers.size()>0){ if (multipliers.size()>1){ throw new ComponentGenerationException(subOrBracket.getLocalName() +" has multiple multipliers, unable to determine meaning!"); } if (oneBelowWordLevel && XOMTools.getNextSibling(subOrBracket) == null && XOMTools.getPreviousSibling(subOrBracket) == null) { return;//word level multiplier } multiplier = Integer.parseInt(multipliers.get(0).getAttributeValue(VALUE_ATR)); subOrBracket.addAttribute(new Attribute(MULTIPLIER_ATR, multipliers.get(0).getAttributeValue(VALUE_ATR))); //multiplier is INTENTIONALLY not detached. As brackets/subs are only multiplied later on it is neccesary at that stage to determine what elements (if any) are in front of the multiplier if (groupIfPresent !=null && PERHALOGENO_SUBTYPE_VAL.equals(groupIfPresent.getAttributeValue(SUBTYPE_ATR))){ throw new StructureBuildingException(groupIfPresent.getValue() +" cannot be multiplied"); } } if(locants.size() > 0) { if (multiplier==1 && oneBelowWordLevel && XOMTools.getPreviousSibling(subOrBracket)==null){//locant might be word Level locant if (wordLevelLocantsAllowed(subOrBracket, locants.size())){//something like S-ethyl or S-(2-ethylphenyl) or S-4-tert-butylphenyl Element locant = locants.remove(0); if (MATCH_COMMA.split(locant.getValue()).length!=1){ throw new ComponentGenerationException("Multiplier and locant count failed to agree; All locants could not be assigned!"); } parentElem.addAttribute(new Attribute(LOCANT_ATR, locant.getValue())); locant.detach(); if (locants.size()==0){ return; } } } if (subOrBracket.getLocalName().equals(ROOT_EL)){ locantsToDebugString(locants); throw new ComponentGenerationException(locantsToDebugString(locants)); } if (locants.size()!=1){ throw new ComponentGenerationException(locantsToDebugString(locants)); } Element locantEl = locants.get(0); String[] locantValues = MATCH_COMMA.split(locantEl.getValue()); if (multiplier != locantValues.length){ throw new ComponentGenerationException("Multiplier and locant count failed to agree; All locants could not be assigned!"); } Element parent =(Element) subOrBracket.getParent(); //attempt to find cases where locant will not be utilised. A special case is made for carbonyl derivatives //e.g. 1H-2-benzopyran-1,3,4-trione 4-[N-(4-chlorophenyl)hydrazone] if (!parent.getLocalName().equals(WORD_EL) || !parent.getAttributeValue(TYPE_ATR).equals(WordType.full.toString()) || !state.currentWordRule.equals(WordRule.carbonylDerivative)){ Elements children =parent.getChildElements(); boolean foundSomethingToSubstitute =false; for (int i = parent.indexOf(subOrBracket) +1 ; i < children.size(); i++) { if (!children.get(i).getLocalName().equals(HYPHEN_EL)){ foundSomethingToSubstitute = true; } } if (!foundSomethingToSubstitute){ throw new ComponentGenerationException(locantsToDebugString(locants)); } } if (groupIfPresent !=null && PERHALOGENO_SUBTYPE_VAL.equals(groupIfPresent.getAttributeValue(SUBTYPE_ATR))){ throw new StructureBuildingException(groupIfPresent.getValue() +" cannot be locanted"); } subOrBracket.addAttribute(new Attribute(LOCANT_ATR, locantEl.getValue())); locantEl.detach(); } } private String locantsToDebugString(List<Element> locants) { StringBuilder message = new StringBuilder("Unable to assign all locants. "); message.append((locants.size() > 1) ? "These locants " : "This locant "); message.append((locants.size() > 1) ? "were " : "was "); message.append("not assigned: "); for(Element locant : locants) { message.append(locant.getValue()); message.append(" "); } return message.toString(); } private boolean wordLevelLocantsAllowed(Element subOrBracket, int numberOflocants) { Element parentElem =(Element)subOrBracket.getParent(); if (WordType.valueOf(parentElem.getAttributeValue(TYPE_ATR))==WordType.substituent && (XOMTools.getNextSibling(subOrBracket)==null || numberOflocants>=2)){ if (state.currentWordRule == WordRule.ester || state.currentWordRule == WordRule.functionalClassEster || state.currentWordRule == WordRule.multiEster || state.currentWordRule == WordRule.acetal){ return true; } } if ((state.currentWordRule == WordRule.potentialBiochemicalEster || (state.currentWordRule == WordRule.ester && (XOMTools.getNextSibling(subOrBracket)==null || numberOflocants>=2))) && parentElem.getLocalName().equals(WORD_EL)){ Element wordRule = (Element) parentElem.getParent(); Elements words = wordRule.getChildElements(WORD_EL); Element ateWord = words.get(words.size()-1); if (parentElem==ateWord){ return true; } } return false; } /** * If a word level multiplier is present e.g. diethyl butandioate then this is processed to ethyl ethyl butandioate * If wordCount is 1 then an exception is thrown if a multiplier is encountered e.g. triphosgene parsed as tri phosgene * @param word * @param wordCount * @throws StructureBuildingException * @throws ComponentGenerationException */ private void processWordLevelMultiplierIfApplicable(Element word, int wordCount) throws StructureBuildingException, ComponentGenerationException { if (word.getChildCount()==1){ Element subOrBracket = (Element) word.getChild(0); Element multiplier = subOrBracket.getFirstChildElement(MULTIPLIER_EL); if (multiplier !=null){ int multiVal =Integer.parseInt(multiplier.getAttributeValue(VALUE_ATR)); Elements locants =subOrBracket.getChildElements(LOCANT_EL); boolean assignLocants =false; boolean wordLevelLocants = wordLevelLocantsAllowed(subOrBracket, locants.size());//something like O,S-dimethyl phosphorothioate if (locants.size()>1){ throw new ComponentGenerationException("Unable to assign all locants"); } String[] locantValues = null; if (locants.size()==1){ locantValues = MATCH_COMMA.split(locants.get(0).getValue()); if (locantValues.length == multiVal){ assignLocants=true; locants.get(0).detach(); if (wordLevelLocants){ word.addAttribute(new Attribute(LOCANT_ATR, locantValues[0])); } else{ throw new ComponentGenerationException(locantsToDebugString(OpsinTools.elementsToElementArrayList(locants))); } } else{ throw new ComponentGenerationException("Unable to assign all locants"); } } checkForNonConfusedWithNona(multiplier); if (wordCount ==1){ if (!isMonoFollowedByElement(multiplier, multiVal)){ throw new StructureBuildingException("Unexpected multiplier found at start of word. Perhaps the name is trivial e.g. triphosgene"); } } if (multiVal ==1){//mono return; } List<Element> elementsNotToBeMultiplied = new ArrayList<Element>();//anything before the multiplier for (int i = subOrBracket.indexOf(multiplier) -1 ; i >=0 ; i Element el = (Element) subOrBracket.getChild(i); el.detach(); elementsNotToBeMultiplied.add(el); } multiplier.detach(); for(int i=multiVal -1; i>=1; i Element clone = state.fragManager.cloneElement(state, word); if (assignLocants){ clone.getAttribute(LOCANT_ATR).setValue(locantValues[i]); } XOMTools.insertAfter(word, clone); } for (Element el : elementsNotToBeMultiplied) {//re-add anything before multiplier to original word subOrBracket.insertChild(el, 0); } } } } private void checkForNonConfusedWithNona(Element multiplier) throws StructureBuildingException { if (multiplier.getValue().equals("non")){ String subsequentUnsemanticToken = multiplier.getAttributeValue(SUBSEQUENTUNSEMANTICTOKEN_ATR); if (subsequentUnsemanticToken !=null && subsequentUnsemanticToken.toLowerCase().startsWith("a")){ return; } throw new StructureBuildingException("\"non\" probably means \"not\". If a multiplier of value 9 was intended \"nona\" should be used"); } } /** * Names like monooxygen may be used to emphasise that a molecule is not being described * @param multiplier * @param multiVal * @return */ private boolean isMonoFollowedByElement(Element multiplier, int multiVal) { if (multiVal ==1){ Element possibleElement = (Element) XOMTools.getNextSibling(multiplier); if (possibleElement != null && possibleElement.getLocalName().equals(GROUP_EL) && (ELEMENTARYATOM_SUBTYPE_VAL.equals(possibleElement.getAttributeValue(SUBTYPE_ATR)) || possibleElement.getValue().equals("hydrogen"))){ return true; } } return false; } }
package uk.ac.cam.ch.wwmm.opsin; import java.io.IOException; 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.Set; import java.util.Stack; import java.util.regex.Matcher; import java.util.regex.Pattern; import uk.ac.cam.ch.wwmm.opsin.ParseWord.WordType; import uk.ac.cam.ch.wwmm.opsin.WordRules.WordRule; import static uk.ac.cam.ch.wwmm.opsin.XmlDeclarations.*; import nu.xom.Attribute; import nu.xom.Document; import nu.xom.Element; import nu.xom.Elements; import nu.xom.Node; /**Performs structure-aware destructive procedural parsing on parser results. * * @author dl387 * */ class ComponentProcessor { private final static Pattern matchAddedHydrogenBracket =Pattern.compile("[\\[\\(\\{]([^\\[\\(\\{]*)H[\\]\\)\\}]"); private final static Pattern matchColon =Pattern.compile(":"); private final static Pattern matchSemiColon =Pattern.compile(";"); private final static Pattern matchComma =Pattern.compile(","); private final static Pattern matchSpace =Pattern.compile(" "); private final static Pattern matchElementSymbolOrAminoAcidLocant = Pattern.compile("[A-Z][a-z]?'*(\\d+[a-z]?'*)?"); private final static Pattern matchElementSymbol = Pattern.compile("[A-Z][a-z]?"); private final static Pattern matchNumericLocant =Pattern.compile("\\d+[a-z]?'*"); private final static Pattern matchChalcogenReplacement= Pattern.compile("thio|seleno|telluro"); private final static Pattern matchInlineSuffixesThatAreAlsoGroups = Pattern.compile("carbon|oxy|sulfen|sulfin|sulfon|selenen|selenin|selenon|telluren|tellurin|telluron"); private final static String[] traditionalAlkanePositionNames =new String[]{"alpha", "beta", "gamma", "delta", "epsilon", "zeta"}; /*Holds the rules on how suffixes are interpreted. Convenience methods are available to use them*/ private HashMap<String, HashMap<String, List<Element>>> suffixApplicability; private HashMap<String, Element> suffixRules; //rings that look like HW rings but have other meanings. For the HW like inorganics the true meaning is given private static final HashMap<String, String[]> specialHWRings = new HashMap<String, String[]>(); static{ //The first entry of the array is a special instruction e.g. blocked or saturated. The correct order of the heteroatoms follows //terminal e is ignored from all of the keys as it is optional in the input name specialHWRings.put("oxin", new String[]{"blocked"}); specialHWRings.put("azin", new String[]{"blocked"}); specialHWRings.put("selenin", new String[]{"not_icacid", "Se","C","C","C","C","C"}); specialHWRings.put("tellurin", new String[]{"not_icacid", "Te","C","C","C","C","C"}); specialHWRings.put("thiol", new String[]{"not_nothingOrOlate", "S","C","C","C","C"}); specialHWRings.put("selenol", new String[]{"not_nothingOrOlate", "Se","C","C","C","C"}); specialHWRings.put("tellurol", new String[]{"not_nothingOrOlate", "Te","C","C","C","C"}); specialHWRings.put("oxazol", new String[]{"","O","C","N","C","C"}); specialHWRings.put("thiazol", new String[]{"","S","C","N","C","C"}); specialHWRings.put("selenazol", new String[]{"","Se","C","N","C","C"}); specialHWRings.put("tellurazol", new String[]{"","Te","C","N","C","C"}); specialHWRings.put("oxazolidin", new String[]{"","O","C","N","C","C"}); specialHWRings.put("thiazolidin", new String[]{"","S","C","N","C","C"}); specialHWRings.put("selenazolidin", new String[]{"","Se","C","N","C","C"}); specialHWRings.put("tellurazolidin", new String[]{"","Te","C","N","C","C"}); specialHWRings.put("oxazolin", new String[]{"","O","C","N","C","C"}); specialHWRings.put("thiazolin", new String[]{"","S","C","N","C","C"}); specialHWRings.put("selenazolin", new String[]{"","Se","C","N","C","C"}); specialHWRings.put("tellurazolin", new String[]{"","Te","C","N","C","C"}); specialHWRings.put("oxoxolan", new String[]{"","O","C","O","C","C"}); specialHWRings.put("oxoxan", new String[]{"","O","C","C","O","C","C"}); specialHWRings.put("oxoxin", new String[]{"","O","C","C","O","C","C"}); specialHWRings.put("boroxin", new String[]{"saturated","O","B","O","B","O","B"}); specialHWRings.put("borazin", new String[]{"saturated","N","B","N","B","N","B"}); specialHWRings.put("borthiin", new String[]{"saturated","S","B","S","B","S","B"}); } ComponentProcessor(ResourceGetter resourceGetter) throws IOException{ //Populate suffix rules/applicability hashes Document suffixApplicabilityDoc = resourceGetter.getXMLDocument("suffixApplicability.xml"); Document suffixRulesDoc = resourceGetter.getXMLDocument("suffixRules.xml"); suffixApplicability = new HashMap<String, HashMap<String,List<Element>>>(); suffixRules = new HashMap<String, Element>(); Elements groupTypes = suffixApplicabilityDoc.getRootElement().getChildElements(SUFFIXAPPLICABILITY_GROUPTYPE_EL); for (int i = 0; i < groupTypes.size(); i++) { Element groupType =groupTypes.get(i); Elements suffixes = groupType.getChildElements(SUFFIXAPPLICABILITY_SUFFIX_EL); HashMap<String, List<Element>> suffixToRuleMap= new HashMap<String, List<Element>>(); for (int j = 0; j < suffixes.size(); j++) { Element suffix =suffixes.get(j); String suffixValue= suffix.getAttributeValue(SUFFIXAPPLICABILITY_VALUE_ATR); if (suffixToRuleMap.get(suffixValue)!=null){//can have multiple entries if subType attribute is set suffixToRuleMap.get(suffixValue).add(suffix); } else{ ArrayList<Element> suffixList =new ArrayList<Element>(); suffixList.add(suffix); suffixToRuleMap.put(suffixValue, suffixList); } } suffixApplicability.put(groupType.getAttributeValue(SUFFIXAPPLICABILITY_TYPE_ATR), suffixToRuleMap); } Elements rules = suffixRulesDoc.getRootElement().getChildElements(SUFFIXRULES_RULE_EL); for (int i = 0; i < rules.size(); i++) { Element rule =rules.get(i); String ruleValue=rule.getAttributeValue(SUFFIXRULES_VALUE_ATR); if (suffixRules.get(ruleValue)!=null){ throw new RuntimeException("Suffix: " +ruleValue +" appears multiple times in suffixRules.xml"); } suffixRules.put(ruleValue, rule); } } /** The master method, processes a parse result that has already gone through the ComponentGenerator. * At this stage one can except all substituents/roots to have at least 1 group. * Multiple groups are present in, for example, fusion nomenclature. By the end of this function there will be exactly 1 group * associated with each substituent/root. Multiplicative nomenclature can result in there being multiple roots * * @param state * @param elem The element to process. * @return * @throws ComponentGenerationException * @throws StructureBuildingException */ void process(BuildState state, Element elem) throws ComponentGenerationException, StructureBuildingException { List<Element> words =XOMTools.getDescendantElementsWithTagName(elem, WORD_EL); int wordCount =words.size(); for (int i = wordCount -1; i>=0; i Element word =words.get(i); String wordRule = OpsinTools.getParentWordRule(word).getAttributeValue(WORDRULE_EL); state.currentWordRule = WordRule.valueOf(wordRule); if (word.getAttributeValue(TYPE_ATR).equals(WordType.functionalTerm.toString())){ continue;//functionalTerms are handled on a case by case basis by wordRules } List<Element> roots = XOMTools.getDescendantElementsWithTagName(word, ROOT_EL); if (roots.size() >1){ throw new ComponentGenerationException("Multiple roots, but only 0 or 1 were expected. Found: " +roots.size()); } List<Element> substituents = XOMTools.getDescendantElementsWithTagName(word, SUBSTITUENT_EL); List<Element> substituentsAndRoot = OpsinTools.combineElementLists(substituents, roots); List<Element> brackets = XOMTools.getDescendantElementsWithTagName(word, BRACKET_EL); List<Element> substituentsAndRootAndBrackets =OpsinTools.combineElementLists(substituentsAndRoot, brackets); List<Element> groups = XOMTools.getDescendantElementsWithTagName(word, GROUP_EL); for (Element group : groups) { Fragment thisFrag = resolveGroup(state, group); processChargeAndOxidationNumberSpecification(group, thisFrag);//e.g. mercury(2+) or mercury(II) state.xmlFragmentMap.put(group, thisFrag); } for (int j = substituents.size() -1; j >=0; j Element substituent = substituents.get(j); boolean removed = removeAndMoveToAppropriateGroupIfHydroSubstituent(state, substituent);//this REMOVES a substituent just containing hydro/dehydro/perhydro elements and moves these elements in front of an appropriate ring if (!removed){ removed = removeAndMoveToAppropriateGroupIfSubstractivePrefix(substituent); } if (removed){ substituents.remove(j); substituentsAndRoot.remove(substituent); substituentsAndRootAndBrackets.remove(substituent); } } Element finalSubOrRootInWord =(Element) word.getChild(word.getChildElements().size()-1); while (!finalSubOrRootInWord.getLocalName().equals(ROOT_EL) && !finalSubOrRootInWord.getLocalName().equals(SUBSTITUENT_EL)){ List<Element> children = XOMTools.getChildElementsWithTagNames(finalSubOrRootInWord, new String[]{ROOT_EL, SUBSTITUENT_EL, BRACKET_EL}); if (children.size()==0){ throw new ComponentGenerationException("Unable to find finalSubOrRootInWord"); } finalSubOrRootInWord = children.get(children.size()-1); } for (Element subOrRootOrBracket : substituentsAndRootAndBrackets) { determineLocantMeaning(state, subOrRootOrBracket, finalSubOrRootInWord); } for (Element subOrRoot : substituentsAndRoot) { processMultipliers(subOrRoot); detectConjunctiveSuffixGroups(state, subOrRoot, groups); matchLocantsToDirectFeatures(state, subOrRoot); Elements groupsOfSubOrRoot = subOrRoot.getChildElements(GROUP_EL); Element lastGroupInSubOrRoot =groupsOfSubOrRoot.get(groupsOfSubOrRoot.size()-1); preliminaryProcessSuffixes(state, lastGroupInSubOrRoot, XOMTools.getChildElementsWithTagName(subOrRoot, SUFFIX_EL)); } FunctionalReplacement.processAmideOrHydrazideFunctionalClassNomenclature(state, finalSubOrRootInWord, word); if (FunctionalReplacement.processPrefixFunctionalReplacementNomenclature(state, groups, substituents)){//true if functional replacement performed, 1 or more substituents will have been removed substituentsAndRoot = OpsinTools.combineElementLists(substituents, roots); substituentsAndRootAndBrackets =OpsinTools.combineElementLists(substituentsAndRoot, brackets); } handleGroupIrregularities(state, groups); for (Element subOrRoot : substituentsAndRoot) { processHW(state, subOrRoot);//hantzch-widman rings FusedRingBuilder.processFusedRings(state, subOrRoot); processFusedRingBridges(state, subOrRoot); assignElementSymbolLocants(state, subOrRoot); processRingAssemblies(state, subOrRoot); processPolyCyclicSpiroNomenclature(state, subOrRoot); } for (Element subOrRoot : substituentsAndRoot) { applyLambdaConvention(state, subOrRoot); handleMultiRadicals(state, subOrRoot); } //System.out.println(new XOMFormatter().elemToString(elem)); addImplicitBracketsToAminoAcids(groups, brackets); findAndStructureImplictBrackets(state, substituents, brackets); substituentsAndRootAndBrackets =OpsinTools.combineElementLists(substituentsAndRoot, brackets);//findAndStructureImplictBrackets may have created new brackets for (Element subOrRoot : substituentsAndRoot) { matchLocantsToIndirectFeatures(state, subOrRoot); assignImplicitLocantsToDiTerminalSuffixes(state, subOrRoot); processConjunctiveNomenclature(state, subOrRoot); resolveSuffixes(state, subOrRoot.getFirstChildElement(GROUP_EL), XOMTools.getChildElementsWithTagName(subOrRoot, SUFFIX_EL)); } moveErroneouslyPositionedLocantsAndMultipliers(brackets);//e.g. (tetramethyl)azanium == tetra(methyl)azanium List<Element> children = XOMTools.getChildElementsWithTagNames(word, new String[]{ROOT_EL, SUBSTITUENT_EL, BRACKET_EL}); while (children.size()==1){ children = XOMTools.getChildElementsWithTagNames(children.get(0), new String[]{ROOT_EL, SUBSTITUENT_EL, BRACKET_EL}); } if (children.size()>0){ assignLocantsToMultipliedRootIfPresent(state, children.get(children.size()-1));//multiplicative nomenclature e.g. methylenedibenzene or 3,4'-oxydipyridine } for (Element subBracketOrRoot : substituentsAndRootAndBrackets) { assignLocantsAndMultipliers(state, subBracketOrRoot); } processWordLevelMultiplierIfApplicable(state, word, wordCount); } } /**Resolves the contents of a group element * * @param group The group element * @return The fragment specified by the group element. * @throws StructureBuildingException If the group can't be built. * @throws ComponentGenerationException */ static Fragment resolveGroup(BuildState state, Element group) throws StructureBuildingException, ComponentGenerationException { String groupType = group.getAttributeValue(TYPE_ATR); String groupSubType = group.getAttributeValue(SUBTYPE_ATR); String groupValue = group.getAttributeValue(VALUE_ATR); String groupValType = group.getAttributeValue(VALTYPE_ATR); Fragment thisFrag =null; if(groupValType.equals(SMILES_VALTYPE_VAL)) { if (group.getAttribute(LABELS_ATR)!=null){ thisFrag = state.fragManager.buildSMILES(groupValue, groupType, groupSubType, group.getAttributeValue(LABELS_ATR)); } else{ thisFrag = state.fragManager.buildSMILES(groupValue, groupType, groupSubType, ""); } } else if(groupValType.equals(DBKEY_VALTYPE_VAL)) { thisFrag = state.fragManager.buildCML(groupValue, groupType, groupSubType); } else{ throw new StructureBuildingException("Group tag has bad or missing valType: " + group.toXML()); } if (thisFrag ==null){ throw new StructureBuildingException("null fragment returned from the following xml: " + group.toXML()); } //processes groups like cymene and xylene whose structure is determined by the presence of a locant in front e.g. p-xylene processXyleneLikeNomenclature(state, group, thisFrag); FragmentTools.convertHighOrderBondsToSpareValencies(thisFrag);//only applied to cyclic bonds setFragmentDefaultInAtomIfSpecified(thisFrag, group); setFragmentFunctionalAtomsIfSpecified(group, thisFrag); applyTraditionalAlkaneNumberingIfAppropriate(group, thisFrag); applyDLPrefixesIfPresent(group, thisFrag); return thisFrag; } /** * Checks for groups with the addGroup/addBond/addHeteroAtom attributes. For the addGroup attribute adds the group defined by the SMILES described within * e.g. for xylene this function would add two methyls. Xylene is initially generated using the structure of benzene! * See tokenList dtd for more information on the syntax of these attributes if it is not clear from the code * @param state * @param group: The group element * @param parentFrag: The fragment that has been generated from the group element * @throws StructureBuildingException * @throws ComponentGenerationException */ private static void processXyleneLikeNomenclature(BuildState state, Element group, Fragment parentFrag) throws StructureBuildingException, ComponentGenerationException { if(group.getAttribute(ADDGROUP_ATR)!=null) { String addGroupInformation=group.getAttributeValue(ADDGROUP_ATR); String[] groupsToBeAdded = matchSemiColon.split(addGroupInformation);//typically only one, but 2 in the case of xylene and quinones ArrayList<HashMap<String, String>> allGroupInformation = new ArrayList<HashMap<String, String>>(); for (String groupToBeAdded : groupsToBeAdded) {//populate allGroupInformation list String[] tempArray = matchSpace.split(groupToBeAdded); HashMap<String, String> groupInformation = new HashMap<String, String>(); if (tempArray.length != 2 && tempArray.length != 3) { throw new ComponentGenerationException("malformed addGroup tag"); } groupInformation.put("SMILES", tempArray[0]); if (tempArray[1].startsWith("id")) { groupInformation.put("atomReferenceType", "id"); groupInformation.put("atomReference", tempArray[1].substring(2)); } else if (tempArray[1].startsWith("locant")) { groupInformation.put("atomReferenceType", "locant"); groupInformation.put("atomReference", tempArray[1].substring(6)); } else { throw new ComponentGenerationException("malformed addGroup tag"); } if (tempArray.length == 3) {//labels may optionally be specified for the group to be added groupInformation.put("labels", tempArray[2]); } allGroupInformation.add(groupInformation); } Element previousEl =(Element) XOMTools.getPreviousSibling(group); if (previousEl !=null && previousEl.getLocalName().equals(LOCANT_EL)){//has the name got specified locants to override the default ones List<String> locantValues =StringTools.arrayToList(matchComma.split(previousEl.getValue())); if ((locantValues.size()==groupsToBeAdded.length || locantValues.size() +1 ==groupsToBeAdded.length) && locantAreAcceptableForXyleneLikeNomenclatures(locantValues, group)){//one locant can be implicit in some cases boolean assignlocants =true; if (locantValues.size()!=groupsToBeAdded.length){ //check that the firstGroup by default will be added to the atom with locant 1. If this is not the case then as many locants as there were groups should of been specified //or no locants should have been specified, which is what will be assumed (i.e. the locants will be left unassigned) HashMap<String, String> groupInformation =allGroupInformation.get(0); String locant; if (groupInformation.get("atomReferenceType").equals("locant")){ locant =parentFrag.getAtomByLocantOrThrow(groupInformation.get("atomReference")).getFirstLocant(); } else if (groupInformation.get("atomReferenceType").equals("id") ){ locant =parentFrag.getAtomByIDOrThrow(parentFrag.getIdOfFirstAtom() + Integer.parseInt(groupInformation.get("atomReference")) -1 ).getFirstLocant(); } else{ throw new ComponentGenerationException("malformed addGroup tag"); } if (locant ==null || !locant.equals("1")){ assignlocants=false; } } if (assignlocants){ for (int i = groupsToBeAdded.length -1; i >=0 ; i //if less locants than expected are specified the locants of only the later groups will be changed //e.g. 4-xylene will transform 1,2-xylene to 1,4-xylene HashMap<String, String> groupInformation =allGroupInformation.get(i); if (locantValues.size() >0){ groupInformation.put("atomReferenceType", "locant"); groupInformation.put("atomReference", locantValues.get(locantValues.size()-1)); locantValues.remove(locantValues.size()-1); } else{ break; } } group.removeAttribute(group.getAttribute(FRONTLOCANTSEXPECTED_ATR)); previousEl.detach(); } } } for (int i = 0; i < groupsToBeAdded.length; i++) { HashMap<String, String> groupInformation =allGroupInformation.get(i); String smilesOfGroupToBeAdded = groupInformation.get("SMILES"); Fragment newFrag; if (groupInformation.get("labels")!=null){ newFrag = state.fragManager.buildSMILES(smilesOfGroupToBeAdded, parentFrag.getType(), parentFrag.getSubType(), groupInformation.get("labels")); } else{ newFrag = state.fragManager.buildSMILES(smilesOfGroupToBeAdded, parentFrag.getType(), parentFrag.getSubType(), NONE_LABELS_VAL); } Atom atomOnParentFrag =null; if (groupInformation.get("atomReferenceType").equals("locant")){ atomOnParentFrag=parentFrag.getAtomByLocantOrThrow(groupInformation.get("atomReference")); } else if (groupInformation.get("atomReferenceType").equals("id") ){ atomOnParentFrag= parentFrag.getAtomByIDOrThrow(parentFrag.getIdOfFirstAtom() + Integer.parseInt(groupInformation.get("atomReference")) -1); } else{ throw new ComponentGenerationException("malformed addGroup tag"); } if (newFrag.getOutAtoms().size() >1){ throw new ComponentGenerationException("too many outAtoms on group to be added"); } if (newFrag.getOutAtoms().size() ==1) { OutAtom newFragOutAtom = newFrag.getOutAtom(0); newFrag.removeOutAtom(newFragOutAtom); state.fragManager.incorporateFragment(newFrag, newFragOutAtom.getAtom(), parentFrag, atomOnParentFrag, newFragOutAtom.getValency()); } else{ Atom atomOnNewFrag = newFrag.getDefaultInAtom(); state.fragManager.incorporateFragment(newFrag, atomOnNewFrag, parentFrag, atomOnParentFrag, 1); } } } if(group.getAttributeValue(ADDHETEROATOM_ATR)!=null) { String addHeteroAtomInformation=group.getAttributeValue(ADDHETEROATOM_ATR); String[] heteroAtomsToBeAdded = matchSemiColon.split(addHeteroAtomInformation); ArrayList<HashMap<String, String>> allHeteroAtomInformation = new ArrayList<HashMap<String, String>>(); for (String heteroAtomToBeAdded : heteroAtomsToBeAdded) {//populate allHeteroAtomInformation list String[] tempArray = matchSpace.split(heteroAtomToBeAdded); HashMap<String, String> heteroAtomInformation = new HashMap<String, String>(); if (tempArray.length != 2) { throw new ComponentGenerationException("malformed addHeteroAtom tag"); } heteroAtomInformation.put("SMILES", tempArray[0]); if (tempArray[1].startsWith("id")) { heteroAtomInformation.put("atomReferenceType", "id"); heteroAtomInformation.put("atomReference", tempArray[1].substring(2)); } else if (tempArray[1].startsWith("locant")) { heteroAtomInformation.put("atomReferenceType", "locant"); heteroAtomInformation.put("atomReference", tempArray[1].substring(6)); } else { throw new ComponentGenerationException("malformed addHeteroAtom tag"); } allHeteroAtomInformation.add(heteroAtomInformation); } Element previousEl =(Element) XOMTools.getPreviousSibling(group); if (previousEl !=null && previousEl.getLocalName().equals(LOCANT_EL)){//has the name got specified locants to override the default ones List<String> locantValues =StringTools.arrayToList(matchComma.split(previousEl.getValue())); if (locantValues.size() ==heteroAtomsToBeAdded.length && locantAreAcceptableForXyleneLikeNomenclatures(locantValues, group)){ for (int i = heteroAtomsToBeAdded.length -1; i >=0 ; i--) {//all heteroatoms must have a locant or default locants will be used HashMap<String, String> groupInformation =allHeteroAtomInformation.get(i); groupInformation.put("atomReferenceType", "locant"); groupInformation.put("atomReference", locantValues.get(locantValues.size()-1)); locantValues.remove(locantValues.size()-1); } group.removeAttribute(group.getAttribute(FRONTLOCANTSEXPECTED_ATR)); previousEl.detach(); } } for (int i = 0; i < heteroAtomsToBeAdded.length; i++) { HashMap<String, String> heteroAtomInformation =allHeteroAtomInformation.get(i); Atom atomOnParentFrag =null; if (heteroAtomInformation.get("atomReferenceType").equals("locant")){ atomOnParentFrag=parentFrag.getAtomByLocantOrThrow(heteroAtomInformation.get("atomReference")); } else if (heteroAtomInformation.get("atomReferenceType").equals("id") ){ atomOnParentFrag= parentFrag.getAtomByIDOrThrow(parentFrag.getIdOfFirstAtom() + Integer.parseInt(heteroAtomInformation.get("atomReference")) -1); } else{ throw new ComponentGenerationException("malformed addHeteroAtom tag"); } state.fragManager.replaceAtomWithSmiles(atomOnParentFrag, heteroAtomInformation.get("SMILES")); } } if(group.getAttributeValue(ADDBOND_ATR)!=null && !HANTZSCHWIDMAN_SUBTYPE_VAL.equals(group.getAttributeValue(SUBTYPE_ATR))) {//HW add bond is handled later String addBondInformation=group.getAttributeValue(ADDBOND_ATR); String[] bondsToBeAdded = matchSemiColon.split(addBondInformation); ArrayList<HashMap<String, String>> allBondInformation = new ArrayList<HashMap<String, String>>(); for (String bondToBeAdded : bondsToBeAdded) {//populate allBondInformation list String[] tempArray = matchSpace.split(bondToBeAdded); HashMap<String, String> bondInformation = new HashMap<String, String>(); if (tempArray.length != 2) { throw new ComponentGenerationException("malformed addBond tag"); } bondInformation.put("bondOrder", tempArray[0]); if (tempArray[1].startsWith("id")) { bondInformation.put("atomReferenceType", "id"); bondInformation.put("atomReference", tempArray[1].substring(2)); } else if (tempArray[1].startsWith("locant")) { bondInformation.put("atomReferenceType", "locant"); bondInformation.put("atomReference", tempArray[1].substring(6)); } else { throw new ComponentGenerationException("malformed addBond tag"); } allBondInformation.add(bondInformation); } Element previousEl =(Element) XOMTools.getPreviousSibling(group); if (previousEl !=null && previousEl.getLocalName().equals(LOCANT_EL)){//has the name got specified locants to override the default ones List<String> locantValues =StringTools.arrayToList(matchComma.split(previousEl.getValue())); if (locantValues.size() ==bondsToBeAdded.length && locantAreAcceptableForXyleneLikeNomenclatures(locantValues, group)){ for (int i = bondsToBeAdded.length -1; i >=0 ; i--) {//all bond order changes must have a locant or default locants will be used HashMap<String, String> bondInformation =allBondInformation.get(i); bondInformation.put("atomReferenceType", "locant"); bondInformation.put("atomReference", locantValues.get(locantValues.size()-1)); locantValues.remove(locantValues.size()-1); } group.removeAttribute(group.getAttribute(FRONTLOCANTSEXPECTED_ATR)); previousEl.detach(); } } for (int i = 0; i < bondsToBeAdded.length; i++) { HashMap<String, String> bondInformation =allBondInformation.get(i); Atom atomOnParentFrag =null; if (bondInformation.get("atomReferenceType").equals("locant")){ atomOnParentFrag=parentFrag.getAtomByLocantOrThrow(bondInformation.get("atomReference")); } else if (bondInformation.get("atomReferenceType").equals("id") ){ atomOnParentFrag= parentFrag.getAtomByIDOrThrow(parentFrag.getIdOfFirstAtom() + Integer.parseInt(bondInformation.get("atomReference")) -1); } else{ throw new ComponentGenerationException("malformed addBond tag"); } FragmentTools.unsaturate(atomOnParentFrag, Integer.parseInt(bondInformation.get("bondOrder")) , parentFrag); } } } /** * Checks that all locants are present within the front locants expected attribute of the group * @param locantValues * @param group * @return */ private static boolean locantAreAcceptableForXyleneLikeNomenclatures(List<String> locantValues, Element group) { if (group.getAttribute(FRONTLOCANTSEXPECTED_ATR)==null){ throw new IllegalArgumentException("Group must have frontLocantsExpected to implement xylene-like nomenclature"); } List<String> allowedLocants = Arrays.asList(matchComma.split(group.getAttributeValue(FRONTLOCANTSEXPECTED_ATR))); for (String locant : locantValues) { if (!allowedLocants.contains(locant)){ return false; } } return true; } /** * Looks for the presence of DEFAULTINLOCANT_ATR and DEFAULTINID_ATR on the group and applies them to the fragment * Also sets the default in atom for alkanes so that say methylethyl is prop-2-yl rather than propyl * @param thisFrag * @param group * @throws StructureBuildingException */ private static void setFragmentDefaultInAtomIfSpecified(Fragment thisFrag, Element group) throws StructureBuildingException { String groupSubType = group.getAttributeValue(SUBTYPE_ATR); if (group.getAttribute(DEFAULTINLOCANT_ATR)!=null){//sets the atom at which substitution will occur to by default thisFrag.setDefaultInAtom(thisFrag.getAtomByLocantOrThrow(group.getAttributeValue(DEFAULTINLOCANT_ATR))); } else if (group.getAttribute(DEFAULTINID_ATR)!=null){ thisFrag.setDefaultInAtom(thisFrag.getAtomByIDOrThrow(thisFrag.getIdOfFirstAtom() + Integer.parseInt(group.getAttributeValue(DEFAULTINID_ATR)) -1)); } else if ("yes".equals(group.getAttributeValue(USABLEASJOINER_ATR)) && group.getAttribute(SUFFIXAPPLIESTO_ATR)==null){//makes linkers by default attach end to end int chainLength =thisFrag.getChainLength(); if (chainLength >1){ boolean connectEndToEndWithPreviousSub =true; if (groupSubType.equals(ALKANESTEM_SUBTYPE_VAL)){//don't do this if the group is preceded by another alkaneStem e.g. methylethyl makes more sense as prop-2-yl rather than propyl Element previousSubstituent =(Element) XOMTools.getPreviousSibling(group.getParent()); if (previousSubstituent!=null){ Elements groups = previousSubstituent.getChildElements(GROUP_EL); if (groups.size()==1 && groups.get(0).getAttributeValue(SUBTYPE_ATR).equals(ALKANESTEM_SUBTYPE_VAL) && !groups.get(0).getAttributeValue(TYPE_ATR).equals(RING_TYPE_VAL)){ connectEndToEndWithPreviousSub = false; } } } if (connectEndToEndWithPreviousSub){ Element parent =(Element) group.getParent(); while (parent.getLocalName().equals(BRACKET_EL)){ parent = (Element) parent.getParent(); } if (parent.getLocalName().equals(ROOT_EL)){ Element previous = (Element) XOMTools.getPrevious(group); if (previous==null || !previous.getLocalName().equals(MULTIPLIER_EL)){ connectEndToEndWithPreviousSub=false; } } } if (connectEndToEndWithPreviousSub){ group.addAttribute(new Attribute(DEFAULTINID_ATR, Integer.toString(chainLength))); thisFrag.setDefaultInAtom(thisFrag.getAtomByLocantOrThrow(Integer.toString(chainLength))); } } } } /** * Looks for the presence of FUNCTIONALIDS_ATR on the group and applies them to the fragment * @param group * @param thisFrag * @throws StructureBuildingException */ private static void setFragmentFunctionalAtomsIfSpecified(Element group, Fragment thisFrag) throws StructureBuildingException { if (group.getAttribute(FUNCTIONALIDS_ATR)!=null){ String[] functionalIDs = matchComma.split(group.getAttributeValue(FUNCTIONALIDS_ATR)); for (String functionalID : functionalIDs) { thisFrag.addFunctionalAtom(thisFrag.getAtomByIDOrThrow(thisFrag.getIdOfFirstAtom() + Integer.parseInt(functionalID) - 1)); } } } private static void applyTraditionalAlkaneNumberingIfAppropriate(Element group, Fragment thisFrag) { String groupType = group.getAttributeValue(TYPE_ATR); if (groupType.equals(ACIDSTEM_TYPE_VAL)){ List<Atom> atomList = thisFrag.getAtomList(); Atom startingAtom = thisFrag.getFirstAtom(); if (group.getAttribute(SUFFIXAPPLIESTO_ATR)!=null){ String suffixAppliesTo = group.getAttributeValue(SUFFIXAPPLIESTO_ATR); String suffixAppliesToArr[] = matchComma.split(suffixAppliesTo); if (suffixAppliesToArr.length!=1){ return; } startingAtom = atomList.get(Integer.parseInt(suffixAppliesToArr[0])-1); } List<Atom> neighbours = startingAtom.getAtomNeighbours(); int counter =-1; Atom previousAtom = startingAtom; for (int i = neighbours.size()-1; i >=0; i--) {//only consider carbon atoms if (!neighbours.get(i).getElement().equals("C")){ neighbours.remove(i); } } while (neighbours.size()==1){ counter++; if (counter>5){ break; } Atom nextAtom = neighbours.get(0); if (nextAtom.getAtomIsInACycle()){ break; } nextAtom.addLocant(traditionalAlkanePositionNames[counter]); neighbours = nextAtom.getAtomNeighbours(); neighbours.remove(previousAtom); for (int i = neighbours.size()-1; i >=0; i--) {//only consider carbon atoms if (!neighbours.get(i).getElement().equals("C")){ neighbours.remove(i); } } previousAtom = nextAtom; } } else if (groupType.equals(CHAIN_TYPE_VAL) && ALKANESTEM_SUBTYPE_VAL.equals(group.getAttributeValue(SUBTYPE_ATR))){ List<Atom> atomList = thisFrag.getAtomList(); if (atomList.size()==1){ return; } Element possibleSuffix = (Element) XOMTools.getNextSibling(group, SUFFIX_EL); Boolean terminalSuffixWithNoSuffixPrefixPresent =false; if (possibleSuffix!=null && TERMINAL_SUBTYPE_VAL.equals(possibleSuffix.getAttributeValue(SUBTYPE_ATR)) && possibleSuffix.getAttribute(SUFFIXPREFIX_ATR)==null){ terminalSuffixWithNoSuffixPrefixPresent =true; } for (Atom atom : atomList) { String firstLocant = atom.getFirstLocant(); if (!atom.getAtomIsInACycle() && firstLocant!=null && firstLocant.length()==1 && Character.isDigit(firstLocant.charAt(0))){ int locantNumber = Integer.parseInt(firstLocant); if (terminalSuffixWithNoSuffixPrefixPresent){ if (locantNumber>1 && locantNumber<=7){ atom.addLocant(traditionalAlkanePositionNames[locantNumber-2]); } } else{ if (locantNumber>0 && locantNumber<=6){ atom.addLocant(traditionalAlkanePositionNames[locantNumber-1]); } } } } } } static void applyDLPrefixesIfPresent(Element group, Fragment frag) throws ComponentGenerationException { if (AMINOACID_TYPE_VAL.equals(group.getAttributeValue(TYPE_ATR))){ Element possibleDl = (Element) XOMTools.getPreviousSibling(group); if (possibleDl !=null && possibleDl.getLocalName().equals(DLSTEREOCHEISTRY_EL)){ String value = possibleDl.getAttributeValue(VALUE_ATR); List<Atom> atomList = frag.getAtomList(); List<Atom> atomsWithParities = new ArrayList<Atom>(); for (Atom atom : atomList) { if (atom.getAtomParity()!=null){ atomsWithParities.add(atom); } } if (atomsWithParities.isEmpty()){ throw new ComponentGenerationException("D/L stereochemistry :" +value + " found before achiral amino acid"); } if (value.equals("l") || value.equals("ls")){ //do nothing, L- is implicit } else if (value.equals("d") || value.equals("ds")){ for (Atom atom : atomsWithParities) { atom.getAtomParity().setParity(-atom.getAtomParity().getParity()); } } else if (value.equals("dl")){ for (Atom atom : atomsWithParities) { atom.setAtomParity(null); } } else{ throw new ComponentGenerationException("Unexpected value for D/L stereochemistry found before amino acid: " + value ); } possibleDl.detach(); } } else if (CARBOHYDRATE_SUBTYPE_VAL.equals(group.getAttributeValue(SUBTYPE_ATR))){ Element possibleDl = (Element) XOMTools.getPreviousSibling(group); if (possibleDl !=null && possibleDl.getLocalName().equals(DLSTEREOCHEISTRY_EL)){ String value = possibleDl.getAttributeValue(VALUE_ATR); List<Atom> atomList = frag.getAtomList(); List<Atom> atomsWithParities = new ArrayList<Atom>(); for (Atom atom : atomList) { if (atom.getAtomParity()!=null){ atomsWithParities.add(atom); } } if (atomsWithParities.isEmpty()){ throw new ComponentGenerationException("D/L stereochemistry :" +value + " found before achiral carbohydrate");//sounds like a vocab bug... } if (value.equals("d") || value.equals("dg")){ //do nothing, D- is implicit } else if (value.equals("l") || value.equals("lg")){ for (Atom atom : atomsWithParities) { atom.getAtomParity().setParity(-atom.getAtomParity().getParity()); } } else if (value.equals("dl")){ for (Atom atom : atomsWithParities) { atom.setAtomParity(null); } } else{ throw new ComponentGenerationException("Unexpected value for D/L stereochemistry found before carbohydrate: " + value ); } possibleDl.detach(); } } } private void processChargeAndOxidationNumberSpecification(Element group, Fragment frag) { Element nextEl = (Element) XOMTools.getNextSibling(group); if (nextEl!=null){ if(nextEl.getLocalName().equals(CHARGESPECIFIER_EL)){ frag.getFirstAtom().setCharge(Integer.parseInt(nextEl.getAttributeValue(VALUE_ATR))); nextEl.detach(); } if(nextEl.getLocalName().equals(OXIDATIONNUMBERSPECIFIER_EL)){ frag.getFirstAtom().setProperty(Atom.OXIDATION_NUMBER, Integer.parseInt(nextEl.getAttributeValue(VALUE_ATR))); nextEl.detach(); } } } /** * Removes substituents which are just a hydro/dehydro/perhydro element and moves their contents to be in front of the next in scope ring * @param state * @param substituent * @return true is the substituent was a hydro substituent and hence was removed * @throws ComponentGenerationException */ private boolean removeAndMoveToAppropriateGroupIfHydroSubstituent(BuildState state, Element substituent) throws ComponentGenerationException { Elements hydroElements = substituent.getChildElements(HYDRO_EL); if (hydroElements.size() > 0 && substituent.getChildElements(GROUP_EL).size()==0){ Element hydroSubstituent = substituent; if (hydroElements.size()!=1){ throw new ComponentGenerationException("Unexpected number of hydro elements found in substituent"); } Element hydroElement = hydroElements.get(0); String hydroValue = hydroElement.getValue(); if (hydroValue.equals("hydro") || hydroValue.equals("dehydro")){ Element multiplier = (Element) XOMTools.getPreviousSibling(hydroElement); if (multiplier == null || !multiplier.getLocalName().equals(MULTIPLIER_EL) ){ throw new ComponentGenerationException("Multiplier expected but not found before hydro subsituent"); } if (Integer.parseInt(multiplier.getAttributeValue(VALUE_ATR)) %2 !=0){ throw new ComponentGenerationException("Hydro/dehydro can only be added in pairs but multiplier was odd: " + multiplier.getAttributeValue(VALUE_ATR)); } } Element targetRing =null; Node nextSubOrRootOrBracket = XOMTools.getNextSibling(hydroSubstituent); //first check adjacent substituent/root. If the hydroelement has one locant or the ring is locantless then we can assume the hydro is acting as a nondetachable prefix Element potentialRing =((Element)nextSubOrRootOrBracket).getFirstChildElement(GROUP_EL); if (potentialRing!=null && containsCyclicAtoms(state, potentialRing)){ Element possibleLocantInFrontOfHydro = XOMTools.getPreviousSiblingIgnoringCertainElements(hydroElement, new String[]{MULTIPLIER_EL}); if (possibleLocantInFrontOfHydro !=null && possibleLocantInFrontOfHydro.getLocalName().equals(LOCANT_EL) && matchComma.split(possibleLocantInFrontOfHydro.getValue()).length==1){ //e.g.4-decahydro-1-naphthalenyl targetRing =potentialRing; } else{ Element possibleLocantInFrontOfRing =(Element) XOMTools.getPreviousSibling(potentialRing, LOCANT_EL); if (possibleLocantInFrontOfRing !=null){ if (potentialRing.getAttribute(FRONTLOCANTSEXPECTED_ATR)!=null){//check whether the group was expecting a locant e.g. 2-furyl String locantValue = possibleLocantInFrontOfRing.getValue(); String[] expectedLocants = matchComma.split(potentialRing.getAttributeValue(FRONTLOCANTSEXPECTED_ATR)); for (String expectedLocant : expectedLocants) { if (locantValue.equals(expectedLocant)){ targetRing =potentialRing; break; } } } //check whether the group is a HW system e.g. 1,3-thiazole if (potentialRing.getAttributeValue(SUBTYPE_ATR).equals(HANTZSCHWIDMAN_SUBTYPE_VAL)){ String locantValue = possibleLocantInFrontOfRing.getValue(); int locants = matchComma.split(locantValue).length; int heteroCount = 0; Element currentElem = (Element) XOMTools.getNextSibling(possibleLocantInFrontOfRing); while(!currentElem.equals(potentialRing)){ if(currentElem.getLocalName().equals(HETEROATOM_EL)) { heteroCount++; } else if (currentElem.getLocalName().equals(MULTIPLIER_EL)){ heteroCount += Integer.parseInt(currentElem.getAttributeValue(VALUE_ATR)) -1; } currentElem = (Element)XOMTools.getNextSibling(currentElem); } if (heteroCount==locants){//number of locants must match number targetRing =potentialRing; } } //check whether the group is a benzofused ring e.g. 1,4-benzodioxin if (FUSIONRING_SUBTYPE_VAL.equals(potentialRing.getAttributeValue(SUBTYPE_ATR)) && (potentialRing.getValue().equals("benzo")|| potentialRing.getValue().equals("benz")) && !((Element)XOMTools.getNextSibling(potentialRing)).getLocalName().equals(FUSION_EL)){ targetRing =potentialRing; } } else{ targetRing =potentialRing; } } } //that didn't match so the hydro appears to be a detachable prefix. detachable prefixes attach in preference to the rightmost applicable group so search any remaining substituents/roots from right to left if (targetRing ==null){ Element nextSubOrRootOrBracketFromLast = (Element) hydroSubstituent.getParent().getChild(hydroSubstituent.getParent().getChildCount()-1);//the last sibling while (!nextSubOrRootOrBracketFromLast.equals(hydroSubstituent)){ potentialRing = nextSubOrRootOrBracketFromLast.getFirstChildElement(GROUP_EL); if (potentialRing!=null && containsCyclicAtoms(state, potentialRing)){ targetRing =potentialRing; break; } else{ nextSubOrRootOrBracketFromLast = (Element) XOMTools.getPreviousSibling(nextSubOrRootOrBracketFromLast); } } } if (targetRing ==null){ throw new ComponentGenerationException("Cannot find ring for hydro substituent to apply to"); } //move the children of the hydro substituent Elements children =hydroSubstituent.getChildElements(); for (int i = children.size()-1; i >=0 ; i Element child =children.get(i); if (!child.getLocalName().equals(HYPHEN_EL)){ child.detach(); targetRing.getParent().insertChild(child, 0); } } hydroSubstituent.detach(); return true; } return false; } /** * Removes substituents which are just a substractivePrefix element e.g. deoxy and moves their contents to be in front of the next in scope biochemical fragment (or failing that group) * @param state * @param substituent * @return true is the substituent was a subtractivePrefix substituent and hence was removed * @throws ComponentGenerationException */ static boolean removeAndMoveToAppropriateGroupIfSubstractivePrefix(Element substituent) throws ComponentGenerationException { Elements subtractivePrefixes = substituent.getChildElements(SUBTRACTIVEPREFIX_EL); if (subtractivePrefixes.size() > 0){ if (subtractivePrefixes.size()!=1){ throw new RuntimeException("Unexpected number of suffixPrefixes found in substituent"); } Element biochemicalGroup =null;//preferred Element standardGroup =null; Node nextSubOrRootOrBracket = XOMTools.getNextSibling(substituent); if (nextSubOrRootOrBracket == null){ throw new ComponentGenerationException("Unable to find group for: " + subtractivePrefixes.get(0).getValue() +" to apply to!"); } //first check adjacent substituent/root. If this is a biochemical group treat as a non detachable prefix Element potentialBiochemicalGroup =((Element)nextSubOrRootOrBracket).getFirstChildElement(GROUP_EL); if (potentialBiochemicalGroup!=null && (BIOCHEMICAL_SUBTYPE_VAL.equals(potentialBiochemicalGroup.getAttributeValue(SUBTYPE_ATR))|| CARBOHYDRATE_SUBTYPE_VAL.equals(potentialBiochemicalGroup.getAttributeValue(SUBTYPE_ATR)))){ biochemicalGroup = potentialBiochemicalGroup; } if (biochemicalGroup==null){ Element nextSubOrRootOrBracketFromLast = (Element) substituent.getParent().getChild(substituent.getParent().getChildCount()-1);//the last sibling while (!nextSubOrRootOrBracketFromLast.equals(substituent)){ Element groupToConsider = nextSubOrRootOrBracketFromLast.getFirstChildElement(GROUP_EL); if (groupToConsider!=null){ if (BIOCHEMICAL_SUBTYPE_VAL.equals(groupToConsider.getAttributeValue(SUBTYPE_ATR)) || CARBOHYDRATE_SUBTYPE_VAL.equals(groupToConsider.getAttributeValue(SUBTYPE_ATR))){ biochemicalGroup = groupToConsider; break; } else { standardGroup = groupToConsider; } } nextSubOrRootOrBracketFromLast = (Element) XOMTools.getPreviousSibling(nextSubOrRootOrBracketFromLast); } } Element targetGroup = biochemicalGroup!=null ? biochemicalGroup : standardGroup; if (targetGroup == null){ throw new ComponentGenerationException("Unable to find group for: " + subtractivePrefixes.get(0).getValue() +" to apply to!"); } //move the children of the subtractivePrefix substituent Elements children =substituent.getChildElements(); for (int i = children.size()-1; i >=0 ; i Element child =children.get(i); if (!child.getLocalName().equals(HYPHEN_EL)){ child.detach(); targetGroup.getParent().insertChild(child, 0); } } substituent.detach(); return true; } return false; } private boolean containsCyclicAtoms(BuildState state, Element potentialRing) { Fragment potentialRingFrag = state.xmlFragmentMap.get(potentialRing); List<Atom> atomList = potentialRingFrag.getAtomList(); for (Atom atom : atomList) { if (atom.getAtomIsInACycle()){ return true; } } return false; } /** * Checks for agreement between the number of locants and multipliers. * If a locant element contains multiple elements and is not next to a multiplier the various cases where this is the case will be checked for * This may result in a locant being moved if it is more convenient for subsequent processing * @param state * @param subOrBracketOrRoot The substituent/root/bracket to looks for locants in. * @param finalSubOrRootInWord : used to check if a locant is referring to the root as in multiplicative nomenclature * @throws ComponentGenerationException * @throws StructureBuildingException */ private void determineLocantMeaning(BuildState state, Element subOrBracketOrRoot, Element finalSubOrRootInWord) throws StructureBuildingException, ComponentGenerationException { List<Element> locants = XOMTools.getChildElementsWithTagName(subOrBracketOrRoot, LOCANT_EL); Element group =subOrBracketOrRoot.getFirstChildElement(GROUP_EL);//will be null if element is a bracket for (Element locant : locants) { String [] locantValues = matchComma.split(locant.getValue()); if(locantValues.length > 1) { Element afterLocant = (Element)XOMTools.getNextSibling(locant); int structuralBracketDepth = 0; Element multiplierEl = null; while (afterLocant !=null){ String elName = afterLocant.getLocalName(); if (elName.equals(STRUCTURALOPENBRACKET_EL)){ structuralBracketDepth++; } else if (elName.equals(STRUCTURALCLOSEBRACKET_EL)){ structuralBracketDepth } if (structuralBracketDepth!=0){ afterLocant = (Element)XOMTools.getNextSibling(afterLocant); continue; } if(elName.equals(LOCANT_EL)) { break; } else if (elName.equals(MULTIPLIER_EL)){ if (locantValues.length == Integer.parseInt(afterLocant.getAttributeValue(VALUE_ATR))){ if (afterLocant.equals(XOMTools.getNextSiblingIgnoringCertainElements(locant, new String[]{INDICATEDHYDROGEN_EL}))){ //direct locant, typical case. An exception is made for indicated hydrogen e.g. 1,2,4-1H-triazole multiplierEl = afterLocant; break; } else{ Element afterMultiplier = (Element) XOMTools.getNextSibling(afterLocant); if (afterMultiplier!=null && (afterMultiplier.getLocalName().equals(SUFFIX_EL) || afterMultiplier.getLocalName().equals(INFIX_EL) || afterMultiplier.getLocalName().equals(UNSATURATOR_EL) || afterMultiplier.getLocalName().equals(GROUP_EL))){ multiplierEl = afterLocant; //indirect locant break; } } } if (afterLocant.equals(XOMTools.getNextSibling(locant))){//if nothing better can be found report this as a locant/multiplier mismatch multiplierEl = afterLocant; } } else if (elName.equals(RINGASSEMBLYMULTIPLIER_EL)&& afterLocant.equals(XOMTools.getNextSibling(locant))){//e.g. 1,1'-biphenyl multiplierEl = afterLocant; if (!FragmentTools.allAtomsInRingAreIdentical(state.xmlFragmentMap.get(group))){//if all atoms are identical then the locant may refer to suffixes break; } } else if (elName.equals(FUSEDRINGBRIDGE_EL)&& locantValues.length ==2 && afterLocant.equals(XOMTools.getNextSibling(locant))){//e.g. 1,8-methano break; } afterLocant = (Element)XOMTools.getNextSibling(afterLocant); } if(multiplierEl != null) { if(Integer.parseInt(multiplierEl.getAttributeValue(VALUE_ATR)) == locantValues.length ) { // number of locants and multiplier agree boolean locantModified =false;//did determineLocantMeaning do something? if (locantValues[locantValues.length-1].endsWith("'") && group!=null && subOrBracketOrRoot.indexOf(group) > subOrBracketOrRoot.indexOf(locant)){//quite possible that this is referring to a multiplied root if (group.getAttribute(OUTIDS_ATR)!=null && matchComma.split(group.getAttributeValue(OUTIDS_ATR)).length>1){ locantModified = checkSpecialLocantUses(state, locant, locantValues, finalSubOrRootInWord); } else{ Element afterGroup = (Element)XOMTools.getNextSibling(group); int inlineSuffixCount =0; int multiplier=1; while (afterGroup !=null){ if(afterGroup.getLocalName().equals(MULTIPLIER_EL)){ multiplier =Integer.parseInt(afterGroup.getAttributeValue(VALUE_ATR)); } else if(afterGroup.getLocalName().equals(SUFFIX_EL) && afterGroup.getAttributeValue(TYPE_ATR).equals(INLINE_TYPE_VAL)){ inlineSuffixCount +=(multiplier); multiplier=1; } afterGroup = (Element)XOMTools.getNextSibling(afterGroup); } if (inlineSuffixCount >=2){ locantModified = checkSpecialLocantUses(state, locant, locantValues, finalSubOrRootInWord); } } } if (!locantModified && !XOMTools.getNextSibling(locant).equals(multiplierEl)){//the locants apply indirectly the multiplier e.g. 2,3-butandiol //move the locant to be next to the multiplier. locant.detach(); XOMTools.insertBefore(multiplierEl, locant); } } else { if(!checkSpecialLocantUses(state, locant, locantValues, finalSubOrRootInWord)) { throw new ComponentGenerationException("Mismatch between locant and multiplier counts (" + Integer.toString(locantValues.length) + " and " + multiplierEl.getAttributeValue(VALUE_ATR) + "):" + locant.toXML()); } } } else { /* Multiple locants without a multiplier */ if(!checkSpecialLocantUses(state, locant, locantValues, finalSubOrRootInWord)) { throw new ComponentGenerationException("Multiple locants without a multiplier: " + locant.toXML()); } } } } } /**Looks for Hantzch-Widman systems, and sees if the number of locants * agrees with the number of heteroatoms. * If this is not the case alternative possibilities are tested: * The locants could be intended to indicate the position of outAtoms e.g. 1,4-phenylene * The locants could be intended to indicate the attachement points of the root groups in multiplicative nomenclature e.g. 4,4'-methylenedibenzoic acid * @param state * @param locant The element corresponding to the locant group to be tested * @param locantValues The locant values; * @param finalSubOrRootInWord : used to check if a locant is referring to the root as in multiplicative nomenclatures) * @return true if there's a HW system, and agreement; or if the locants conform to one of the alternative possibilities, otherwise false. * @throws StructureBuildingException */ private boolean checkSpecialLocantUses(BuildState state, Element locant, String[] locantValues, Element finalSubOrRootInWord) throws StructureBuildingException { int count =locantValues.length; Element currentElem = (Element)XOMTools.getNextSibling(locant); int heteroCount = 0; int multiplierValue = 1; while(currentElem != null && !currentElem.getLocalName().equals(GROUP_EL)){ if(currentElem.getLocalName().equals(HETEROATOM_EL)) { heteroCount+=multiplierValue; multiplierValue =1; } else if (currentElem.getLocalName().equals(MULTIPLIER_EL)){ multiplierValue = Integer.parseInt(currentElem.getAttributeValue(VALUE_ATR)); } else{ break; } currentElem = (Element)XOMTools.getNextSibling(currentElem); } if(currentElem != null && currentElem.getLocalName().equals(GROUP_EL)){ if (currentElem.getAttributeValue(SUBTYPE_ATR).equals(HANTZSCHWIDMAN_SUBTYPE_VAL)) { if(heteroCount == count) { return true; } else if (heteroCount > 1){ return false;//there is a case where locants don't apply to heteroatoms in a HW system, but in that case only one locant is expected so this function would not be called } } if (heteroCount==0 && currentElem.getAttribute(OUTIDS_ATR)!=null ) {//e.g. 1,4-phenylene String[] outIDs = matchComma.split(currentElem.getAttributeValue(OUTIDS_ATR), -1); Fragment groupFragment =state.xmlFragmentMap.get(currentElem); if (count ==outIDs.length && groupFragment.getAtomList().size()>1){//things like oxy do not need to have their outIDs specified int idOfFirstAtomInFrag =groupFragment.getIdOfFirstAtom(); boolean foundLocantNotPresentOnFragment = false; for (int i = outIDs.length-1; i >=0; i Atom a =groupFragment.getAtomByLocant(locantValues[i]); if (a==null){ foundLocantNotPresentOnFragment = true; break; } outIDs[i]=Integer.toString(a.getID() -idOfFirstAtomInFrag +1);//convert to relative id } if (!foundLocantNotPresentOnFragment){ currentElem.getAttribute(OUTIDS_ATR).setValue(StringTools.arrayToString(outIDs, ",")); locant.detach(); return true; } } } else if(currentElem.getValue().equals("benz") || currentElem.getValue().equals("benzo")){ Node potentialGroupAfterBenzo = XOMTools.getNextSibling(currentElem, GROUP_EL);//need to make sure this isn't benzyl if (potentialGroupAfterBenzo!=null){ return true;//e.g. 1,2-benzothiazole } } } if(currentElem != null && currentElem.getLocalName().equals(POLYCYCLICSPIRO_EL)){ return true; } if(currentElem != null && count==2 && currentElem.getLocalName().equals(FUSEDRINGBRIDGE_EL)){ return true; } boolean detectedMultiplicativeNomenclature = detectMultiplicativeNomenclature(locant, locantValues, finalSubOrRootInWord); if (detectedMultiplicativeNomenclature){ return true; } if (currentElem != null && currentElem.getLocalName().equals(GROUP_EL) && count ==2 && EPOXYLIKE_SUBTYPE_VAL.equals(currentElem.getAttributeValue(SUBTYPE_ATR))){ return true; } Element parentElem = (Element) locant.getParent(); if (count==2 && parentElem.getLocalName().equals(BRACKET_EL)){//e.g. 3,4-(dichloromethylenedioxy) this is changed to (dichloro3,4-methylenedioxy) List<Element> substituents = XOMTools.getChildElementsWithTagName(parentElem, SUBSTITUENT_EL); if (substituents.size()>0){ Element finalSub = substituents.get(substituents.size()-1); Element group = finalSub.getFirstChildElement(GROUP_EL); if (EPOXYLIKE_SUBTYPE_VAL.equals(group.getAttributeValue(SUBTYPE_ATR))){ locant.detach(); XOMTools.insertBefore(group, locant); return true; } } } return false; } /** * Detects multiplicative nomenclature. If it does then the locant will be moved, changed to a multiplicative locant and true will be returned * @param locant * @param locantValues * @param finalSubOrRootInWord * @return */ private boolean detectMultiplicativeNomenclature(Element locant, String[] locantValues, Element finalSubOrRootInWord) { int count =locantValues.length; Element multiplier =(Element) finalSubOrRootInWord.getChild(0); if (((Element)finalSubOrRootInWord.getParent()).getLocalName().equals(BRACKET_EL)){//e.g. 1,1'-ethynediylbis(1-cyclopentanol) if (!multiplier.getLocalName().equals(MULTIPLIER_EL)){ multiplier =(Element) finalSubOrRootInWord.getParent().getChild(0); } else{ Element elAfterMultiplier = (Element) XOMTools.getNextSibling(multiplier); String elName = elAfterMultiplier.getLocalName(); if (elName.equals(HETEROATOM_EL) || elName.equals(SUBTRACTIVEPREFIX_EL)|| (elName.equals(HYDRO_EL) && !elAfterMultiplier.getValue().startsWith("per"))|| elName.equals(FUSEDRINGBRIDGE_EL)) { multiplier =(Element) finalSubOrRootInWord.getParent().getChild(0); } } } Node commonParent =locant.getParent().getParent();//this should be a common parent of the multiplier in front of the root. If it is not, then this locant is in a different scope Node parentOfMultiplier =multiplier.getParent(); while (parentOfMultiplier!=null){ if (commonParent.equals(parentOfMultiplier)){ if (locantValues[count-1].endsWith("'") && multiplier.getLocalName().equals(MULTIPLIER_EL) && !((Element)XOMTools.getNextSibling(multiplier)).getLocalName().equals(MULTIPLICATIVELOCANT_EL) && Integer.parseInt(multiplier.getAttributeValue(VALUE_ATR)) == count ){//multiplicative nomenclature locant.setLocalName(MULTIPLICATIVELOCANT_EL); locant.detach(); XOMTools.insertAfter(multiplier, locant); return true; } } parentOfMultiplier=parentOfMultiplier.getParent(); } return false; } /** Look for multipliers, and multiply out suffixes/unsaturators/heteroatoms/hydros. * Locants are assigned if the number of locants matches the multiplier * associated with them. Eg. triol - > ololol. * Note that infix multiplication is handled seperately as resolution of suffixes is required to perform this unambiguously * @param subOrRoot The substituent/root to looks for multipliers in. */ private void processMultipliers(Element subOrRoot) { List<Element> multipliers = XOMTools.getChildElementsWithTagName(subOrRoot, MULTIPLIER_EL); for (Element multiplier : multipliers) { Element possibleLocant =(Element)XOMTools.getPreviousSibling(multiplier); String[] locants = null; if (possibleLocant !=null && possibleLocant.getLocalName().equals(LOCANT_EL)){ locants = matchComma.split(possibleLocant.getValue()); } Element featureToMultiply = (Element)XOMTools.getNextSibling(multiplier); String nextName = featureToMultiply.getLocalName(); if(nextName.equals(UNSATURATOR_EL) || nextName.equals(SUFFIX_EL) || nextName.equals(SUBTRACTIVEPREFIX_EL) || (nextName.equals(HETEROATOM_EL) && !GROUP_TYPE_VAL.equals(multiplier.getAttributeValue(TYPE_ATR))) || nextName.equals(HYDRO_EL)) { int mvalue = Integer.parseInt(multiplier.getAttributeValue(VALUE_ATR)); if (mvalue>1){ featureToMultiply.addAttribute(new Attribute(MULTIPLIED_ATR, "multiplied")); } for(int i= mvalue -1; i >=1; i Element newElement = new Element(featureToMultiply); if (locants !=null && locants.length==mvalue){ newElement.addAttribute(new Attribute(LOCANT_ATR, locants[i])); } XOMTools.insertAfter(featureToMultiply, newElement); } multiplier.detach(); if (locants !=null && locants.length==mvalue){ featureToMultiply.addAttribute(new Attribute(LOCANT_ATR, locants[0])); possibleLocant.detach(); } } } } /** * Converts group elements that are identified as being conjunctive suffixes to CONJUNCTIVESUFFIXGROUP_EL * and labels them appropriately. Any suffixes that the conjunctive suffix may have are resolved onto it * @param state * @param subOrRoot * @param allGroups * @throws ComponentGenerationException * @throws StructureBuildingException */ private void detectConjunctiveSuffixGroups(BuildState state, Element subOrRoot, List<Element> allGroups) throws ComponentGenerationException, StructureBuildingException { List<Element> groups = XOMTools.getChildElementsWithTagName(subOrRoot, GROUP_EL); if (groups.size()>1){ List<Element> conjunctiveGroups = new ArrayList<Element>(); Element ringGroup =null; for (int i = groups.size() -1 ; i >=0; i Element group =groups.get(i); if (!group.getAttributeValue(TYPE_ATR).equals(RING_TYPE_VAL)){//e.g. the methanol in benzenemethanol. conjunctiveGroups.add(group); } else{ ringGroup =group; break; } } if (conjunctiveGroups.size() ==0){ return; } if (ringGroup ==null){ throw new ComponentGenerationException("OPSIN bug: unable to find ring associated with conjunctive suffix group"); } if (conjunctiveGroups.size()!=1){ throw new ComponentGenerationException("OPSIN Bug: Two groups exactly should be present at this point when processing conjunctive nomenclature"); } Element primaryConjunctiveGroup =conjunctiveGroups.get(0); Fragment primaryConjunctiveFrag = state.xmlFragmentMap.get(primaryConjunctiveGroup); //remove all locants List<Atom> atomList = primaryConjunctiveFrag.getAtomList(); for (Atom atom : atomList) { atom.clearLocants(); } List<Element> suffixes = new ArrayList<Element>(); Element possibleSuffix = (Element) XOMTools.getNextSibling(primaryConjunctiveGroup); while (possibleSuffix !=null){ if (possibleSuffix.getLocalName().equals(SUFFIX_EL)){ suffixes.add(possibleSuffix); } possibleSuffix = (Element) XOMTools.getNextSibling(possibleSuffix); } preliminaryProcessSuffixes(state, primaryConjunctiveGroup, suffixes); resolveSuffixes(state, primaryConjunctiveGroup, suffixes); for (Element suffix : suffixes) { suffix.detach(); } primaryConjunctiveGroup.setLocalName(CONJUNCTIVESUFFIXGROUP_EL); allGroups.remove(primaryConjunctiveGroup); Element possibleMultiplier = (Element) XOMTools.getPreviousSibling(primaryConjunctiveGroup); //label atoms appropriately boolean alphaIsPosition1 = atomList.get(0).getIncomingValency() < 3; int counter =0; for (int i = (alphaIsPosition1 ? 0 : 1); i < atomList.size(); i++) { Atom a = atomList.get(i); if (counter==0){ a.addLocant("alpha"); } else if (counter==1){ a.addLocant("beta"); } else if (counter==2){ a.addLocant("gamma"); } else if (counter==3){ a.addLocant("delta"); } else if (counter==4){ a.addLocant("epsilon"); } else if (counter==5){ a.addLocant("zeta"); } else if (counter==6){ a.addLocant("eta"); } counter++; } if (MULTIPLIER_EL.equals(possibleMultiplier.getLocalName())){ int multiplier = Integer.parseInt(possibleMultiplier.getAttributeValue(VALUE_ATR)); for (int i = 1; i < multiplier; i++) { Element conjunctiveSuffixGroup = new Element(primaryConjunctiveGroup); Fragment newFragment = state.fragManager.copyAndRelabelFragment(primaryConjunctiveFrag, i); state.xmlFragmentMap.put(conjunctiveSuffixGroup, newFragment); conjunctiveGroups.add(conjunctiveSuffixGroup); XOMTools.insertAfter(primaryConjunctiveGroup, conjunctiveSuffixGroup); } Element possibleLocant =(Element)XOMTools.getPreviousSibling(possibleMultiplier); possibleMultiplier.detach(); if (possibleLocant.getLocalName().equals(LOCANT_EL)){ String[] locants = matchComma.split(possibleLocant.getValue()); if (locants.length!=multiplier){ throw new ComponentGenerationException("mismatch between number of locants and multiplier in conjunctive nomenclature routine"); } for (int i = 0; i < locants.length; i++) { conjunctiveGroups.get(i).addAttribute(new Attribute(LOCANT_ATR, locants[i])); } possibleLocant.detach(); } } } } /** Match each locant to the next applicable "feature". Assumes that processLocants * has done a good job and rejected cases where no match can be made. * Handles cases where the locant is next to the feature it refers to * @param state * * @param subOrRoot The substituent/root to look for locants in. * @throws ComponentGenerationException */ private void matchLocantsToDirectFeatures(BuildState state, Element subOrRoot) throws ComponentGenerationException { List<Element> locants = XOMTools.getChildElementsWithTagName(subOrRoot, LOCANT_EL); List<Element> groups = XOMTools.getChildElementsWithTagName(subOrRoot, GROUP_EL); for (Element group : groups) { if (group.getAttributeValue(SUBTYPE_ATR).equals(HANTZSCHWIDMAN_SUBTYPE_VAL)){//handle Hantzch-widman systems if (group.getAttribute(ADDBOND_ATR)!=null){//special case for partunsatring //exception for where a locant is supposed to indicate the location of a double bond... Elements deltas = subOrRoot.getChildElements(DELTA_EL); if (deltas.size()==0){ Element delta =new Element(DELTA_EL); Element appropriateLocant = XOMTools.getPreviousSiblingIgnoringCertainElements(group, new String[]{HETEROATOM_EL, MULTIPLIER_EL}); if (appropriateLocant !=null && appropriateLocant.getLocalName().equals(LOCANT_EL) && matchComma.split(appropriateLocant.getValue()).length == 1){ delta.appendChild(appropriateLocant.getValue()); XOMTools.insertBefore(appropriateLocant, delta); appropriateLocant.detach(); locants.remove(appropriateLocant); } else{ delta.appendChild(""); subOrRoot.insertChild(delta, 0);//no obvious attempt to set double bond position, potentially ambiguous, valency will be used to choose later } } } if (locants.size()>0 ){ Element locantBeforeHWSystem = null; List<Element> heteroAtoms = new ArrayList<Element>(); int indexOfGroup =subOrRoot.indexOf(group); for (int j = indexOfGroup -1; j >= 0; j String elName=((Element)subOrRoot.getChild(j)).getLocalName(); if (elName.equals(LOCANT_EL)){ locantBeforeHWSystem = (Element)subOrRoot.getChild(j); break; } else if(elName.equals(HETEROATOM_EL)){ Element heteroAtom = (Element)subOrRoot.getChild(j); heteroAtoms.add(heteroAtom); if (heteroAtom.getAttribute(LOCANT_ATR)!=null){//locants already assigned, assumedly by process multipliers break; } } else{ break; } } Collections.reverse(heteroAtoms); if (locantBeforeHWSystem !=null){ String[] locantValues = matchComma.split(locantBeforeHWSystem.getValue()); //detect a solitary locant in front of a HW system and prevent it being assigned. //something like 1-aziridin-1-yl never means the N is at position 1 as it is at position 1 by convention //this special case is not applied to pseudo HW like systems e.g. [1]oxacyclotetradecine if (locantValues.length ==1 && state.xmlFragmentMap.get(group).getAtomList().size() <=10){ locants.remove(locantBeforeHWSystem);//don't assign this locant } else { if (locantValues.length == heteroAtoms.size()){ for (int j = 0; j < locantValues.length; j++) { String locantValue = locantValues[j]; heteroAtoms.get(j).addAttribute(new Attribute(LOCANT_ATR, locantValue)); } locantBeforeHWSystem.detach(); locants.remove(locantBeforeHWSystem); } else if (heteroAtoms.size()>1){ throw new ComponentGenerationException("Mismatch between number of locants and HW heteroatoms"); } } } } } } assignSingleLocantsToAdjacentFeatures(locants); } /** * Looks for a suffix/suffix/heteroatom/hydro element adjacent to the given locant * and if the locant element describes just 1 locant asssigns it * @param locants */ private void assignSingleLocantsToAdjacentFeatures(List<Element> locants) { for (Element locant : locants) { String[] locantValues = matchComma.split(locant.getValue()); Element referent = (Element)XOMTools.getNextSibling(locant); if (referent!=null && locantValues.length==1){ String refName = referent.getLocalName(); if(referent.getAttribute(LOCANT_ATR) == null && referent.getAttribute(MULTIPLIED_ATR) == null && (refName.equals(UNSATURATOR_EL) || refName.equals(SUFFIX_EL) || refName.equals(HETEROATOM_EL) || refName.equals(CONJUNCTIVESUFFIXGROUP_EL) || refName.equals(SUBTRACTIVEPREFIX_EL) || (refName.equals(HYDRO_EL) && !referent.getValue().startsWith("per") ))) {//not perhydro referent.addAttribute(new Attribute(LOCANT_ATR, locantValues[0])); locant.detach(); } } } } /** * Handles suffixes, passes them to resolveGroupAddingSuffixes. * Processes the suffixAppliesTo command which multiplies a suffix and attaches the suffixes to the atoms described by the given IDs * @param state * @param group * @param suffixes * @throws ComponentGenerationException * @throws StructureBuildingException */ private void preliminaryProcessSuffixes(BuildState state, Element group, List<Element> suffixes) throws ComponentGenerationException, StructureBuildingException{ Fragment suffixableFragment =state.xmlFragmentMap.get(group); boolean imideSpecialCase =false; if (group.getAttribute(SUFFIXAPPLIESTO_ATR)!=null){//typically a trivial polyAcid or aminoAcid imideSpecialCase = processSuffixAppliesTo(group, suffixes,suffixableFragment); } else{ for (Element suffix : suffixes) { if (suffix.getAttribute(ADDITIONALVALUE_ATR)!=null){ throw new ComponentGenerationException("suffix: " + suffix.getValue() + " used on an inappropriate group"); } } } if (group.getAttribute(SUFFIXAPPLIESTOBYDEFAULT_ATR)!=null){ applyDefaultLocantToSuffixIfPresent(group.getAttributeValue(SUFFIXAPPLIESTOBYDEFAULT_ATR), group, suffixableFragment); } List<Fragment> suffixFragments =resolveGroupAddingSuffixes(state, suffixes, suffixableFragment); state.xmlSuffixMap.put(group, suffixFragments); boolean suffixesResolved =false; if (group.getAttributeValue(TYPE_ATR).equals(CHALCOGENACIDSTEM_TYPE_VAL)){//merge the suffix into the chalcogen acid stem e.g sulfonoate needs to be one fragment for infix replacement resolveSuffixes(state, group, suffixes); suffixesResolved =true; } processSuffixPrefixes(state, suffixes);//e.g. carbox amide FunctionalReplacement.processInfixFunctionalReplacementNomenclature(state, suffixes, suffixFragments); processConvertHydroxyGroupsToOutAtomsRule(state, suffixes, suffixableFragment); if (group.getValue().equals("oxal")){//oxalic acid is treated as a non carboxylic acid for the purposes of functional replacment. See P-65.2.3 resolveSuffixes(state, group, suffixes); group.getAttribute(TYPE_ATR).setValue(NONCARBOXYLICACID_TYPE_VAL); suffixableFragment.setType(NONCARBOXYLICACID_TYPE_VAL); suffixesResolved =true; } if (imideSpecialCase){//Pretty horrible hack to allow cyclic imides if (suffixes.size() !=2){ throw new ComponentGenerationException("Expected two suffixes fragments for cyclic imide"); } Atom nitrogen =null; for (Atom a : suffixFragments.get(0).getAtomList()) { if (a.getElement().equals("N")){//amide nitrogen =a; } } if (nitrogen ==null){ throw new ComponentGenerationException("Nitrogen not found where nitrogen expected"); } Atom carbon = suffixableFragment.getAtomByIDOrThrow(Integer.parseInt(suffixes.get(1).getAttributeValue(LOCANTID_ATR))); if (!carbon.getElement().equals("C")){ throw new ComponentGenerationException("Carbon not found where carbon expected"); } resolveSuffixes(state, group, suffixes); suffixesResolved = true; state.fragManager.createBond(nitrogen, carbon, 1);//join the N of the amide to the carbon of the acid to form the cyclic imide } if (suffixesResolved){ //suffixes have already been resolved so need to be detached to avoid being passed to resolveSuffixes later for (int i = suffixes.size() -1; i>=0; i Element suffix =suffixes.remove(i); suffix.detach(); } } if (group.getAttribute(NUMBEROFFUNCTIONALATOMSTOREMOVE_ATR)!=null){ int numberToRemove = Integer.parseInt(group.getAttributeValue(NUMBEROFFUNCTIONALATOMSTOREMOVE_ATR)); if (numberToRemove > suffixableFragment.getFunctionalAtoms().size()){ throw new ComponentGenerationException("Too many hydrogen for the number of positions on non carboxylic acid"); } for (int i = 0; i< numberToRemove; i++) { Atom functionalAtom = suffixableFragment.removeFunctionalAtom(0).getAtom(); functionalAtom.neutraliseCharge(); } } } private void applyDefaultLocantToSuffixIfPresent(String attributeValue, Element group, Fragment suffixableFragment) { Element suffix =OpsinTools.getNextNonChargeSuffix(group); if (suffix !=null){ suffix.addAttribute(new Attribute(DEFAULTLOCANTID_ATR, Integer.toString(suffixableFragment.getIdOfFirstAtom() + Integer.parseInt(attributeValue) -1))); } } /** * Processes the effects of the suffixAppliesTo attribute * Returns true if an imide is detected * @param group * @param suffixes * @param suffixableFragment * @return * @throws ComponentGenerationException */ private boolean processSuffixAppliesTo(Element group, List<Element> suffixes, Fragment suffixableFragment) throws ComponentGenerationException { boolean imideSpecialCase =false; //suffixAppliesTo attribute contains instructions for number/positions of suffix //this is of the form comma sepeated ids with the number of ids corresponding to the number of instances of the suffix Element suffix =OpsinTools.getNextNonChargeSuffix(group); if (suffix ==null){ throw new ComponentGenerationException("No suffix where suffix was expected"); } else{ if (suffixes.size()>1 && group.getAttributeValue(TYPE_ATR).equals(ACIDSTEM_TYPE_VAL)){ throw new ComponentGenerationException("More than one suffix detected on trivial polyAcid. Not believed to be allowed"); } String suffixInstruction =group.getAttributeValue(SUFFIXAPPLIESTO_ATR); String[] suffixInstructions = matchComma.split(suffixInstruction); boolean symmetricSuffixes =true; if (suffix.getAttribute(ADDITIONALVALUE_ATR)!=null){//handles amic, aldehydic, anilic and amoyl suffixes properly if (suffixInstructions.length < 2){ throw new ComponentGenerationException("suffix: " + suffix.getValue() + " used on an inappropriate group"); } symmetricSuffixes = false; String suffixValue = suffix.getValue(); if (suffixValue.equals("imide") || suffixValue.equals("imid")|| suffixValue.equals("imido") || suffixValue.equals("imidyl")|| suffixValue.equals("imidium") || suffixValue.equals("imidylium")){ imideSpecialCase =true;//prematurely resolve the two suffixes and explicitly join them to form a cyclic imide } } int firstIdInFragment=suffixableFragment.getIdOfFirstAtom(); if (suffix.getAttribute(LOCANT_ATR)==null){ suffix.addAttribute(new Attribute(LOCANTID_ATR, Integer.toString(firstIdInFragment + Integer.parseInt(suffixInstructions[0]) -1))); } for (int i = 1; i < suffixInstructions.length; i++) { Element newSuffix = new Element(SUFFIX_EL); if (symmetricSuffixes){ newSuffix.addAttribute(new Attribute(VALUE_ATR, suffix.getAttributeValue(VALUE_ATR))); newSuffix.addAttribute(new Attribute(TYPE_ATR, suffix.getAttributeValue(TYPE_ATR))); if (suffix.getAttribute(SUBTYPE_ATR)!=null){ newSuffix.addAttribute(new Attribute(SUBTYPE_ATR, suffix.getAttributeValue(SUBTYPE_ATR))); } if (suffix.getAttribute(INFIX_ATR)!=null && suffix.getAttributeValue(INFIX_ATR).startsWith("=")){//clone infixes that effect double bonds but not single bonds e.g. maleamidate still should have one functional atom newSuffix.addAttribute(new Attribute(INFIX_ATR, suffix.getAttributeValue(INFIX_ATR))); } } else{ newSuffix.addAttribute(new Attribute(VALUE_ATR, suffix.getAttributeValue(ADDITIONALVALUE_ATR))); newSuffix.addAttribute(new Attribute(TYPE_ATR, ROOT_EL)); } newSuffix.addAttribute(new Attribute(LOCANTID_ATR, Integer.toString(firstIdInFragment + Integer.parseInt(suffixInstructions[i]) -1))); XOMTools.insertAfter(suffix, newSuffix); suffixes.add(newSuffix); } } return imideSpecialCase; } /**Processes a suffix and returns any fragment the suffix intends to add to the molecule * @param state * @param suffixes The suffix elements for a fragment. * @param frag The fragment to which the suffix will be applied * @return An arrayList containing the generated fragments * @throws StructureBuildingException If the suffixes can't be resolved properly. * @throws ComponentGenerationException */ private List<Fragment> resolveGroupAddingSuffixes(BuildState state, List<Element> suffixes, Fragment frag) throws StructureBuildingException, ComponentGenerationException { List<Fragment> suffixFragments =new ArrayList<Fragment>(); String groupType = frag.getType(); String subgroupType = frag.getSubType(); String suffixTypeToUse =null; if (suffixApplicability.containsKey(groupType)){ suffixTypeToUse =groupType; } else{ suffixTypeToUse = STANDARDGROUP_TYPE_VAL; } for (Element suffix : suffixes) { String suffixValue = suffix.getAttributeValue(VALUE_ATR); boolean cyclic;//needed for addSuffixPrefixIfNonePresentAndCyclic rule Atom atomLikelyToBeUsedBySuffix = null; if (suffix.getAttribute(LOCANT_ATR) != null) { atomLikelyToBeUsedBySuffix = frag.getAtomByLocant(suffix.getAttributeValue(LOCANT_ATR)); } else if (suffix.getAttribute(LOCANTID_ATR) != null) { atomLikelyToBeUsedBySuffix = frag.getAtomByIDOrThrow(Integer.parseInt(suffix.getAttributeValue(LOCANTID_ATR))); } if (atomLikelyToBeUsedBySuffix==null){ //a locant has not been specified //also can happen in the cases of things like fused rings where the final numbering is not available so lookup by locant fails (in which case all the atoms will be cyclic anyway) atomLikelyToBeUsedBySuffix = frag.getFirstAtom(); } cyclic = atomLikelyToBeUsedBySuffix.getAtomIsInACycle(); Elements suffixRuleTags = getSuffixRuleTags(suffixTypeToUse, suffixValue, subgroupType); Fragment suffixFrag = null; /* * Temp fragments are build for each addGroup rule and then merged into suffixFrag */ for (int j = 0; j < suffixRuleTags.size(); j++) { Element suffixRuleTag = suffixRuleTags.get(j); String suffixRuleTagName = suffixRuleTag.getLocalName(); if (suffixRuleTagName.equals(SUFFIXRULES_ADDGROUP_EL)) { String labels = NONE_LABELS_VAL; if (suffixRuleTag.getAttribute(SUFFIXRULES_LABELS_ATR) != null) { labels = suffixRuleTag.getAttributeValue(SUFFIXRULES_LABELS_ATR); } suffixFrag = state.fragManager.buildSMILES(suffixRuleTag.getAttributeValue(SUFFIXRULES_SMILES_ATR), SUFFIX_TYPE_VAL, SUFFIX_SUBTYPE_VAL, labels); List<Atom> atomList = suffixFrag.getAtomList(); if (suffixRuleTag.getAttribute(SUFFIXRULES_FUNCTIONALIDS_ATR) != null) { String[] relativeIdsOfFunctionalAtoms = matchComma.split(suffixRuleTag.getAttributeValue(SUFFIXRULES_FUNCTIONALIDS_ATR)); for (String relativeId : relativeIdsOfFunctionalAtoms) { int atomIndice = Integer.parseInt(relativeId) -1; if (atomIndice >=atomList.size()){ throw new StructureBuildingException("Check suffixRules.xml: Atom requested to have a functionalAtom was not within the suffix fragment"); } suffixFrag.addFunctionalAtom(atomList.get(atomIndice)); } } if (suffixRuleTag.getAttribute(SUFFIXRULES_OUTIDS_ATR) != null) { String[] relativeIdsOfOutAtoms = matchComma.split(suffixRuleTag.getAttributeValue(SUFFIXRULES_OUTIDS_ATR)); for (String relativeId : relativeIdsOfOutAtoms) { int atomIndice = Integer.parseInt(relativeId) -1; if (atomIndice >=atomList.size()){ throw new StructureBuildingException("Check suffixRules.xml: Atom requested to have a outAtom was not within the suffix fragment"); } suffixFrag.addOutAtom(atomList.get(atomIndice), 1 , true); } } } else if (suffixRuleTagName.equals(SUFFIXRULES_ADDSUFFIXPREFIXIFNONEPRESENTANDCYCLIC_EL)){ if (cyclic && suffix.getAttribute(SUFFIXPREFIX_ATR)==null){ suffix.addAttribute(new Attribute(SUFFIXPREFIX_ATR, suffixRuleTag.getAttributeValue(SUFFIXRULES_SMILES_ATR))); } } else if (suffixRuleTagName.equals(SUFFIXRULES_ADDFUNCTIONALATOMSTOHYDROXYGROUPS_EL)){ if (suffixFrag != null){ throw new ComponentGenerationException("addFunctionalAtomsToHydroxyGroups is not currently compatable with the addGroup suffix rule"); } addFunctionalAtomsToHydroxyGroups(atomLikelyToBeUsedBySuffix); } else if (suffixRuleTagName.equals(SUFFIXRULES_CHARGEHYDROXYGROUPS_EL)){ if (suffixFrag != null){ throw new ComponentGenerationException("chargeHydroxyGroups is not currently compatable with the addGroup suffix rule"); } chargeHydroxyGroups(atomLikelyToBeUsedBySuffix); } else if (suffixRuleTagName.equals(SUFFIXRULES_REMOVEONEDOUBLEBONDEDOXYGEN_EL)){ if (suffixFrag != null){ throw new ComponentGenerationException("removeOneDoubleBondedOxygen is not currently compatable with the addGroup suffix rule"); } removeOneDoubleBondedOxygen(state, atomLikelyToBeUsedBySuffix); } } if (suffixFrag != null) { suffixFragments.add(suffixFrag); state.xmlFragmentMap.put(suffix, suffixFrag); } } return suffixFragments; } /**Processes any convertHydroxyGroupsToOutAtoms instructions * This is not handled as part of resolveGroupAddingSuffixes as something like carbonochloridoyl involves infix replacement * on a hydroxy that would otherwise actually be removed by this rule! * @param state * @param suffixes The suffix elements for a fragment. * @param frag The fragment to which the suffix will be applied * @return An arrayList containing the generated fragments * @throws ComponentGenerationException * @throws StructureBuildingException */ private void processConvertHydroxyGroupsToOutAtomsRule(BuildState state, List<Element> suffixes, Fragment frag) throws ComponentGenerationException, StructureBuildingException{ String groupType = frag.getType(); String subgroupType = frag.getSubType(); String suffixTypeToUse =null; if (suffixApplicability.containsKey(groupType)){ suffixTypeToUse =groupType; } else{ suffixTypeToUse = STANDARDGROUP_TYPE_VAL; } for (Element suffix : suffixes) { String suffixValue = suffix.getAttributeValue(VALUE_ATR); Elements suffixRuleTags = getSuffixRuleTags(suffixTypeToUse, suffixValue, subgroupType); for (int j = 0; j < suffixRuleTags.size(); j++) { Element suffixRuleTag = suffixRuleTags.get(j); String suffixRuleTagName = suffixRuleTag.getLocalName(); if (suffixRuleTagName.equals(SUFFIXRULES_CONVERTHYDROXYGROUPSTOOUTATOMS_EL)){ convertHydroxyGroupsToOutAtoms(state, frag); } } } } /** * Finds all hydroxy groups connected to a given atom and adds a functionalAtom to each of them * @param atom * @throws StructureBuildingException */ private void addFunctionalAtomsToHydroxyGroups(Atom atom) throws StructureBuildingException { List<Atom> neighbours = atom.getAtomNeighbours(); for (Atom neighbour : neighbours) { if (neighbour.getElement().equals("O") && neighbour.getCharge()==0 && neighbour.getAtomNeighbours().size()==1 && atom.getBondToAtomOrThrow(neighbour).getOrder()==1){ neighbour.getFrag().addFunctionalAtom(neighbour); } } } /** * Finds all hydroxy groups connected to a given atom and makes them negatively charged * @param atom * @throws StructureBuildingException */ private void chargeHydroxyGroups(Atom atom) throws StructureBuildingException { List<Atom> neighbours = atom.getAtomNeighbours(); for (Atom neighbour : neighbours) { if (neighbour.getElement().equals("O") && neighbour.getCharge()==0 && neighbour.getAtomNeighbours().size()==1 && atom.getBondToAtomOrThrow(neighbour).getOrder()==1){ neighbour.addChargeAndProtons(-1, -1); } } } /** * Removes a double bonded Oxygen from the atom (an [N+][O-] is treated as N=O) * An exception is thrown if no double bonded oxygen could be found connected to the atom * @param state * @param atom * @throws StructureBuildingException */ private void removeOneDoubleBondedOxygen(BuildState state, Atom atom) throws StructureBuildingException { //TODO prioritise [N+][O-] List<Atom> neighbours = atom.getAtomNeighbours(); for (Atom neighbour : neighbours) { if (neighbour.getElement().equals("O") && neighbour.getAtomNeighbours().size()==1){ Bond b = atom.getBondToAtomOrThrow(neighbour); if (b.getOrder()==2 && neighbour.getCharge()==0){ state.fragManager.removeAtomAndAssociatedBonds(neighbour); if (atom.getLambdaConventionValency()!=null){//corrects valency for phosphin/arsin/stibin atom.setLambdaConventionValency(atom.getLambdaConventionValency()-2); } if (atom.getMinimumValency()!=null){//corrects valency for phosphin/arsin/stibin atom.setMinimumValency(atom.getMinimumValency()-2); } return; } else if (neighbour.getCharge() ==-1 && b.getOrder()==1){ if (atom.getCharge() ==1 && atom.getElement().equals("N")){ state.fragManager.removeAtomAndAssociatedBonds(neighbour); atom.neutraliseCharge(); return; } } } } throw new StructureBuildingException("Double bonded oxygen not found in fragment. Perhaps a suffix has been used inappropriately"); } /** * * @param state * @param frag * @throws StructureBuildingException */ private void convertHydroxyGroupsToOutAtoms(BuildState state, Fragment frag) throws StructureBuildingException { List<Atom> atomList = frag.getAtomList(); for (Atom atom : atomList) { if (atom.getElement().equals("O") && atom.getCharge()==0){ List<Atom> neighbours = atom.getAtomNeighbours(); if (neighbours.size()==1 && atom.getBondToAtomOrThrow(neighbours.get(0)).getOrder()==1){ state.fragManager.removeAtomAndAssociatedBonds(atom); frag.addOutAtom(neighbours.get(0), 1, true); } } } } /** * Returns the appropriate suffixRule tags for the given arguements. * The suffix rule tags are the children of the appropriate rule in suffixRules.xml * @param suffixTypeToUse * @param suffixValue * @param subgroupType * @return * @throws ComponentGenerationException */ private Elements getSuffixRuleTags(String suffixTypeToUse, String suffixValue, String subgroupType) throws ComponentGenerationException { HashMap<String, List<Element>> groupToSuffixMap = suffixApplicability.get(suffixTypeToUse); if (groupToSuffixMap==null){ throw new ComponentGenerationException("Suffix Type: "+ suffixTypeToUse + " does not have a corresponding groupType entry in suffixApplicability.xml"); } List<Element> potentiallyApplicableSuffixes =groupToSuffixMap.get(suffixValue); if(potentiallyApplicableSuffixes==null || potentiallyApplicableSuffixes.size()==0 ) { throw new ComponentGenerationException("Suffix: " +suffixValue +" does not apply to the group it was associated with (type: "+ suffixTypeToUse + ")according to suffixApplicability.xml"); } Element chosenSuffix=null; for (Element suffix : potentiallyApplicableSuffixes) { if (suffix.getAttribute(SUFFIXAPPLICABILITY_SUBTYPE_ATR) != null) { if (!suffix.getAttributeValue(SUFFIXAPPLICABILITY_SUBTYPE_ATR).equals(subgroupType)) { continue; } } if (chosenSuffix != null) { throw new ComponentGenerationException("Suffix: " + suffixValue + " appears multiple times in suffixApplicability.xml"); } chosenSuffix = suffix; } if (chosenSuffix==null){ throw new ComponentGenerationException("Suffix: " +suffixValue +" does not apply to the group it was associated with (type: "+ suffixTypeToUse + ")due to the group's subType: "+ subgroupType +" according to suffixApplicability.xml"); } Element rule =suffixRules.get(chosenSuffix.getValue()); if(rule ==null) { throw new ComponentGenerationException("Suffix: " +chosenSuffix.getValue() +" does not have a rule associated with it in suffixRules.xml"); } return rule.getChildElements(); } /** * Searches for suffix elements with the suffixPrefix attribute set * A suffixPrefix is something like sulfon in sulfonamide. It would in this case take the value S(=O) * @param state * @param suffixes * @throws StructureBuildingException */ private void processSuffixPrefixes(BuildState state, List<Element> suffixes) throws StructureBuildingException{ for (Element suffix : suffixes) { if (suffix.getAttribute(SUFFIXPREFIX_ATR)!=null){ Fragment suffixPrefixFrag = state.fragManager.buildSMILES(suffix.getAttributeValue(SUFFIXPREFIX_ATR), SUFFIX_TYPE_VAL, NONE_LABELS_VAL); addFunctionalAtomsToHydroxyGroups(suffixPrefixFrag.getFirstAtom()); if (suffix.getValue().endsWith("ate") || suffix.getValue().endsWith("at")){ chargeHydroxyGroups(suffixPrefixFrag.getFirstAtom()); } Atom firstAtomOfPrefix = suffixPrefixFrag.getFirstAtom(); firstAtomOfPrefix.addLocant("X");//make sure this atom is not given a locant Fragment suffixFrag = state.xmlFragmentMap.get(suffix); state.fragManager.incorporateFragment(suffixPrefixFrag, suffixFrag); //manipulate suffixFrag such that all the bonds to the first atom (the R) go instead to the first atom of suffixPrefixFrag. //Then reconnect the R to that atom Atom theR = suffixFrag.getFirstAtom(); List<Atom> neighbours = theR.getAtomNeighbours(); for (Atom neighbour : neighbours) { Bond b = theR.getBondToAtomOrThrow(neighbour); state.fragManager.removeBond(b); state.fragManager.createBond(neighbour, firstAtomOfPrefix, b.getOrder()); } state.fragManager.createBond(firstAtomOfPrefix, theR, 1); } } } /** * Checks through the groups accesible from the startingElement taking into account brackets (i.e. those that it is feasible that the group of the startingElement could substitute onto). * It is assumed that one does not intentionally locant onto something in a deeper level of bracketting (not implicit bracketing). e.g. 2-propyl(ethyl)ammonia will give prop-2-yl * @param state * @param startingElement * @param locant: the locant string to check for the presence of * @return whether the locant was found * @throws StructureBuildingException */ private boolean checkLocantPresentOnPotentialRoot(BuildState state, Element startingElement, String locant) throws StructureBuildingException { boolean foundSibling =false; Stack<Element> s = new Stack<Element>(); s.add(startingElement); boolean doneFirstIteration =false;//check on index only done on first iteration to only get elements with an index greater than the starting element while (s.size()>0){ Element currentElement =s.pop(); Element parent = (Element)currentElement.getParent(); List<Element> siblings = XOMTools.getChildElementsWithTagNames(parent, new String[]{BRACKET_EL, SUBSTITUENT_EL, ROOT_EL}); int indexOfCurrentElement =parent.indexOf(currentElement); for (Element bracketOrSub : siblings) { if (!doneFirstIteration && parent.indexOf(bracketOrSub) <= indexOfCurrentElement){ continue; } if (bracketOrSub.getLocalName().equals(BRACKET_EL)){//only want to consider implicit brackets, not proper brackets if (bracketOrSub.getAttribute(TYPE_ATR)==null){ continue; } s.push((Element)bracketOrSub.getChild(0)); } else{ Element group = bracketOrSub.getFirstChildElement(GROUP_EL); Fragment groupFrag =state.xmlFragmentMap.get(group); if (groupFrag.hasLocant(locant)){ return true; } List<Fragment> suffixes =state.xmlSuffixMap.get(group); if (suffixes!=null){ for (Fragment suffix : suffixes) { if (suffix.hasLocant(locant)){ return true; } } } List<Element> conjunctiveGroups = XOMTools.getNextSiblingsOfType(group, CONJUNCTIVESUFFIXGROUP_EL); for (Element conjunctiveGroup : conjunctiveGroups) { if (state.xmlFragmentMap.get(conjunctiveGroup).hasLocant(locant)){ return true; } } } foundSibling =true; } doneFirstIteration =true; } if (!foundSibling){//Special case: anything the group could potentially substitute onto is in a bracket. The bracket is checked recursively s = new Stack<Element>(); s.add(startingElement); doneFirstIteration =false;//check on index only done on first iteration to only get elements with an index greater than the starting element while (s.size()>0){ Element currentElement =s.pop(); Element parent = (Element)currentElement.getParent(); List<Element> siblings = XOMTools.getChildElementsWithTagNames(parent, new String[]{BRACKET_EL, SUBSTITUENT_EL, ROOT_EL}); int indexOfCurrentElement =parent.indexOf(currentElement); for (Element bracketOrSub : siblings) { if (!doneFirstIteration && parent.indexOf(bracketOrSub) <= indexOfCurrentElement){ continue; } if (bracketOrSub.getLocalName().equals(BRACKET_EL)){ s.push((Element)bracketOrSub.getChild(0)); } else{ Element group = bracketOrSub.getFirstChildElement(GROUP_EL); Fragment groupFrag =state.xmlFragmentMap.get(group); if (groupFrag.hasLocant(locant)){ return true; } List<Fragment> suffixes =state.xmlSuffixMap.get(group); if (suffixes!=null){ for (Fragment suffix : suffixes) { if (suffix.hasLocant(locant)){ return true; } } } List<Element> conjunctiveGroups = XOMTools.getNextSiblingsOfType(group, CONJUNCTIVESUFFIXGROUP_EL); for (Element conjunctiveGroup : conjunctiveGroups) { if (state.xmlFragmentMap.get(conjunctiveGroup).hasLocant(locant)){ return true; } } } } doneFirstIteration =true; } } return false; } /** Handles special cases in IUPAC nomenclature that are most elegantly solved by modification of the fragment * @param state * @param groups * @throws StructureBuildingException */ private static void handleGroupIrregularities(BuildState state, List<Element> groups) throws StructureBuildingException{ for (Element group : groups) { String groupValue =group.getValue(); if (groupValue.equals("porphyrin")|| groupValue.equals("porphin")){ List<Element> hydrogenAddingEls = XOMTools.getChildElementsWithTagName((Element) group.getParent(), INDICATEDHYDROGEN_EL); boolean implicitHydrogenExplicitlySet =false; for (Element hydrogenAddingEl : hydrogenAddingEls) { String locant = hydrogenAddingEl.getAttributeValue(LOCANT_ATR); if (locant !=null && (locant.equals("21") || locant.equals("22") || locant.equals("23") || locant.equals("24"))){ implicitHydrogenExplicitlySet =true; } } if (!implicitHydrogenExplicitlySet){ //porphyrins implicitly have indicated hydrogen at the 21/23 positions //directly modify the fragment to avoid problems with locants in for example ring assemblies Fragment frag =state.xmlFragmentMap.get(group); frag.getAtomByLocantOrThrow("21").setSpareValency(false); frag.getAtomByLocantOrThrow("23").setSpareValency(false); } } } } /** * Handles Hantzsch-Widman rings. Adds SMILES to the group corresponding to the ring's structure * @param state * @param subOrRoot * @throws StructureBuildingException * @throws ComponentGenerationException */ private void processHW(BuildState state, Element subOrRoot) throws StructureBuildingException, ComponentGenerationException{ List<Element> hwGroups = XOMTools.getChildElementsWithTagNameAndAttribute(subOrRoot, GROUP_EL, SUBTYPE_ATR, HANTZSCHWIDMAN_SUBTYPE_VAL); for (Element group : hwGroups) { Fragment hwRing =state.xmlFragmentMap.get(group); List<Atom> atomList =hwRing.getAtomList(); Element prev = (Element) XOMTools.getPreviousSibling(group); ArrayList<Element> prevs = new ArrayList<Element>(); boolean noLocants = true; while(prev != null && prev.getLocalName().equals(HETEROATOM_EL)) { prevs.add(prev); if(prev.getAttribute(LOCANT_ATR) != null) { noLocants = false; } prev = (Element) XOMTools.getPreviousSibling(prev); } if (atomList.size() == 6 && group.getValue().equals("an")){ boolean hasNitrogen = false; boolean hasSiorGeorSnorPb=false; boolean saturatedRing =true; for(Element heteroatom : prevs){ String heteroAtomElement =heteroatom.getAttributeValue(VALUE_ATR); Matcher m = matchElementSymbol.matcher(heteroAtomElement); if (!m.find()){ throw new ComponentGenerationException("Failed to extract element from HW heteroatom"); } heteroAtomElement = m.group(); if (heteroAtomElement.equals("N")){ hasNitrogen=true; } if (heteroAtomElement.equals("Si") || heteroAtomElement.equals("Ge") || heteroAtomElement.equals("Sn") || heteroAtomElement.equals("Pb") ){ hasSiorGeorSnorPb =true; } } for (Atom a: atomList) { if (a.hasSpareValency()){ saturatedRing =false; } } if (saturatedRing && !hasNitrogen && hasSiorGeorSnorPb){ throw new ComponentGenerationException("Blocked HW system (6 member saturated ring with no nitrogen but has Si/Ge/Sn/Pb)"); } } StringBuilder nameSB = new StringBuilder(); Collections.reverse(prevs); for(Element heteroatom : prevs){ nameSB.append(heteroatom.getValue()); } nameSB.append(group.getValue()); String name = nameSB.toString().toLowerCase(); if(noLocants && prevs.size() > 0) { if(specialHWRings.containsKey(name)) { String[] specialRingInformation =specialHWRings.get(name); String specialInstruction =specialRingInformation[0]; if (!specialInstruction.equals("")){ if (specialInstruction.equals("blocked")){ throw new ComponentGenerationException("Blocked HW system"); } else if (specialInstruction.equals("saturated")){ for (Atom a: hwRing.getAtomList()) { a.setSpareValency(false); } } else if (specialInstruction.equals("not_icacid")){ if (group.getAttribute(SUBSEQUENTUNSEMANTICTOKEN_ATR)==null){ Element nextEl = (Element) XOMTools.getNextSibling(group); if (nextEl!=null && nextEl.getLocalName().equals(SUFFIX_EL) && nextEl.getAttribute(LOCANT_ATR)==null && nextEl.getAttributeValue(VALUE_ATR).equals("ic")){ throw new ComponentGenerationException(name + nextEl.getValue() +" appears to be a generic class name, not a HW ring"); } } } else if (specialInstruction.equals("not_nothingOrOlate")){ if (group.getAttribute(SUBSEQUENTUNSEMANTICTOKEN_ATR)==null){ Element nextEl = (Element) XOMTools.getNextSibling(group); if (nextEl==null || (nextEl!=null && nextEl.getLocalName().equals(SUFFIX_EL) && nextEl.getAttribute(LOCANT_ATR)==null && nextEl.getAttributeValue(VALUE_ATR).equals("ate"))){ throw new ComponentGenerationException(name +" has the syntax for a HW ring but probably does not mean that in this context"); } } } else{ throw new ComponentGenerationException("OPSIN Bug: Unrecognised special HW ring instruction"); } } //something like oxazole where by convention locants go 1,3 or a inorganic HW-like system for (int j = 1; j < specialRingInformation.length; j++) { Atom a =hwRing.getAtomByLocantOrThrow(Integer.toString(j)); a.setElement(specialRingInformation[j]); } for(Element p : prevs){ p.detach(); } prevs.clear(); } } HashSet<Element> elementsToRemove =new HashSet<Element>(); for(Element heteroatom : prevs){//add locanted heteroatoms if (heteroatom.getAttribute(LOCANT_ATR) !=null){ String locant =heteroatom.getAttributeValue(LOCANT_ATR); String elementReplacement =heteroatom.getAttributeValue(VALUE_ATR); Matcher m = matchElementSymbol.matcher(elementReplacement); if (!m.find()){ throw new ComponentGenerationException("Failed to extract element from HW heteroatom"); } elementReplacement = m.group(); Atom a =hwRing.getAtomByLocantOrThrow(locant); a.setElement(elementReplacement); if (heteroatom.getAttribute(LAMBDA_ATR)!=null){ a.setLambdaConventionValency(Integer.parseInt(heteroatom.getAttributeValue(LAMBDA_ATR))); } heteroatom.detach(); elementsToRemove.add(heteroatom); } } for(Element p : elementsToRemove){ prevs.remove(p); } //add unlocanted heteroatoms int defaultLocant=1; for(Element heteroatom : prevs){ String elementReplacement =heteroatom.getAttributeValue(VALUE_ATR); Matcher m = matchElementSymbol.matcher(elementReplacement); if (!m.find()){ throw new ComponentGenerationException("Failed to extract element from HW heteroatom"); } elementReplacement = m.group(); while (!hwRing.getAtomByLocantOrThrow(Integer.toString(defaultLocant)).getElement().equals("C")){ defaultLocant++; } Atom a =hwRing.getAtomByLocantOrThrow(Integer.toString(defaultLocant)); a.setElement(elementReplacement); if (heteroatom.getAttribute(LAMBDA_ATR)!=null){ a.setLambdaConventionValency(Integer.parseInt(heteroatom.getAttributeValue(LAMBDA_ATR))); } heteroatom.detach(); } Elements deltas = subOrRoot.getChildElements(DELTA_EL);//add specified double bonds for (int j = 0; j < deltas.size(); j++) { String locantOfDoubleBond = deltas.get(j).getValue(); if (locantOfDoubleBond.equals("")){ Element newUnsaturator = new Element(UNSATURATOR_EL); newUnsaturator.addAttribute(new Attribute(VALUE_ATR, "2")); XOMTools.insertAfter(group, newUnsaturator); } else{ Atom firstInDoubleBond = hwRing.getAtomByLocantOrThrow(locantOfDoubleBond); Atom secondInDoubleBond = hwRing.getAtomByIDOrThrow(firstInDoubleBond.getID() +1); Bond b = firstInDoubleBond.getBondToAtomOrThrow(secondInDoubleBond); b.setOrder(2); } deltas.get(j).detach(); } XOMTools.setTextChild(group, name); } } /** * Assigns Element symbols to groups, suffixes and conjunctive suffixes. * Suffixes have preference. * @param state * @param subOrRoot * @throws StructureBuildingException */ private void assignElementSymbolLocants(BuildState state, Element subOrRoot) throws StructureBuildingException { List<Element> groups = XOMTools.getChildElementsWithTagName(subOrRoot, GROUP_EL); Element lastGroupElementInSubOrRoot =groups.get(groups.size()-1); List<Fragment> suffixFragments = new ArrayList<Fragment>(state.xmlSuffixMap.get(lastGroupElementInSubOrRoot)); Fragment suffixableFragment =state.xmlFragmentMap.get(lastGroupElementInSubOrRoot); //treat conjunctive suffixesas if they were suffixes List<Element> conjunctiveGroups = XOMTools.getChildElementsWithTagName(subOrRoot, CONJUNCTIVESUFFIXGROUP_EL); for (Element group : conjunctiveGroups) { suffixFragments.add(state.xmlFragmentMap.get(group)); } FragmentTools.assignElementLocants(suffixableFragment, suffixFragments); for (int i = groups.size()-2; i>=0; i FragmentTools.assignElementLocants(state.xmlFragmentMap.get(groups.get(i)), new ArrayList<Fragment>()); } } /** * Processes constructs such as biphenyl, 1,1':4',1''-Terphenyl, 2,2'-Bipyridylium, m-Quaterphenyl * @param state * @param subOrRoot * @throws ComponentGenerationException * @throws StructureBuildingException */ private void processRingAssemblies(BuildState state, Element subOrRoot) throws ComponentGenerationException, StructureBuildingException { List<Element> ringAssemblyMultipliers = XOMTools.getChildElementsWithTagName(subOrRoot, RINGASSEMBLYMULTIPLIER_EL); for (Element multiplier : ringAssemblyMultipliers) { int mvalue = Integer.parseInt(multiplier.getAttributeValue(VALUE_ATR)); /* * Populate locants with locants. Two locants are required for every pair of rings to be joined. * e.g. bi requires 2, ter requires 4 etc. */ List<List<String>> ringJoiningLocants =new ArrayList<List<String>>(); Element potentialLocant =(Element)XOMTools.getPreviousSibling(multiplier); Element group =(Element)XOMTools.getNextSibling(multiplier, GROUP_EL); if (potentialLocant!=null && (potentialLocant.getLocalName().equals(COLONSEPERATEDLOCANT_EL)||potentialLocant.getLocalName().equals(LOCANT_EL)) ){//a locant appears to have been provided to indicate how to connect the rings of the ringAssembly if (ORTHOMETAPARA_TYPE_VAL.equals(potentialLocant.getAttributeValue(TYPE_ATR))){//an OMP locant has been provided to indicate how to connect the rings of the ringAssembly String locant2 =potentialLocant.getValue(); String locant1 ="1"; ArrayList<String> locantArrayList =new ArrayList<String>(); locantArrayList.add("1"); locantArrayList.add("1'"); ringJoiningLocants.add(locantArrayList); for (int j = 1; j < mvalue -1; j++) { locantArrayList =new ArrayList<String>(); locantArrayList.add(locant2 + StringTools.multiplyString("'", j)); locantArrayList.add(locant1 + StringTools.multiplyString("'", j+1)); ringJoiningLocants.add(locantArrayList); } potentialLocant.detach(); } else{ String locantText =StringTools.removeDashIfPresent(potentialLocant.getValue()); //locantText might be something like 1,1':3',1'' String[] perRingLocantArray =matchColon.split(locantText); if (perRingLocantArray.length !=(mvalue -1)){ throw new ComponentGenerationException("Disagreement between number of locants(" + locantText +") and ring assembly multiplier: " + mvalue); } if (perRingLocantArray.length!=1 || matchComma.split(perRingLocantArray[0]).length!=1){//not for the case of a single locant for (int j = 0; j < perRingLocantArray.length; j++) { String[] locantArray = matchComma.split(perRingLocantArray[j]); if (locantArray.length !=2){ throw new ComponentGenerationException("missing locant, expected 2 locants: " + perRingLocantArray[j]); } ringJoiningLocants.add(Arrays.asList(locantArray)); } potentialLocant.detach(); } } } Fragment fragmentToResolveAndDuplicate =state.xmlFragmentMap.get(group); Element elementToResolve;//temporary element containing elements that should be resolved before the ring is duplicated Element nextEl =(Element) XOMTools.getNextSibling(multiplier); if (nextEl.getLocalName().equals(STRUCTURALOPENBRACKET_EL)){//brackets have been provided to aid disambiguation. These brackets are detached e.g. bi(cyclohexyl) elementToResolve = new Element(SUBSTITUENT_EL); Element currentEl =nextEl; nextEl = (Element) XOMTools.getNextSibling(currentEl); currentEl.detach(); while (nextEl !=null && !nextEl.getLocalName().equals(STRUCTURALCLOSEBRACKET_EL)){ currentEl =nextEl; nextEl = (Element) XOMTools.getNextSibling(currentEl); currentEl.detach(); elementToResolve.appendChild(currentEl); } if (nextEl!=null){ nextEl.detach(); } } else{ elementToResolve = determineElementsToResolveIntoRingAssembly(multiplier, ringJoiningLocants.size(), fragmentToResolveAndDuplicate.getOutAtoms().size(), state); } List<Element> suffixes = XOMTools.getChildElementsWithTagName(elementToResolve, SUFFIX_EL); resolveSuffixes(state, group, suffixes); StructureBuildingMethods.resolveLocantedFeatures(state, elementToResolve); StructureBuildingMethods.resolveUnLocantedFeatures(state, elementToResolve); group.detach(); XOMTools.insertAfter(multiplier, group); int bondOrder = 1; if (fragmentToResolveAndDuplicate.getOutAtoms().size()>0){//e.g. bicyclohexanylidene bondOrder =fragmentToResolveAndDuplicate.getOutAtom(0).getValency(); } if (fragmentToResolveAndDuplicate.getOutAtoms().size()>1){ throw new StructureBuildingException("Ring assembly fragment should have one or no OutAtoms; not more than one!"); } List<Fragment> clonedFragments = new ArrayList<Fragment>(); for (int j = 1; j < mvalue; j++) { clonedFragments.add(state.fragManager.copyAndRelabelFragment(fragmentToResolveAndDuplicate, j)); } for (int j = 0; j < mvalue-1; j++) { Fragment clone =clonedFragments.get(j); Atom atomOnParent; Atom atomOnLatestClone; if (ringJoiningLocants.size()>0){//locants defined atomOnParent = fragmentToResolveAndDuplicate.getAtomByLocantOrThrow(ringJoiningLocants.get(j).get(0)); atomOnLatestClone = clone.getAtomByLocantOrThrow(ringJoiningLocants.get(j).get(1)); } else{ if (fragmentToResolveAndDuplicate.getOutAtoms().size()>0 && mvalue==2){ atomOnParent = fragmentToResolveAndDuplicate.getOutAtom(0).getAtom(); atomOnLatestClone = clone.getOutAtom(0).getAtom(); } else{ atomOnParent =fragmentToResolveAndDuplicate.getAtomOrNextSuitableAtomOrThrow(fragmentToResolveAndDuplicate.getDefaultInAtom(), bondOrder, true); atomOnLatestClone = clone.getAtomOrNextSuitableAtomOrThrow(clone.getDefaultInAtom(), bondOrder, true); } } if (fragmentToResolveAndDuplicate.getOutAtoms().size()>0){ fragmentToResolveAndDuplicate.removeOutAtom(0); } if (clone.getOutAtoms().size()>0){ clone.removeOutAtom(0); } state.fragManager.incorporateFragment(clone, atomOnLatestClone, fragmentToResolveAndDuplicate, atomOnParent, bondOrder); fragmentToResolveAndDuplicate.setDefaultInAtom(clone.getDefaultInAtom()); } XOMTools.setTextChild(group, multiplier.getValue() +group.getValue()); Element possibleOpenStructuralBracket = (Element) XOMTools.getPreviousSibling(multiplier); if (possibleOpenStructuralBracket!=null && possibleOpenStructuralBracket.getLocalName().equals(STRUCTURALOPENBRACKET_EL)){//e.g. [2,2'-bipyridin]. //To emphasise there can actually be two sets of structural brackets e.g. [1,1'-bi(cyclohexyl)] XOMTools.getNextSibling(possibleOpenStructuralBracket, STRUCTURALCLOSEBRACKET_EL).detach(); possibleOpenStructuralBracket.detach(); } multiplier.detach(); } } /** * Given the element after the ring assembly multiplier determines which siblings should be resolved by adding them to elementToResolve * @param ringJoiningLocants * @param elementAfterMultiplier * @param elementToResolve * @return * @throws ComponentGenerationException */ private Element determineElementsToResolveIntoRingAssembly(Element multiplier, int ringJoiningLocants, int outAtomCount, BuildState state) throws ComponentGenerationException { Element elementToResolve = new Element(SUBSTITUENT_EL); boolean groupFound = false; boolean inlineSuffixSeen = outAtomCount > 0; Element currentEl = (Element) XOMTools.getNextSibling(multiplier); while (currentEl !=null){ Element nextEl = (Element) XOMTools.getNextSibling(currentEl); if (!groupFound || currentEl.getLocalName().equals(SUFFIX_EL) && currentEl.getAttributeValue(TYPE_ATR).equals(CHARGE_TYPE_VAL)|| currentEl.getLocalName().equals(UNSATURATOR_EL)){ currentEl.detach(); elementToResolve.appendChild(currentEl); } else if (currentEl.getLocalName().equals(SUFFIX_EL)){ state.xmlFragmentMap.get(currentEl); if (!inlineSuffixSeen && currentEl.getAttributeValue(TYPE_ATR).equals(INLINE_TYPE_VAL) && currentEl.getAttributeValue(MULTIPLIED_ATR) ==null && (currentEl.getAttribute(LOCANT_ATR)==null || ("2".equals(multiplier.getAttributeValue(VALUE_ATR)) && ringJoiningLocants==0)) && state.xmlFragmentMap.get(currentEl)==null){ inlineSuffixSeen = true; currentEl.detach(); elementToResolve.appendChild(currentEl); } else{ break; } } else{ break; } if (currentEl.getLocalName().equals(GROUP_EL)){ groupFound = true; } currentEl = nextEl; } Element parent = (Element) multiplier.getParent(); if (!parent.getLocalName().equals(SUBSTITUENT_EL) && XOMTools.getChildElementsWithTagNameAndAttribute(parent, SUFFIX_EL, TYPE_ATR, INLINE_TYPE_VAL).size()!=0){ throw new ComponentGenerationException("Unexpected radical adding suffix on ring assembly"); } return elementToResolve; } private void processPolyCyclicSpiroNomenclature(BuildState state, Element subOrRoot) throws ComponentGenerationException, StructureBuildingException { List<Element> polyCyclicSpiros = XOMTools.getChildElementsWithTagName(subOrRoot, POLYCYCLICSPIRO_EL); if (polyCyclicSpiros.size()>0){ Element polyCyclicSpiroDescriptor = polyCyclicSpiros.get(0); String value = polyCyclicSpiroDescriptor.getAttributeValue(VALUE_ATR); if (value.equals("spiro")){ if (polyCyclicSpiros.size()!=1){ throw new ComponentGenerationException("Nested polyspiro systems are not supported"); } processNonIdenticalPolyCyclicSpiro(state, polyCyclicSpiroDescriptor); } else if (value.equals("spiroOldMethod")){ processOldMethodPolyCyclicSpiro(state, polyCyclicSpiros); } else if (value.equals("spirobi")){ if (polyCyclicSpiros.size()!=1){ throw new ComponentGenerationException("Nested polyspiro systems are not supported"); } processSpiroBiOrTer(state, polyCyclicSpiroDescriptor, 2); } else if (value.equals("spiroter")){ if (polyCyclicSpiros.size()!=1){ throw new ComponentGenerationException("Nested polyspiro systems are not supported"); } processSpiroBiOrTer(state, polyCyclicSpiroDescriptor, 3); } else if (value.equals("dispiroter")){ if (polyCyclicSpiros.size()!=1){ throw new ComponentGenerationException("Nested polyspiro systems are not supported"); } processDispiroter(state, polyCyclicSpiroDescriptor); } else{ throw new ComponentGenerationException("Unsupported spiro system encountered"); } polyCyclicSpiroDescriptor.detach(); } } private void processNonIdenticalPolyCyclicSpiro(BuildState state, Element polyCyclicSpiroDescriptor) throws ComponentGenerationException, StructureBuildingException { Element subOrRoot = (Element) polyCyclicSpiroDescriptor.getParent(); List<Element> groups = XOMTools.getChildElementsWithTagName(subOrRoot, GROUP_EL); if (groups.size()<2){ throw new ComponentGenerationException("OPSIN Bug: Atleast two groups were expected in polycyclic spiro system"); } Element openBracket = (Element) XOMTools.getNextSibling(polyCyclicSpiroDescriptor); if (!openBracket.getLocalName().equals(STRUCTURALOPENBRACKET_EL)){ throw new ComponentGenerationException("OPSIN Bug: Open bracket not found where open bracket expeced"); } List<Element> spiroBracketElements = XOMTools.getSiblingsUpToElementWithTagName(openBracket, STRUCTURALCLOSEBRACKET_EL); Element closeBracket = (Element) XOMTools.getNextSibling(spiroBracketElements.get(spiroBracketElements.size()-1)); if (closeBracket == null || !closeBracket.getLocalName().equals(STRUCTURALCLOSEBRACKET_EL)){ throw new ComponentGenerationException("OPSIN Bug: Open bracket not found where open bracket expeced"); } Element firstGroup = groups.get(0); List<Element> firstGroupEls = new ArrayList<Element>(); int indexOfOpenBracket = subOrRoot.indexOf(openBracket); int indexOfFirstGroup = subOrRoot.indexOf(firstGroup); for (int i =indexOfOpenBracket +1; i < indexOfFirstGroup; i++) { firstGroupEls.add((Element) subOrRoot.getChild(i)); } firstGroupEls.add(firstGroup); firstGroupEls.addAll(XOMTools.getNextAdjacentSiblingsOfType(firstGroup, UNSATURATOR_EL)); resolveFeaturesOntoGroup(state, firstGroupEls); Set<Atom> spiroAtoms = new HashSet<Atom>(); for (int i = 1; i < groups.size(); i++) { Element nextGroup =groups.get(i); Element locant = (Element) XOMTools.getNextSibling(groups.get(i-1), SPIROLOCANT_EL); if (locant ==null){ throw new ComponentGenerationException("Unable to find locantEl for polycyclic spiro system"); } List<Element> nextGroupEls = new ArrayList<Element>(); int indexOfLocant = subOrRoot.indexOf(locant); int indexOfNextGroup = subOrRoot.indexOf(nextGroup); for (int j =indexOfLocant +1; j < indexOfNextGroup; j++) { nextGroupEls.add((Element) subOrRoot.getChild(j)); } nextGroupEls.add(nextGroup); nextGroupEls.addAll(XOMTools.getNextAdjacentSiblingsOfType(nextGroup, UNSATURATOR_EL)); resolveFeaturesOntoGroup(state, nextGroupEls); String[] locants = matchComma.split(StringTools.removeDashIfPresent(locant.getValue())); if (locants.length!=2){ throw new ComponentGenerationException("Incorrect number of locants found before component of polycyclic spiro system"); } for (int j = 0; j < locants.length; j++) { String locantText= locants[j]; Matcher m = matchAddedHydrogenBracket.matcher(locantText); if (m.find()){ Element addedHydrogenElement=new Element(ADDEDHYDROGEN_EL); addedHydrogenElement.addAttribute(new Attribute(LOCANT_ATR, m.group(1))); XOMTools.insertBefore(locant, addedHydrogenElement); locant.addAttribute(new Attribute(TYPE_ATR, ADDEDHYDROGENLOCANT_TYPE_VAL)); locants[j] = m.replaceAll(""); } } locant.detach(); Fragment nextFragment = state.xmlFragmentMap.get(nextGroup); FragmentTools.relabelNumericLocants(nextFragment.getAtomList(), StringTools.multiplyString("'", i)); Atom atomToBeReplaced = nextFragment.getAtomByLocantOrThrow(locants[1]); Atom atomOnParentFrag = null; for (int j = 0; j < i; j++) { atomOnParentFrag = state.xmlFragmentMap.get(groups.get(j)).getAtomByLocant(locants[0]); if (atomOnParentFrag!=null){ break; } } if (atomOnParentFrag==null){ throw new ComponentGenerationException("Could not find the atom with locant " + locants[0] +" for use in polycyclic spiro system"); } spiroAtoms.add(atomOnParentFrag); state.fragManager.replaceAtomWithAnotherAtomPreservingConnectivity(atomToBeReplaced, atomOnParentFrag); if (atomToBeReplaced.hasSpareValency()){ atomOnParentFrag.setSpareValency(true); } } if (spiroAtoms.size()>1){ Element expectedMultiplier = (Element) XOMTools.getPreviousSibling(polyCyclicSpiroDescriptor); if (expectedMultiplier!=null && expectedMultiplier.getLocalName().equals(MULTIPLIER_EL) && Integer.parseInt(expectedMultiplier.getAttributeValue(VALUE_ATR))==spiroAtoms.size()){ expectedMultiplier.detach(); } } Element rootGroup = groups.get(groups.size()-1); Fragment rootFrag = state.xmlFragmentMap.get(rootGroup); String name = rootGroup.getValue(); for (int i = 0; i < groups.size() -1; i++) { Element group =groups.get(i); state.fragManager.incorporateFragment(state.xmlFragmentMap.get(group), rootFrag); name = group.getValue() + name; group.detach(); } XOMTools.setTextChild(rootGroup, polyCyclicSpiroDescriptor.getValue() + name); openBracket.detach(); closeBracket.detach(); } /** * Processes spiro systems described using the now deprectated method described in the 1979 guidelines Rule A-42 * @param state * @param spiroElements * @throws ComponentGenerationException * @throws StructureBuildingException */ private void processOldMethodPolyCyclicSpiro(BuildState state, List<Element> spiroElements) throws ComponentGenerationException, StructureBuildingException { Element firstSpiro =spiroElements.get(0); Element subOrRoot = (Element) firstSpiro.getParent(); Element firstEl = (Element) subOrRoot.getChild(0); List<Element> elementsToResolve = XOMTools.getSiblingsUpToElementWithTagName(firstEl, POLYCYCLICSPIRO_EL); elementsToResolve.add(0, firstEl); resolveFeaturesOntoGroup(state, elementsToResolve); for (int i = 0; i < spiroElements.size(); i++) { Element currentSpiro = spiroElements.get(i); Element previousGroup = (Element) XOMTools.getPreviousSibling(currentSpiro, GROUP_EL); if (previousGroup==null){ throw new ComponentGenerationException("OPSIN bug: unable to locate group before polycylic spiro descriptor"); } Element nextGroup = (Element) XOMTools.getNextSibling(currentSpiro, GROUP_EL); if (nextGroup==null){ throw new ComponentGenerationException("OPSIN bug: unable to locate group after polycylic spiro descriptor"); } Fragment parentFrag = state.xmlFragmentMap.get(nextGroup); Fragment previousFrag = state.xmlFragmentMap.get(previousGroup); FragmentTools.relabelNumericLocants(parentFrag.getAtomList(), StringTools.multiplyString("'",i+1)); elementsToResolve = XOMTools.getSiblingsUpToElementWithTagName(currentSpiro, POLYCYCLICSPIRO_EL); resolveFeaturesOntoGroup(state, elementsToResolve); String locant1 =null; Element possibleFirstLocant = (Element) XOMTools.getPreviousSibling(currentSpiro); if (possibleFirstLocant !=null && possibleFirstLocant.getLocalName().equals(LOCANT_EL)){ if (matchComma.split(possibleFirstLocant.getValue()).length==1){ locant1 = possibleFirstLocant.getValue(); possibleFirstLocant.detach(); } else{ throw new ComponentGenerationException("Malformed locant before polycyclic spiro descriptor"); } } Atom atomToBeReplaced; if (locant1 != null){ atomToBeReplaced = previousFrag.getAtomByLocantOrThrow(locant1); } else{ atomToBeReplaced = previousFrag.getAtomOrNextSuitableAtomOrThrow(previousFrag.getFirstAtom(), 2, true); } Atom atomOnParentFrag; String locant2 =null; Element possibleSecondLocant = (Element) XOMTools.getNextSibling(currentSpiro); if (possibleSecondLocant !=null && possibleSecondLocant.getLocalName().equals(LOCANT_EL)){ if (matchComma.split(possibleSecondLocant.getValue()).length==1){ locant2 = possibleSecondLocant.getValue(); possibleSecondLocant.detach(); } else{ throw new ComponentGenerationException("Malformed locant after polycyclic spiro descriptor"); } } if (locant2!=null){ atomOnParentFrag = parentFrag.getAtomByLocantOrThrow(locant2); } else{ atomOnParentFrag = parentFrag.getAtomOrNextSuitableAtomOrThrow(parentFrag.getFirstAtom(), 2, true); } state.fragManager.replaceAtomWithAnotherAtomPreservingConnectivity(atomToBeReplaced, atomOnParentFrag); if (atomToBeReplaced.hasSpareValency()){ atomOnParentFrag.setSpareValency(true); } if (atomToBeReplaced.getCharge()!=0 && atomOnParentFrag.getCharge()==0){ atomOnParentFrag.setCharge(atomToBeReplaced.getCharge()); atomOnParentFrag.setProtonsExplicitlyAddedOrRemoved(atomToBeReplaced.getProtonsExplicitlyAddedOrRemoved()); } state.fragManager.incorporateFragment(previousFrag, parentFrag); XOMTools.setTextChild(nextGroup, previousGroup.getValue() + currentSpiro.getValue() + nextGroup.getValue()); previousGroup.detach(); } } /** * Two or three copies of the fragment after polyCyclicSpiroDescriptor are spiro fused at one centre * @param state * @param polyCyclicSpiroDescriptor * @param components * @throws ComponentGenerationException * @throws StructureBuildingException */ private void processSpiroBiOrTer(BuildState state, Element polyCyclicSpiroDescriptor, int components) throws ComponentGenerationException, StructureBuildingException { Element locant = (Element) XOMTools.getPreviousSibling(polyCyclicSpiroDescriptor); String locantText; if (locant ==null || !locant.getLocalName().equals(LOCANT_EL)){ if (components==2){ locantText ="1,1'"; } else{ throw new ComponentGenerationException("Unable to find locant indicating atoms to form polycyclic spiro system!"); } } else{ locantText = locant.getValue(); locant.detach(); } String[] locants = matchComma.split(locantText); if (locants.length!=components){ throw new ComponentGenerationException("Mismatch between spiro descriptor and number of locants provided"); } Element group = (Element) XOMTools.getNextSibling(polyCyclicSpiroDescriptor, GROUP_EL); if (group==null){ throw new ComponentGenerationException("Cannot find group to which spirobi/ter descriptor applies"); } determineFeaturesToResolveInSingleComponentSpiro(state, polyCyclicSpiroDescriptor); Fragment fragment = state.xmlFragmentMap.get(group); List<Fragment> clones = new ArrayList<Fragment>(); for (int i = 1; i < components ; i++) { clones.add(state.fragManager.copyAndRelabelFragment(fragment, i)); } for (Fragment clone : clones) { state.fragManager.incorporateFragment(clone, fragment); } Atom atomOnOriginalFragment = fragment.getAtomByLocantOrThrow(locants[0]); for (int i = 1; i < components ; i++) { Atom atomToBeReplaced = fragment.getAtomByLocantOrThrow(locants[i]); state.fragManager.replaceAtomWithAnotherAtomPreservingConnectivity(atomToBeReplaced, atomOnOriginalFragment); if (atomToBeReplaced.hasSpareValency()){ atomOnOriginalFragment.setSpareValency(true); } } XOMTools.setTextChild(group, polyCyclicSpiroDescriptor.getValue() + group.getValue()); } /** * Three copies of the fragment after polyCyclicSpiroDescriptor are spiro fused at two centres * @param state * @param polyCyclicSpiroDescriptor * @throws StructureBuildingException * @throws ComponentGenerationException */ private void processDispiroter(BuildState state, Element polyCyclicSpiroDescriptor) throws StructureBuildingException, ComponentGenerationException { String value = polyCyclicSpiroDescriptor.getValue(); value = value.substring(0, value.length()-10);//remove dispiroter value = StringTools.removeDashIfPresent(value); String[] locants = matchColon.split(value); Element group = (Element) XOMTools.getNextSibling(polyCyclicSpiroDescriptor, GROUP_EL); if (group==null){ throw new ComponentGenerationException("Cannot find group to which dispiroter descriptor applies"); } determineFeaturesToResolveInSingleComponentSpiro(state, polyCyclicSpiroDescriptor); Fragment fragment = state.xmlFragmentMap.get(group); List<Fragment> clones = new ArrayList<Fragment>(); for (int i = 1; i < 3 ; i++) { clones.add(state.fragManager.copyAndRelabelFragment(fragment, i)); } for (Fragment clone : clones) { state.fragManager.incorporateFragment(clone, fragment); } Atom atomOnLessPrimedFragment = fragment.getAtomByLocantOrThrow(matchComma.split(locants[0])[0]); Atom atomToBeReplaced = fragment.getAtomByLocantOrThrow(matchComma.split(locants[0])[1]); state.fragManager.replaceAtomWithAnotherAtomPreservingConnectivity(atomToBeReplaced, atomOnLessPrimedFragment); if (atomToBeReplaced.hasSpareValency()){ atomOnLessPrimedFragment.setSpareValency(true); } atomOnLessPrimedFragment = fragment.getAtomByLocantOrThrow(matchComma.split(locants[1])[0]); atomToBeReplaced = fragment.getAtomByLocantOrThrow(matchComma.split(locants[1])[1]); state.fragManager.replaceAtomWithAnotherAtomPreservingConnectivity(atomToBeReplaced, atomOnLessPrimedFragment); if (atomToBeReplaced.hasSpareValency()){ atomOnLessPrimedFragment.setSpareValency(true); } XOMTools.setTextChild(group, "dispiroter" + group.getValue()); } /** * The features between the polyCyclicSpiroDescriptor and the first group element, or beween the STRUCTURALOPENBRACKET_EL and STRUCTURALCLOSEBRACKET_EL * are found and then passed to resolveFeaturesOntoGroup * @param state * @param polyCyclicSpiroDescriptor * @throws StructureBuildingException * @throws ComponentGenerationException */ private void determineFeaturesToResolveInSingleComponentSpiro(BuildState state, Element polyCyclicSpiroDescriptor) throws StructureBuildingException, ComponentGenerationException { Element possibleOpenBracket = (Element) XOMTools.getNextSibling(polyCyclicSpiroDescriptor); List<Element> elementsToResolve; if (possibleOpenBracket.getLocalName().equals(STRUCTURALOPENBRACKET_EL)){ possibleOpenBracket.detach(); elementsToResolve = XOMTools.getSiblingsUpToElementWithTagName(polyCyclicSpiroDescriptor, STRUCTURALCLOSEBRACKET_EL); XOMTools.getNextSibling(elementsToResolve.get(elementsToResolve.size()-1)).detach();//detach close bracket } else{ elementsToResolve = XOMTools.getSiblingsUpToElementWithTagName(polyCyclicSpiroDescriptor, GROUP_EL); } resolveFeaturesOntoGroup(state, elementsToResolve); } /** * Given some elements including a group element resolves all locanted and unlocanted features. * If suffixes are present these are resolved and detached * @param state * @param elementsToResolve * @throws StructureBuildingException * @throws ComponentGenerationException */ private void resolveFeaturesOntoGroup(BuildState state, List<Element> elementsToResolve) throws StructureBuildingException, ComponentGenerationException{ if (elementsToResolve.size()==0){ return; } Element substituentToResolve = new Element(SUBSTITUENT_EL);//temporary element containing elements that should be resolved before the ring is cloned Element parent = (Element) elementsToResolve.get(0).getParent(); int index = parent.indexOf(elementsToResolve.get(0)); Element group =null; List<Element> suffixes = new ArrayList<Element>(); Element locant =null; for (Element element : elementsToResolve) { String elName =element.getLocalName(); if (elName.equals(GROUP_EL)){ group = element; } else if (elName.equals(SUFFIX_EL)){ suffixes.add(element); } else if (elName.equals(LOCANT_EL) && group==null){ locant = element; } element.detach(); substituentToResolve.appendChild(element); } if (group ==null){ throw new ComponentGenerationException("OPSIN bug: group element should of been given to method"); } if (locant !=null){//locant is probably an indirect locant, try and assign it List<Element> locantAble = findElementsMissingIndirectLocants(substituentToResolve, locant); String[] locantValues = matchComma.split(locant.getValue()); if (locantAble.size() >= locantValues.length){ for (int i = 0; i < locantValues.length; i++) { String locantValue = locantValues[i]; locantAble.get(i).addAttribute(new Attribute(LOCANT_ATR, locantValue)); } locant.detach(); } } if (!suffixes.isEmpty()){ resolveSuffixes(state, group, suffixes); for (Element suffix : suffixes) { suffix.detach(); } } if (substituentToResolve.getChildElements().size()!=0){ StructureBuildingMethods.resolveLocantedFeatures(state, substituentToResolve); StructureBuildingMethods.resolveUnLocantedFeatures(state, substituentToResolve); Elements children = substituentToResolve.getChildElements(); for (int i = children.size() -1; i>=0; i Element child = children.get(i); child.detach(); parent.insertChild(child, index); } } } /** * Processes bridges e.g. 4,7-methanoindene * Resolves and attaches said bridges to the adjacent ring fragment * @param state * @param subOrRoot * @throws StructureBuildingException */ private void processFusedRingBridges(BuildState state, Element subOrRoot) throws StructureBuildingException { List<Element> bridges = XOMTools.getChildElementsWithTagName(subOrRoot, FUSEDRINGBRIDGE_EL); for (Element bridge : bridges) { Fragment ringFrag = state.xmlFragmentMap.get(XOMTools.getNextSibling(bridge, GROUP_EL)); Fragment bridgeFrag =state.fragManager.buildSMILES(bridge.getAttributeValue(VALUE_ATR), ringFrag.getType(), ringFrag.getSubType(), NONE_LABELS_VAL);//TODO label bridges List<Atom> bridgeAtomList =bridgeFrag.getAtomList(); bridgeFrag.addOutAtom(bridgeAtomList.get(0), 1, true); bridgeFrag.addOutAtom(bridgeAtomList.get(bridgeAtomList.size()-1), 1, true); Element possibleLocant = (Element) XOMTools.getPreviousSibling(bridge); if (possibleLocant !=null && possibleLocant.getLocalName().equals(LOCANT_EL)){ String[] locantArray = matchComma.split(possibleLocant.getValue()); if (locantArray.length==2){ bridgeFrag.getOutAtom(0).setLocant(locantArray[0]); bridgeFrag.getOutAtom(1).setLocant(locantArray[1]); possibleLocant.detach(); } StructureBuildingMethods.formEpoxide(state, bridgeFrag, ringFrag.getDefaultInAtom()); } else{ StructureBuildingMethods.formEpoxide(state, bridgeFrag, ringFrag.getAtomOrNextSuitableAtomOrThrow(ringFrag.getDefaultInAtom(), 1, true)); } state.fragManager.incorporateFragment(bridgeFrag, ringFrag); bridge.detach(); } } /** * Searches for lambdaConvention elements and applies the valency they specify to the atom * they specify on the substituent/root's fragment * @param state * @param subOrRoot * @throws StructureBuildingException */ private void applyLambdaConvention(BuildState state, Element subOrRoot) throws StructureBuildingException { List<Element> lambdaConventionEls = XOMTools.getChildElementsWithTagName(subOrRoot, LAMBDACONVENTION_EL); for (Element lambdaConventionEl : lambdaConventionEls) { Fragment frag = state.xmlFragmentMap.get(subOrRoot.getFirstChildElement(GROUP_EL)); if (lambdaConventionEl.getAttribute(LOCANT_ATR)!=null){ frag.getAtomByLocantOrThrow(lambdaConventionEl.getAttributeValue(LOCANT_ATR)).setLambdaConventionValency(Integer.parseInt(lambdaConventionEl.getAttributeValue(LAMBDA_ATR))); } else{ if (frag.getAtomList().size()!=1){ throw new StructureBuildingException("Ambiguous use of lambda convention. Fragment has more than 1 atom but no locant was specified for the lambda"); } frag.getFirstAtom().setLambdaConventionValency(Integer.parseInt(lambdaConventionEl.getAttributeValue(LAMBDA_ATR))); } lambdaConventionEl.detach(); } } /** * Uses the number of outAtoms that are present to assign the number of outAtoms on substituents that can have a variable number of outAtoms * Hence at this point it can be determined if a multi radical susbtituent is present in the name * This would be expected in multiplicative nomenclature and is noted in the state so that the StructureBuilder knows to resolve the * section of the name from that point onwards in a left to right manner rather than right to left * @param state * @param subOrRoot: The sub/root to look in * @throws ComponentGenerationException * @throws StructureBuildingException */ private void handleMultiRadicals(BuildState state, Element subOrRoot) throws ComponentGenerationException, StructureBuildingException{ Element group =subOrRoot.getFirstChildElement(GROUP_EL); String groupValue =group.getValue(); Fragment thisFrag = state.xmlFragmentMap.get(group); if (groupValue.equals("methylene") || groupValue.equals("oxy")|| matchChalcogenReplacement.matcher(groupValue).matches()){//resolves for example trimethylene to propan-1,3-diyl or dithio to disulfan-1,2-diyl. Locants may not be specified before the multiplier Element beforeGroup =(Element) XOMTools.getPreviousSibling(group); if (beforeGroup!=null && beforeGroup.getLocalName().equals(MULTIPLIER_ATR) && beforeGroup.getAttributeValue(TYPE_ATR).equals(BASIC_TYPE_VAL) && XOMTools.getPreviousSibling(beforeGroup)==null){ int multiplierVal = Integer.parseInt(beforeGroup.getAttributeValue(VALUE_ATR)); if (!unsuitableForFormingChainMultiradical(state, group, beforeGroup)){ if (groupValue.equals("methylene")){ group.getAttribute(VALUE_ATR).setValue(StringTools.multiplyString("C", multiplierVal)); } else if (groupValue.equals("oxy")){ group.getAttribute(VALUE_ATR).setValue(StringTools.multiplyString("O", multiplierVal)); } else if (groupValue.equals("thio")){ group.getAttribute(VALUE_ATR).setValue(StringTools.multiplyString("S", multiplierVal)); } else if (groupValue.equals("seleno")){ group.getAttribute(VALUE_ATR).setValue(StringTools.multiplyString("[SeH?]", multiplierVal)); } else if (groupValue.equals("telluro")){ group.getAttribute(VALUE_ATR).setValue(StringTools.multiplyString("[TeH?]", multiplierVal)); } else{ throw new ComponentGenerationException("unexpected group value"); } group.getAttribute(OUTIDS_ATR).setValue("1,"+Integer.parseInt(beforeGroup.getAttributeValue(VALUE_ATR))); XOMTools.setTextChild(group, beforeGroup.getValue() + groupValue); beforeGroup.detach(); if (group.getAttribute(LABELS_ATR)!=null){//use numeric numbering group.getAttribute(LABELS_ATR).setValue(NUMERIC_LABELS_VAL); } else{ group.addAttribute(new Attribute(LABELS_ATR, NUMERIC_LABELS_VAL)); } state.fragManager.removeFragment(thisFrag); thisFrag =resolveGroup(state, group); state.xmlFragmentMap.put(group, thisFrag); group.removeAttribute(group.getAttribute(USABLEASJOINER_ATR)); } } } if (group.getAttribute(OUTIDS_ATR)!=null){//adds outIDs at the specified atoms String[] radicalPositions = matchComma.split(group.getAttributeValue(OUTIDS_ATR)); int firstIdInFrag =thisFrag.getIdOfFirstAtom(); for (String radicalID : radicalPositions) { thisFrag.addOutAtom(firstIdInFrag + Integer.parseInt(radicalID) - 1, 1, true); } } int outAtomCount = thisFrag.getOutAtoms().size(); if (outAtomCount >=2){ if (groupValue.equals("amine")){//amine is a special case as it shouldn't technically be allowed but is allowed due to it's common usage in EDTA Element previousGroup =(Element) OpsinTools.getPreviousGroup(group); Element nextGroup =(Element) OpsinTools.getNextGroup(group); if (previousGroup==null || state.xmlFragmentMap.get(previousGroup).getOutAtoms().size() < 2 || nextGroup==null){//must be preceded by a multi radical throw new ComponentGenerationException("Invalid use of amine as a substituent!"); } } if (state.currentWordRule == WordRule.polymer){ if (outAtomCount >=3){//In poly mode nothing may have more than 2 outAtoms e.g. nitrilo is -N= or =N- int valency =0; for (int i = 2; i < outAtomCount; i++) { OutAtom nextOutAtom = thisFrag.getOutAtom(i); valency += nextOutAtom.getValency(); thisFrag.removeOutAtom(nextOutAtom); } thisFrag.getOutAtom(1).setValency(thisFrag.getOutAtom(1).getValency() + valency); } } } if (outAtomCount ==2 && EPOXYLIKE_SUBTYPE_VAL.equals(group.getAttributeValue(SUBTYPE_ATR))){ Element possibleLocant =(Element) XOMTools.getPreviousSibling(group); if (possibleLocant !=null){ String[] locantValues = matchComma.split(possibleLocant.getValue()); if (locantValues.length==2){ thisFrag.getOutAtom(0).setLocant(locantValues[0]); thisFrag.getOutAtom(1).setLocant(locantValues[1]); possibleLocant.detach(); subOrRoot.addAttribute(new Attribute(LOCANT_ATR, locantValues[0])); } } } int totalOutAtoms = outAtomCount + calculateOutAtomsToBeAddedFromInlineSuffixes(state, group, subOrRoot.getChildElements(SUFFIX_EL)); if (totalOutAtoms >= 2){ group.addAttribute(new Attribute (ISAMULTIRADICAL_ATR, Integer.toString(totalOutAtoms))); } } /** * Checks for cases where multiplier(methylene) or multiplier(thio) and the like should not be interpreted as one fragment * Something like nitrilotrithiotriacetic acid or oxetane-3,3-diyldimethylene * @param state * @param group * @param multiplierBeforeGroup * @return */ private boolean unsuitableForFormingChainMultiradical(BuildState state, Element group, Element multiplierBeforeGroup) { Element previousGroup = (Element) OpsinTools.getPreviousGroup(group); if (previousGroup!=null){ if (previousGroup.getAttribute(ISAMULTIRADICAL_ATR)!=null){ if (previousGroup.getAttributeValue(ACCEPTSADDITIVEBONDS_ATR)!=null && XOMTools.getPreviousSibling(previousGroup.getParent())!=null){ return false; } //the initial multiplier is proceded by another multiplier e.g. bis(dithio) if (((Element)XOMTools.getPrevious(multiplierBeforeGroup)).getLocalName().equals(MULTIPLIER_EL)){ return false; } if (previousGroup.getAttributeValue(ISAMULTIRADICAL_ATR).equals(multiplierBeforeGroup.getAttributeValue(VALUE_ATR))){ return true;//probably multiplicative } else{ return false; } } else if (XOMTools.getPreviousSibling(previousGroup, MULTIPLIER_EL)==null){ //This is a 99% solution to the detection of cases such as ethylidenedioxy == ethan-1,1-diyldioxy Fragment previousGroupFrag =state.xmlFragmentMap.get(previousGroup); int outAtomValency =0; if (previousGroupFrag.getOutAtoms().size()==1){ outAtomValency = previousGroupFrag.getOutAtom(0).getValency(); } else{ Element suffix = (Element) XOMTools.getNextSibling(previousGroup, SUFFIX_EL); if (suffix!=null && suffix.getAttributeValue(VALUE_ATR).equals("ylidene")){ outAtomValency =2; } if (suffix!=null && suffix.getAttributeValue(VALUE_ATR).equals("ylidyne")){ outAtomValency =3; } } if (outAtomValency==Integer.parseInt(multiplierBeforeGroup.getAttributeValue(VALUE_ATR))){ return true; } } } return false; } /** * Calculates number of OutAtoms that the resolveSuffixes method will add. * @param state * @param group * @param suffixes * @return numberOfOutAtoms that will be added by resolveSuffixes * @throws ComponentGenerationException */ private int calculateOutAtomsToBeAddedFromInlineSuffixes(BuildState state, Element group, Elements suffixes) throws ComponentGenerationException { int outAtomsThatWillBeAdded = 0; Fragment frag = state.xmlFragmentMap.get(group); String groupType = frag.getType(); String subgroupType = frag.getSubType(); String suffixTypeToUse =null; if (suffixApplicability.containsKey(groupType)){ suffixTypeToUse =groupType; } else{ suffixTypeToUse = STANDARDGROUP_TYPE_VAL; } List<Fragment> suffixList =state.xmlSuffixMap.get(group); for (Fragment suffix : suffixList) { outAtomsThatWillBeAdded += suffix.getOutAtoms().size(); } for(int i=0;i<suffixes.size();i++) { Element suffix = suffixes.get(i); String suffixValue = suffix.getAttributeValue(VALUE_ATR); Elements suffixRuleTags =getSuffixRuleTags(suffixTypeToUse, suffixValue, subgroupType); for(int j=0;j<suffixRuleTags.size();j++) { Element suffixRuleTag = suffixRuleTags.get(j); String suffixRuleTagName =suffixRuleTag.getLocalName(); if(suffixRuleTagName.equals(SUFFIXRULES_SETOUTATOM_EL)) { outAtomsThatWillBeAdded +=1; } } } return outAtomsThatWillBeAdded; } /** * Corrects something like L-alanyl-L-glutaminyl-L-arginyl-O-phosphono-L-seryl-L-alanyl-L-proline to: * ((((L-alanyl-L-glutaminyl)-L-arginyl)-O-phosphono-L-seryl)-L-alanyl)-L-proline * i.e. substituents go onto the last mentioned amino acid; amino acids chain together to form peptides * @param groups * @param brackets */ private void addImplicitBracketsToAminoAcids(List<Element> groups, List<Element> brackets) { for (int i = groups.size() -1; i >=0; i Element group = groups.get(i); if (group.getAttributeValue(TYPE_ATR).equals(AMINOACID_TYPE_VAL)){ Element subOrRoot = (Element) group.getParent(); //now find the brackets/substituents before this element Element previous = (Element) XOMTools.getPreviousSibling(subOrRoot); List<Element> previousElements = new ArrayList<Element>(); while( previous !=null){ if (!previous.getLocalName().equals(SUBSTITUENT_EL) && !previous.getLocalName().equals(BRACKET_EL)){ break; } previousElements.add(previous); previous = (Element) XOMTools.getPreviousSibling(previous); } if (previousElements.size()>0){//an implicit bracket is needed Collections.reverse(previousElements); Element bracket = new Element(BRACKET_EL); bracket.addAttribute(new Attribute(TYPE_ATR, IMPLICIT_TYPE_VAL)); Element parent = (Element) subOrRoot.getParent(); int indexToInsertAt = parent.indexOf(previousElements.get(0)); for (Element element : previousElements) { element.detach(); bracket.appendChild(element); } subOrRoot.detach(); bracket.appendChild(subOrRoot); parent.insertChild(bracket, indexToInsertAt); brackets.add(bracket); } } } } /**Looks for places where brackets should have been, and does the same * as findAndStructureBrackets. E.g. dimethylaminobenzene -> (dimethylamino)benzene. * The bracketting in the above case occurs when the substituent that is being procesed is the amino group * @param state * @param brackets * @param substituents: An arraylist of substituent elements * @return Whether the method did something, and so needs to be called again. * @throws StructureBuildingException * @throws ComponentGenerationException */ private void findAndStructureImplictBrackets(BuildState state, List<Element> substituents, List<Element> brackets) throws ComponentGenerationException, StructureBuildingException { for (Element substituent : substituents) {//will attempt to bracket this substituent with the substituent before it String firstElInSubName =((Element)substituent.getChild(0)).getLocalName(); if (firstElInSubName.equals(LOCANT_EL) ||firstElInSubName.equals(MULTIPLIER_EL)){ continue; } Element substituentGroup = substituent.getFirstChildElement(GROUP_EL); String theSubstituentSubType = substituentGroup.getAttributeValue(SUBTYPE_ATR); String theSubstituentType = substituentGroup.getAttributeValue(TYPE_ATR); //Only some substituents are valid joiners (e.g. no rings are valid joiners). Need to be atleast bivalent. if (substituentGroup.getAttribute(USABLEASJOINER_ATR)==null){ continue; } Fragment frag =state.xmlFragmentMap.get(substituentGroup); //there must be an element after the substituent for the implicit bracket to be required Element elementAftersubstituent =(Element)XOMTools.getNextSibling(substituent); if (elementAftersubstituent ==null || !elementAftersubstituent.getLocalName().equals(SUBSTITUENT_EL) && !elementAftersubstituent.getLocalName().equals(BRACKET_EL) && !elementAftersubstituent.getLocalName().equals(ROOT_EL)){ continue; } //checks that the element before is a substituent or a bracket which will obviously include substituent/s //this makes sure there's more than just a substituent in the bracket Element elementBeforeSubstituent =(Element)XOMTools.getPreviousSibling(substituent); if (elementBeforeSubstituent ==null|| !elementBeforeSubstituent.getLocalName().equals(SUBSTITUENT_EL) && !elementBeforeSubstituent.getLocalName().equals(BRACKET_EL)){ continue; } //Not preceded and succeded by a bracket e.g. Not (benzyl)methyl(phenyl)amine c.f. P-16.4.1.3 (draft 2004) if (elementBeforeSubstituent.getLocalName().equals(BRACKET_EL) && !IMPLICIT_TYPE_VAL.equals(elementBeforeSubstituent.getAttributeValue(TYPE_ATR)) && elementAftersubstituent.getLocalName().equals(BRACKET_EL)){ Element firstChildElementOfElementAfterSubstituent = (Element) elementAftersubstituent.getChild(0); if ((firstChildElementOfElementAfterSubstituent.getLocalName().equals(SUBSTITUENT_EL) || firstChildElementOfElementAfterSubstituent.getLocalName().equals(BRACKET_EL)) && !((Element)XOMTools.getPrevious(firstChildElementOfElementAfterSubstituent)).getLocalName().equals(HYPHEN_EL)){ continue; } } //look for hyphen between substituents, this seems to indicate implicit bracketing was not desired e.g. dimethylaminomethane vs dimethyl-aminomethane Element elementDirectlyBeforeSubstituent = (Element) XOMTools.getPrevious(substituent.getChild(0));//can't return null as we know elementBeforeSubstituent is not null if (elementDirectlyBeforeSubstituent.getLocalName().equals(HYPHEN_EL)){ continue; } //prevents alkyl chains being bracketed together e.g. ethylmethylamine //...unless it's something like 2-methylethyl where the first appears to be locanted onto the second List<Element> groupElements = XOMTools.getDescendantElementsWithTagName(elementBeforeSubstituent, GROUP_EL);//one for a substituent, possibly more for a bracket Element lastGroupOfElementBeforeSub =groupElements.get(groupElements.size()-1); if (lastGroupOfElementBeforeSub==null){throw new ComponentGenerationException("No group where group was expected");} if (theSubstituentType.equals(CHAIN_TYPE_VAL) && theSubstituentSubType.equals(ALKANESTEM_SUBTYPE_VAL) && lastGroupOfElementBeforeSub.getAttributeValue(TYPE_ATR).equals(CHAIN_TYPE_VAL) && lastGroupOfElementBeforeSub.getAttributeValue(SUBTYPE_ATR).equals(ALKANESTEM_SUBTYPE_VAL)){ boolean placeInImplicitBracket =false; Element suffixAfterGroup=(Element)XOMTools.getNextSibling(lastGroupOfElementBeforeSub, SUFFIX_EL); //if the alkane ends in oxy, sulfinyl, sulfonyl etc. it's not a pure alkane (other suffixes don't need to be considered as they would produce silly structures) if (suffixAfterGroup !=null && matchInlineSuffixesThatAreAlsoGroups.matcher(suffixAfterGroup.getValue()).matches()){ placeInImplicitBracket =true; } //look for locants and check whether they appear to be referring to the other chain if (!placeInImplicitBracket){ Elements childrenOfElementBeforeSubstituent =elementBeforeSubstituent.getChildElements(); Boolean foundLocantNotReferringToChain =null; for (int i = 0; i < childrenOfElementBeforeSubstituent.size(); i++) { String currentElementName = childrenOfElementBeforeSubstituent.get(i).getLocalName(); if (currentElementName.equals(LOCANT_EL)){ String locantText =childrenOfElementBeforeSubstituent.get(i).getValue(); if(!frag.hasLocant(locantText)){ foundLocantNotReferringToChain=true; break; } else{ foundLocantNotReferringToChain=false; } } else if (currentElementName.equals(STEREOCHEMISTRY_EL)){ } else{ break; } } if (foundLocantNotReferringToChain !=null && !foundLocantNotReferringToChain){//a locant was found and it appeared to refer to the other chain placeInImplicitBracket=true; } } if (!placeInImplicitBracket){ continue; } } //prevent bracketing to multi radicals unless through substitution they are likely to cease being multiradicals if (lastGroupOfElementBeforeSub.getAttribute(ISAMULTIRADICAL_ATR)!=null && lastGroupOfElementBeforeSub.getAttribute(ACCEPTSADDITIVEBONDS_ATR)==null && lastGroupOfElementBeforeSub.getAttribute(IMINOLIKE_ATR)==null){ continue; } if (substituentGroup.getAttribute(ISAMULTIRADICAL_ATR)!=null && substituentGroup.getAttribute(ACCEPTSADDITIVEBONDS_ATR)==null && substituentGroup.getAttribute(IMINOLIKE_ATR)==null){ continue; } if (lastGroupOfElementBeforeSub.getAttribute(IMINOLIKE_ATR)!=null && substituentGroup.getAttribute(IMINOLIKE_ATR)!=null){ continue;//possibly a multiplicative additive operation } //prevent bracketting perhalogeno terms if (PERHALOGENO_SUBTYPE_VAL.equals(lastGroupOfElementBeforeSub.getAttributeValue(SUBTYPE_ATR))){ continue; } /* * locant may need to be moved. This occurs when the group in elementBeforeSubstituent is not supposed to be locanted onto * theSubstituentGroup * e.g. 2-aminomethyl-1-chlorobenzene where the 2 refers to the benzene NOT the methyl */ List<Element> locantRelatedElements = new ArrayList<Element>();//sometimes moved String[] locantValues = null; ArrayList<Element> stereoChemistryElements =new ArrayList<Element>();//always moved if bracketing occurs Elements childrenOfElementBeforeSubstituent = elementBeforeSubstituent.getChildElements(); for (int i = 0; i < childrenOfElementBeforeSubstituent.size(); i++) { String currentElementName = childrenOfElementBeforeSubstituent.get(i).getLocalName(); if (currentElementName.equals(STEREOCHEMISTRY_EL)){ stereoChemistryElements.add(childrenOfElementBeforeSubstituent.get(i)); } else if (currentElementName.equals(LOCANT_EL)){ if (locantValues !=null){ break; } locantRelatedElements.add(childrenOfElementBeforeSubstituent.get(i)); locantValues = matchComma.split(childrenOfElementBeforeSubstituent.get(i).getValue()); } else{ break; } } //either all locants will be moved, or none Boolean moveLocants = false; if (locantValues!=null){ Element elAfterLocant = (Element) XOMTools.getNextSibling(locantRelatedElements.get(0)); for (String locantText : locantValues) { if (elAfterLocant.getAttribute(FRONTLOCANTSEXPECTED_ATR)!=null && StringTools.arrayToList(matchComma.split(elAfterLocant.getAttributeValue(FRONTLOCANTSEXPECTED_ATR))).contains(locantText)){ continue; } //Check the right fragment in the bracket: //if it only has 1 then assume locanted substitution onto it not intended. Or if doesn't have the required locant if (frag.getAtomList().size()==1 || !frag.hasLocant(locantText) || matchElementSymbolOrAminoAcidLocant.matcher(locantText).find()){ if (checkLocantPresentOnPotentialRoot(state, substituent, locantText)){ moveLocants =true;//locant location is present elsewhere } else if (findElementsMissingIndirectLocants(elementBeforeSubstituent, locantRelatedElements.get(0)).size()==0 || !state.xmlFragmentMap.get(lastGroupOfElementBeforeSub).hasLocant(locantText)){ if( frag.getAtomList().size()==1 && frag.hasLocant(locantText)){ //1 locant was intended to locant onto fragment with 1 atom } else{ moveLocants =true;//the fragment adjacent to the locant doesn't have this locant or doesn't need any indirect locants. Assume it will appear elsewhere later } } } } } if (moveLocants && locantValues !=null && locantValues.length >1){ Element shouldBeAMultiplierNode = (Element)XOMTools.getNextSibling(locantRelatedElements.get(0)); if (shouldBeAMultiplierNode !=null && shouldBeAMultiplierNode.getLocalName().equals(MULTIPLIER_EL)){ Element shouldBeAGroupOrSubOrBracket = (Element)XOMTools.getNextSibling(shouldBeAMultiplierNode); if (shouldBeAGroupOrSubOrBracket !=null){ if ((shouldBeAGroupOrSubOrBracket.getLocalName().equals(GROUP_EL) && shouldBeAMultiplierNode.getAttributeValue(TYPE_ATR).equals(GROUP_TYPE_VAL))//e.g. 2,5-bisaminothiobenzene --> 2,5-bis(aminothio)benzene || (matchInlineSuffixesThatAreAlsoGroups.matcher(substituentGroup.getValue()).matches())){//e.g. 4,4'-dimethoxycarbonyl-2,2'-bioxazole --> 4,4'-di(methoxycarbonyl)-2,2'-bioxazole locantRelatedElements.add(shouldBeAMultiplierNode);//e.g. 1,5-bis-(4-methylphenyl)sulfonyl --> 1,5-bis-((4-methylphenyl)sulfonyl) } else if (ORTHOMETAPARA_TYPE_VAL.equals(locantRelatedElements.get(0).getAttributeValue(TYPE_ATR))){//e.g. p-dimethylamino[ring] XOMTools.setTextChild(locantRelatedElements.get(0), locantValues[1]); } else{//don't bracket other complex multiplied substituents (name hasn't given enough hints if indeed bracketing was expected) continue; } } else{ moveLocants =false; } } else{ moveLocants =false; } } Element bracket = new Element(BRACKET_EL); bracket.addAttribute(new Attribute(TYPE_ATR, IMPLICIT_TYPE_VAL)); for (Element stereoChemistryElement : stereoChemistryElements) { stereoChemistryElement.detach(); bracket.appendChild(stereoChemistryElement); } if (moveLocants){ for (Element locantElement : locantRelatedElements) { locantElement.detach(); bracket.appendChild(locantElement); } } /* * Case when a multiplier should be moved * e.g. tripropan-2-yloxyphosphane -->tri(propan-2-yloxy)phosphane or trispropan-2-ylaminophosphane --> tris(propan-2-ylamino)phosphane */ if (locantRelatedElements.size()==0){ Element possibleMultiplier =childrenOfElementBeforeSubstituent.get(0); if (possibleMultiplier.getLocalName().equals(MULTIPLIER_EL) && ( matchInlineSuffixesThatAreAlsoGroups.matcher(substituentGroup.getValue()).matches() || possibleMultiplier.getAttributeValue(TYPE_ATR).equals(GROUP_TYPE_VAL))){ Element desiredGroup = XOMTools.getNextSiblingIgnoringCertainElements(possibleMultiplier, new String[]{MULTIPLIER_EL}); if (desiredGroup !=null && desiredGroup.getLocalName().equals(GROUP_EL)){ childrenOfElementBeforeSubstituent.get(0).detach(); bracket.appendChild(childrenOfElementBeforeSubstituent.get(0)); } } } Element parent = (Element)substituent.getParent(); int startIndex=parent.indexOf(elementBeforeSubstituent); int endIndex=parent.indexOf(substituent); for(int i = 0 ; i <= (endIndex-startIndex);i++) { Node n = parent.getChild(startIndex); n.detach(); bracket.appendChild(n); } parent.insertChild(bracket, startIndex); brackets.add(bracket); } } /** * Attempts to match locants to non adjacent suffixes/unsatuators * e.g. 2-propanol, 3-furyl, 2'-Butyronaphthone * @param state * @param subOrRoot The substituent/root to look for locants in. * @throws StructureBuildingException */ private void matchLocantsToIndirectFeatures(BuildState state, Element subOrRoot) throws StructureBuildingException { /* Root fragments (or the root in a bracket) can have prefix-locants * that work on suffixes - (2-furyl), 2-propanol, (2-propylmethyl), (2-propyloxy), 2'-Butyronaphthone. */ List<Element> locantEls = findLocantsThatCouldBeIndirectLocants(subOrRoot); if (locantEls.size()>0){ Element group =subOrRoot.getFirstChildElement(GROUP_EL); Element lastLocant = locantEls.get(locantEls.size()-1);//the locant that may apply to an unsaturator/suffix String[] locantValues = matchComma.split(lastLocant.getValue()); if (locantValues.length==1 && group.getAttribute(FRONTLOCANTSEXPECTED_ATR)!=null){//some trivial retained names like 2-furyl expect locants to be in front of them. For these the indirect intepretation will always be used rather than checking whether 2-(furyl) even makes sense String[] allowedLocants = matchComma.split(group.getAttributeValue(FRONTLOCANTSEXPECTED_ATR)); for (String allowedLocant : allowedLocants) { if (locantValues[0].equals(allowedLocant)){ Element expectedSuffix =(Element) XOMTools.getNextSibling(group); if (expectedSuffix!=null && expectedSuffix.getLocalName().equals(SUFFIX_EL) && expectedSuffix.getAttribute(LOCANT_ATR)==null){ expectedSuffix.addAttribute(new Attribute(LOCANT_ATR, locantValues[0])); lastLocant.detach(); return; } break; } } } boolean allowIndirectLocants =true; if(state.currentWordRule == WordRule.multiEster && !ADDEDHYDROGENLOCANT_TYPE_VAL.equals(lastLocant.getAttributeValue(TYPE_ATR))){//special case e.g. 1-benzyl 4-butyl terephthalate (locants do not apply to yls) Element parentEl=(Element) subOrRoot.getParent(); if (parentEl.getLocalName().equals(WORD_EL) && parentEl.getAttributeValue(TYPE_ATR).equals(SUBSTITUENT_EL) && parentEl.getChildCount()==1 && locantValues.length==1 && !ORTHOMETAPARA_TYPE_VAL.equals(lastLocant.getAttributeValue(TYPE_ATR))){ allowIndirectLocants =false; } } Fragment fragmentAfterLocant =state.xmlFragmentMap.get(group); if (fragmentAfterLocant.getAtomList().size()<=1){ allowIndirectLocants =false;//e.g. prevent 1-methyl as meth-1-yl is extremely unlikely to be the intended result } if (allowIndirectLocants){ /* The first locant is most likely a locant indicating where this subsituent should be attached. * If the locant cannot be found on a potential root this cannot be the case though (assuming the name is valid of course) */ if (!ADDEDHYDROGENLOCANT_TYPE_VAL.equals(lastLocant.getAttributeValue(TYPE_ATR)) && locantEls.size() ==1 && group.getAttribute(ISAMULTIRADICAL_ATR)==null && locantValues.length == 1 && checkLocantPresentOnPotentialRoot(state, subOrRoot, locantValues[0]) && XOMTools.getPreviousSibling(lastLocant, LOCANT_EL)==null){ return; } boolean assignableToIndirectFeatures =true; List<Element> locantAble =findElementsMissingIndirectLocants(subOrRoot, lastLocant); if (locantAble.size() < locantValues.length){ assignableToIndirectFeatures =false; } else{ for (String locantValue : locantValues) { if (!fragmentAfterLocant.hasLocant(locantValue)){//locant is not available on the group adjacent to the locant! assignableToIndirectFeatures =false; } } } if (!assignableToIndirectFeatures){//usually indicates the name will fail unless the suffix has the locant or heteroatom replacement will create the locant if (locantValues.length==1){ List<Fragment> suffixes =state.xmlSuffixMap.get(group); //I do not want to assign element locants as in locants on the suffix as I currently know of no examples where this actually occurs if (matchElementSymbolOrAminoAcidLocant.matcher(locantValues[0]).matches()){ return; } for (Fragment suffix : suffixes) { if (suffix.hasLocant(locantValues[0])){//e.g. 2'-Butyronaphthone Atom dummyRAtom =suffix.getFirstAtom(); List<Atom> neighbours =dummyRAtom.getAtomNeighbours(); Bond b =null; atomLoop: for (Atom atom : neighbours) { List<String> neighbourLocants = atom.getLocants(); for (String neighbourLocant : neighbourLocants) { if (matchNumericLocant.matcher(neighbourLocant).matches()){ b = dummyRAtom.getBondToAtomOrThrow(atom); break atomLoop; } } } if (b!=null){ state.fragManager.removeBond(b);//the current bond between the dummy R and the suffix state.fragManager.createBond(dummyRAtom, suffix.getAtomByLocantOrThrow(locantValues[0]), b.getOrder()); lastLocant.detach(); } } } } } else{ for (int i = 0; i < locantValues.length; i++) { String locantValue = locantValues[i]; locantAble.get(i).addAttribute(new Attribute(LOCANT_ATR, locantValue)); } lastLocant.detach(); } } } } /** * Finds locants that are before a group element and not immediately followed by a multiplier * @param subOrRoot * @return */ private List<Element> findLocantsThatCouldBeIndirectLocants(Element subOrRoot) { Elements children = subOrRoot.getChildElements(); List<Element> locantEls = new ArrayList<Element>(); for (int i = 0; i < children.size(); i++) { Element el = children.get(i); if (el.getLocalName().equals(LOCANT_EL)){ Element afterLocant =(Element) XOMTools.getNextSibling(el); if (afterLocant!=null && afterLocant.getLocalName().equals(MULTIPLIER_EL)){//locant should not be followed by a multiplier. c.f. 1,2,3-tributyl 2-acetyloxypropane-1,2,3-tricarboxylate continue; } locantEls.add(el); } else if (el.getLocalName().equals(GROUP_EL)){ break; } } return locantEls; } /** * Find elements that can have indirect locants but don't currently * This requirement excludes hydro and heteroatoms as it is assumed that locants for these are always adjacent (or handled by the special HW code in the case of heteroatoms) * @param subOrRoot The subOrRoot of interest * @param locantEl the locant, only elements after it will be considered * @return An arrayList of locantable elements */ private List<Element> findElementsMissingIndirectLocants(Element subOrRoot,Element locantEl) { List<Element> locantAble = new ArrayList<Element>(); Elements childrenOfSubOrBracketOrRoot=subOrRoot.getChildElements(); for (int j = 0; j < childrenOfSubOrBracketOrRoot.size(); j++) { Element el =childrenOfSubOrBracketOrRoot.get(j); String name =el.getLocalName(); if (name.equals(SUFFIX_EL) || name.equals(UNSATURATOR_EL) || name.equals(CONJUNCTIVESUFFIXGROUP_EL)){ if (el.getAttribute(LOCANT_ATR) ==null && el.getAttribute(LOCANTID_ATR) ==null && el.getAttribute(MULTIPLIED_ATR)==null){// shouldn't already have a locant or be multiplied (should of already had locants assignd to it if that were the case) if (subOrRoot.indexOf(el)>subOrRoot.indexOf(locantEl)){ if (name.equals(SUFFIX_EL)){//check a few special cases that must not be locanted Element group = (Element) XOMTools.getPreviousSibling(el, GROUP_EL); String type = group.getAttributeValue(TYPE_ATR); if (type.equals(ACIDSTEM_TYPE_VAL)|| type.equals(NONCARBOXYLICACID_TYPE_VAL) || type.equals(CHALCOGENACIDSTEM_TYPE_VAL)){ continue; } } locantAble.add(el); } } } } return locantAble; } /** * Put di-carbon modifying suffixes e.g. oic acids, aldehydes on opposite ends of chain * @param state * @param subOrRoot * @throws StructureBuildingException */ private void assignImplicitLocantsToDiTerminalSuffixes(BuildState state, Element subOrRoot) throws StructureBuildingException { Element terminalSuffix1 = subOrRoot.getFirstChildElement(SUFFIX_EL); if (terminalSuffix1!=null){ if (isATerminalSuffix(terminalSuffix1) && XOMTools.getNextSibling(terminalSuffix1) != null){ Element terminalSuffix2 =(Element)XOMTools.getNextSibling(terminalSuffix1); if (isATerminalSuffix(terminalSuffix2)){ Element hopefullyAChain = (Element) XOMTools.getPreviousSibling((Element)terminalSuffix1, GROUP_EL); if (hopefullyAChain != null && hopefullyAChain.getAttributeValue(TYPE_ATR).equals(CHAIN_TYPE_VAL)){ int chainLength = state.xmlFragmentMap.get(hopefullyAChain).getChainLength(); if (chainLength >=2){ terminalSuffix1.addAttribute(new Attribute(LOCANT_ATR, "1")); terminalSuffix2.addAttribute(new Attribute(LOCANT_ATR, Integer.toString(chainLength))); } } } } } } /** * Checks whether a suffix element is: * a suffix, an inline suffix OR terminal root suffix, has no current locant * @param suffix * @return */ private boolean isATerminalSuffix(Element suffix){ return suffix.getLocalName().equals(SUFFIX_EL) && suffix.getAttribute(LOCANT_ATR) == null && (suffix.getAttributeValue(TYPE_ATR).equals(INLINE_TYPE_VAL) || TERMINAL_SUBTYPE_VAL.equals(suffix.getAttributeValue(SUBTYPE_ATR))); } private void processConjunctiveNomenclature(BuildState state, Element subOrRoot) throws ComponentGenerationException, StructureBuildingException { List<Element> conjunctiveGroups = XOMTools.getChildElementsWithTagName(subOrRoot, CONJUNCTIVESUFFIXGROUP_EL); if (conjunctiveGroups.size()>0){ Element ringGroup = subOrRoot.getFirstChildElement(GROUP_EL); Fragment ringFrag = state.xmlFragmentMap.get(ringGroup); if (ringFrag.getOutAtoms().size()!=0 ){ throw new ComponentGenerationException("OPSIN Bug: Ring fragment should have no radicals"); } List<Fragment> conjunctiveFragments = new ArrayList<Fragment>(); for (Element group : conjunctiveGroups) { Fragment frag = state.xmlFragmentMap.get(group); conjunctiveFragments.add(frag); } for (int i = 0; i < conjunctiveFragments.size(); i++) { Fragment conjunctiveFragment = conjunctiveFragments.get(i); if (conjunctiveGroups.get(i).getAttribute(LOCANT_ATR)!=null){ state.fragManager.createBond(lastNonSuffixCarbonWithSufficientValency(conjunctiveFragment), ringFrag.getAtomByLocantOrThrow(conjunctiveGroups.get(i).getAttributeValue(LOCANT_ATR)) , 1); } else{ state.fragManager.createBond(lastNonSuffixCarbonWithSufficientValency(conjunctiveFragment), ringFrag.getAtomOrNextSuitableAtomOrThrow(ringFrag.getFirstAtom(), 1, true) , 1); } state.fragManager.incorporateFragment(conjunctiveFragment, ringFrag); } } } private Atom lastNonSuffixCarbonWithSufficientValency(Fragment conjunctiveFragment) throws ComponentGenerationException { List<Atom> atomList = conjunctiveFragment.getAtomList(); for (int i = atomList.size()-1; i >=0; i Atom a = atomList.get(i); if (a.getType().equals(SUFFIX_TYPE_VAL)){ continue; } if (!a.getElement().equals("C")){ continue; } if (ValencyChecker.checkValencyAvailableForBond(a, 1)){ return a; } } throw new ComponentGenerationException("OPSIN Bug: Unable to find non suffix carbon with sufficient valency"); } /**Process the effects of suffixes upon a fragment. * Unlocanted non-terminal suffixes are not attached yet. All other suffix effects are performed * @param state * @param group The group element for the fragment to which the suffixes will be added * @param suffixes The suffix elements for a fragment. * @throws StructureBuildingException If the suffixes can't be resolved properly. * @throws ComponentGenerationException */ private void resolveSuffixes(BuildState state, Element group, List<Element> suffixes) throws StructureBuildingException, ComponentGenerationException { Fragment frag = state.xmlFragmentMap.get(group); int firstAtomID = frag.getIdOfFirstAtom();//typically equivalent to locant 1 List<Atom> atomList =frag.getAtomList();//this instance of atomList will not change even once suffixes are merged into the fragment int defaultAtom =0;//indice in atomList String groupType = frag.getType(); String subgroupType = frag.getSubType(); String suffixTypeToUse =null; if (suffixApplicability.containsKey(groupType)){ suffixTypeToUse =groupType; } else{ suffixTypeToUse =STANDARDGROUP_TYPE_VAL; } List<Fragment> suffixList = state.xmlSuffixMap.get(group); for (Element suffix : suffixes) { String suffixValue = suffix.getAttributeValue(VALUE_ATR); String locant = suffix.getAttributeValue(LOCANT_ATR); int idOnParentFragToUse = 0; if (locant != null) { idOnParentFragToUse = frag.getIDFromLocantOrThrow(locant); } if (idOnParentFragToUse == 0 && suffix.getAttribute(LOCANTID_ATR) != null) { idOnParentFragToUse = Integer.parseInt(suffix.getAttributeValue(LOCANTID_ATR)); } if (idOnParentFragToUse == 0 && suffix.getAttribute(DEFAULTLOCANTID_ATR) != null) { idOnParentFragToUse = Integer.parseInt(suffix.getAttributeValue(DEFAULTLOCANTID_ATR)); } if (idOnParentFragToUse == 0 && (suffixTypeToUse.equals(ACIDSTEM_TYPE_VAL) || suffixTypeToUse.equals(NONCARBOXYLICACID_TYPE_VAL) || suffixTypeToUse.equals(CHALCOGENACIDSTEM_TYPE_VAL))) {//means that e.g. sulfonyl has an explicit outAtom idOnParentFragToUse = firstAtomID; } Fragment suffixFrag = null; Elements suffixRuleTags = getSuffixRuleTags(suffixTypeToUse, suffixValue, subgroupType); for (int j = 0; j < suffixRuleTags.size(); j++) { Element suffixRuleTag = suffixRuleTags.get(j); String suffixRuleTagName = suffixRuleTag.getLocalName(); if (defaultAtom >= atomList.size()) { defaultAtom = 0; } if (suffixRuleTagName.equals(SUFFIXRULES_ADDGROUP_EL)) { if (suffixFrag == null) { if (suffixList.size() <= 0) { throw new ComponentGenerationException("OPSIN Bug: Suffixlist should not be empty"); } suffixFrag = suffixList.remove(0);//take the first suffix out of the list, it should of been added in the same order that it is now being read. if (suffixFrag.getFirstAtom().getBonds().size() <= 0) { throw new ComponentGenerationException("OPSIN Bug: Dummy atom in suffix should have at least one bond to it"); } int bondOrderRequired = suffixFrag.getFirstAtom().getIncomingValency(); Atom parentfragAtom; if (idOnParentFragToUse == 0) { if (suffixRuleTag.getAttribute(SUFFIXRULES_KETONELOCANT_ATR) != null && !atomList.get(defaultAtom).getAtomIsInACycle()) { if (defaultAtom == 0) defaultAtom = FragmentTools.findKetoneAtomIndice(frag, defaultAtom); idOnParentFragToUse = atomList.get(defaultAtom).getID(); defaultAtom++; } else { idOnParentFragToUse = atomList.get(defaultAtom).getID(); } idOnParentFragToUse = frag.getAtomOrNextSuitableAtomOrThrow(frag.getAtomByIDOrThrow(idOnParentFragToUse), bondOrderRequired, true).getID(); parentfragAtom = frag.getAtomByIDOrThrow(idOnParentFragToUse); if (FragmentTools.isCharacteristicAtom(parentfragAtom)){ throw new StructureBuildingException("No suitable atom found to attach suffix"); } } else{ parentfragAtom = frag.getAtomByIDOrThrow(idOnParentFragToUse); } //create a new bond and associate it with the suffixfrag and both atoms. Remember the suffixFrag has not been imported into the frag yet List<Bond> bonds = new ArrayList<Bond>(suffixFrag.getFirstAtom().getBonds()); for (Bond bondToSuffix : bonds) { Atom suffixAtom; if (bondToSuffix.getToAtom().getElement().equals("R")) { suffixAtom = bondToSuffix.getFromAtom(); } else { suffixAtom = bondToSuffix.getToAtom(); } state.fragManager.createBond(parentfragAtom, suffixAtom, bondToSuffix.getOrder()); state.fragManager.removeBond(bondToSuffix); if (parentfragAtom.getIncomingValency()>2 && (suffixValue.equals("aldehyde") || suffixValue.equals("al")|| suffixValue.equals("aldoxime"))){//formaldehyde/methanal are excluded as they are substitutable if("X".equals(suffixAtom.getFirstLocant())){//carbaldehyde suffixAtom.setProperty(Atom.ISALDEHYDE, true); } else{ parentfragAtom.setProperty(Atom.ISALDEHYDE, true); } } } } } else if (suffixRuleTagName.equals(SUFFIXRULES_CHANGECHARGE_EL)) { if (idOnParentFragToUse != 0) { int chargeChange = Integer.parseInt(suffixRuleTag.getAttributeValue(SUFFIXRULES_CHARGE_ATR)); int protonChange = Integer.parseInt(suffixRuleTag.getAttributeValue(SUFFIXRULES_PROTONS_ATR)); frag.getAtomByIDOrThrow(idOnParentFragToUse).addChargeAndProtons(chargeChange, protonChange); } else{ applyUnlocantedChargeModification(atomList, suffixRuleTag); } } else if (suffixRuleTagName.equals(SUFFIXRULES_SETOUTATOM_EL)) { int outValency = suffixRuleTag.getAttribute(SUFFIXRULES_OUTVALENCY_ATR) != null ? Integer.parseInt(suffixRuleTag.getAttributeValue(SUFFIXRULES_OUTVALENCY_ATR)) : 1; if (suffix.getAttribute(SUFFIXPREFIX_ATR) == null) { if (idOnParentFragToUse != 0) { frag.addOutAtom(idOnParentFragToUse, outValency, true); } else { frag.addOutAtom(firstAtomID, outValency, false); } } else {//something like oyl on a ring, which means it is now carbonyl and the outAtom is on the suffix and not frag if (suffixFrag == null) { throw new StructureBuildingException("OPSIN bug: ordering of elements in suffixRules.xml wrong; setOutAtom found before addGroup"); } Set<Bond> bonds = state.fragManager.getInterFragmentBonds(suffixFrag); if (bonds.size() != 1) { throw new StructureBuildingException("OPSIN bug: Wrong number of bonds between suffix and group"); } for (Bond bond : bonds) { if (bond.getFromAtom().getFrag() == suffixFrag) { suffixFrag.addOutAtom(bond.getFromAtom(), outValency, true); } else { suffixFrag.addOutAtom(bond.getToAtom(), outValency, true); } } } } else if (suffixRuleTagName.equals(SUFFIXRULES_ADDSUFFIXPREFIXIFNONEPRESENTANDCYCLIC_EL)) { //already processed } else if (suffixRuleTagName.equals(SUFFIXRULES_ADDFUNCTIONALATOMSTOHYDROXYGROUPS_EL)) { //already processed } else if (suffixRuleTagName.equals(SUFFIXRULES_CHARGEHYDROXYGROUPS_EL)) { //already processed } else if (suffixRuleTagName.equals(SUFFIXRULES_REMOVEONEDOUBLEBONDEDOXYGEN_EL)) { //already processed } else if (suffixRuleTagName.equals(SUFFIXRULES_CONVERTHYDROXYGROUPSTOOUTATOMS_EL)) { //already processed } else { throw new StructureBuildingException("Unknown suffix rule:" + suffixRuleTagName); } } if (suffixFrag != null) {//merge suffix frag and parent fragment state.fragManager.removeAtomAndAssociatedBonds(suffixFrag.getFirstAtom());//the dummy R atom Set<String> suffixLocants = new HashSet<String>(suffixFrag.getLocants()); for (String suffixLocant : suffixLocants) { if (Character.isDigit(suffixLocant.charAt(0))){//check that numeric locants do not conflict with the parent fragment e.g. hydrazide 2' with biphenyl 2' if (frag.hasLocant(suffixLocant)){ suffixFrag.getAtomByLocant(suffixLocant).removeLocant(suffixLocant); } } } state.fragManager.incorporateFragment(suffixFrag, frag); } } } /** * Preference is given to mono cation/anions as they are expected to be more likely * Additionally, Typically if a locant has not been specified then it was intended to refer to a nitrogen even if the nitrogen is not at locant 1 e.g. isoquinolinium * Hence preference is given to nitrogen atoms and then to non carbon atoms * @param atomList * @param suffixRuleTag */ private void applyUnlocantedChargeModification(List<Atom> atomList, Element suffixRuleTag) { int chargeChange = Integer.parseInt(suffixRuleTag.getAttributeValue(SUFFIXRULES_CHARGE_ATR)); int protonChange = Integer.parseInt(suffixRuleTag.getAttributeValue(SUFFIXRULES_PROTONS_ATR)); Atom likelyAtom = null; Atom possibleHeteroatom = null; Atom possibleCarbonAtom = null; Atom possibleDiOrHigherIon = null; for (Atom a : atomList) { Integer[] stableValencies = ValencyChecker.getPossibleValencies(a.getElement(), a.getCharge() + chargeChange); if (stableValencies == null) {//unstable valency so seems unlikely continue; } String element = a.getElement(); int resultantExpectedValency = (a.getLambdaConventionValency() ==null ? ValencyChecker.getDefaultValency(element) : a.getLambdaConventionValency()) + a.getProtonsExplicitlyAddedOrRemoved() + protonChange; boolean matched = false; for (Integer stableValency : stableValencies) { if (stableValency ==resultantExpectedValency){ matched =true; break; } } if (!matched){//unstable valency so seems unlikely continue; } if (protonChange <0 && StructureBuildingMethods.calculateSubstitutableHydrogenAtoms(a)<=0){ continue; } if (Math.abs(a.getCharge())==0){ if (element.equals("N")){ likelyAtom = a; break; } else if (possibleHeteroatom ==null && !element.equals("C")){ possibleHeteroatom= a; } else if (possibleCarbonAtom ==null){ possibleCarbonAtom = a; } } else if (possibleDiOrHigherIon ==null){ possibleDiOrHigherIon = a; } } if (likelyAtom == null) { if (possibleHeteroatom !=null){ likelyAtom = possibleHeteroatom; } else if (possibleCarbonAtom !=null){ likelyAtom = possibleCarbonAtom; } else if (possibleDiOrHigherIon !=null){ likelyAtom = possibleDiOrHigherIon; } else{ likelyAtom = atomList.get(0); } } likelyAtom.addChargeAndProtons(chargeChange, protonChange); } /** * Moves a multiplier out of a bracket if the bracket contains only one substituent * e.g. (trimethyl) --> tri(methyl). * The multiplier may have locants e.g. [N,N-bis(2-hydroxyethyl)] * This is done because OPSIN has no idea what to do with (trimethyl) as there is nothing within the scope to substitute onto! * @param brackets */ private void moveErroneouslyPositionedLocantsAndMultipliers(List<Element> brackets) { for (int i = brackets.size()-1; i >=0; i Element bracket =brackets.get(i); Elements childElements = bracket.getChildElements(); boolean hyphenPresent = false; int childCount = childElements.size(); if (childCount==2){ for (int j = childCount -1; j >=0; j if (childElements.get(j).getLocalName().equals(HYPHEN_EL)){ hyphenPresent=true; } } } if (childCount==1 || hyphenPresent && childCount==2){ Elements substituentContent = childElements.get(0).getChildElements(); if (substituentContent.size()>=2){ Element locant =null; Element multiplier =null; Element possibleMultiplier = substituentContent.get(0); if (substituentContent.get(0).getLocalName().equals(LOCANT_EL)){//probably erroneous locant locant = substituentContent.get(0); possibleMultiplier = substituentContent.get(1); } if (possibleMultiplier.getLocalName().equals(MULTIPLIER_EL)){//erroneously placed multiplier present multiplier = possibleMultiplier; } if (locant!=null){ if (multiplier==null || matchComma.split(locant.getValue()).length == Integer.parseInt(multiplier.getAttributeValue(VALUE_ATR))){ locant.detach(); XOMTools.insertBefore(childElements.get(0), locant); } else{ continue; } } if (multiplier !=null){ multiplier.detach(); XOMTools.insertBefore(childElements.get(0), multiplier); } } } } } /** * Given the right most child of a word: * Checks whether this is multiplied e.g. methylenedibenzene * If it is then it checks for the presence of locants e.g. 4,4'-oxydibenzene which has been changed to oxy-4,4'-dibenzene * An attribute called inLocants is then added that is either INLOCANTS_DEFAULT or a comma seperated list of locants * @param state * @param rightMostElement * @throws ComponentGenerationException * @throws StructureBuildingException */ private void assignLocantsToMultipliedRootIfPresent(BuildState state, Element rightMostElement) throws ComponentGenerationException, StructureBuildingException { Elements multipliers = rightMostElement.getChildElements(MULTIPLIER_EL); if(multipliers.size() == 1) { Element multiplier =multipliers.get(0); if (XOMTools.getPrevious(multiplier)==null){ throw new StructureBuildingException("OPSIN bug: Unacceptable input to function"); } List<Element> locants = XOMTools.getChildElementsWithTagName(rightMostElement, MULTIPLICATIVELOCANT_EL); if (locants.size()>1){ throw new ComponentGenerationException("OPSIN bug: Only none or one multiplicative locant expected"); } int multiVal = Integer.parseInt(multiplier.getAttributeValue(VALUE_ATR)); if (locants.size()==0){ rightMostElement.addAttribute(new Attribute(INLOCANTS_ATR, INLOCANTS_DEFAULT)); } else{ Element locantEl = locants.get(0); String[] locantValues = matchComma.split(locantEl.getValue()); if (locantValues.length == multiVal){ rightMostElement.addAttribute(new Attribute(INLOCANTS_ATR, locantEl.getValue())); locantEl.detach(); } else{ throw new ComponentGenerationException("Mismatch between number of locants and number of roots"); } } } else if (rightMostElement.getLocalName().equals(BRACKET_EL)){ assignLocantsToMultipliedRootIfPresent(state, ((Element) rightMostElement.getChild(rightMostElement.getChildCount()-1))); } } /** * Assigns locants and multipliers to substituents/brackets * If both locants and multipliers are present a final check is done that the number of them agree. * WordLevel multipliers are processed e.g. diethyl ethanoate * Adding a locant to a root or any other group that cannot engage in substitive nomenclature will result in an exception being thrown * An exception is made for cases where the locant could be referring to a position on another word * @param state * @param subOrBracket * @throws ComponentGenerationException * @throws StructureBuildingException */ private void assignLocantsAndMultipliers(BuildState state, Element subOrBracket) throws ComponentGenerationException, StructureBuildingException { List<Element> locants = XOMTools.getChildElementsWithTagName(subOrBracket, LOCANT_EL); int multiplier =1; List<Element> multipliers = XOMTools.getChildElementsWithTagName(subOrBracket, MULTIPLIER_EL); Element parentElem =(Element)subOrBracket.getParent(); boolean oneBelowWordLevel = parentElem.getLocalName().equals(WORD_EL); Element groupIfPresent = subOrBracket.getFirstChildElement(GROUP_EL); if (multipliers.size()>0){ if (multipliers.size()>1){ throw new ComponentGenerationException(subOrBracket.getLocalName() +" has multiple multipliers, unable to determine meaning!"); } if (oneBelowWordLevel && XOMTools.getNextSibling(subOrBracket) == null && XOMTools.getPreviousSibling(subOrBracket) == null) { return;//word level multiplier } multiplier = Integer.parseInt(multipliers.get(0).getAttributeValue(VALUE_ATR)); subOrBracket.addAttribute(new Attribute(MULTIPLIER_ATR, multipliers.get(0).getAttributeValue(VALUE_ATR))); //multiplier is INTENTIONALLY not detached. As brackets/subs are only multiplied later on it is neccesary at that stage to determine what elements (if any) are in front of the multiplier if (groupIfPresent !=null && PERHALOGENO_SUBTYPE_VAL.equals(groupIfPresent.getAttributeValue(SUBTYPE_ATR))){ throw new StructureBuildingException(groupIfPresent.getValue() +" cannot be multiplied"); } } if(locants.size() > 0) { if (multiplier==1 && oneBelowWordLevel && XOMTools.getPreviousSibling(subOrBracket)==null){//locant might be word Level locant if (wordLevelLocantsAllowed(state, subOrBracket, locants.size())){//something like S-ethyl or S-(2-ethylphenyl) or S-4-tert-butylphenyl Element locant = locants.remove(0); if (matchComma.split(locant.getValue()).length!=1){ throw new ComponentGenerationException("Multiplier and locant count failed to agree; All locants could not be assigned!"); } parentElem.addAttribute(new Attribute(LOCANT_ATR, locant.getValue())); locant.detach(); if (locants.size()==0){ return; } } } if (subOrBracket.getLocalName().equals(ROOT_EL)){ locantsToDebugString(locants); throw new ComponentGenerationException(locantsToDebugString(locants)); } if (locants.size()!=1){ throw new ComponentGenerationException(locantsToDebugString(locants)); } Element locantEl = locants.get(0); String[] locantValues = matchComma.split(locantEl.getValue()); if (multiplier != locantValues.length){ throw new ComponentGenerationException("Multiplier and locant count failed to agree; All locants could not be assigned!"); } Element parent =(Element) subOrBracket.getParent(); //attempt to find cases where locant will not be utilised. A special case is made for carbonyl derivatives //e.g. 1H-2-benzopyran-1,3,4-trione 4-[N-(4-chlorophenyl)hydrazone] if (!parent.getLocalName().equals(WORD_EL) || !parent.getAttributeValue(TYPE_ATR).equals(WordType.full.toString()) || !state.currentWordRule.equals(WordRule.carbonylDerivative)){ Elements children =parent.getChildElements(); boolean foundSomethingToSubstitute =false; for (int i = parent.indexOf(subOrBracket) +1 ; i < children.size(); i++) { if (!children.get(i).getLocalName().equals(HYPHEN_EL)){ foundSomethingToSubstitute = true; } } if (!foundSomethingToSubstitute){ throw new ComponentGenerationException(locantsToDebugString(locants)); } } if (groupIfPresent !=null && PERHALOGENO_SUBTYPE_VAL.equals(groupIfPresent.getAttributeValue(SUBTYPE_ATR))){ throw new StructureBuildingException(groupIfPresent.getValue() +" cannot be locanted"); } subOrBracket.addAttribute(new Attribute(LOCANT_ATR, locantEl.getValue())); locantEl.detach(); } } private String locantsToDebugString(List<Element> locants) { StringBuilder message = new StringBuilder("Unable to assign all locants. "); message.append((locants.size() > 1) ? "These locants " : "This locant "); message.append((locants.size() > 1) ? "were " : "was "); message.append("not assigned: "); for(Element locant : locants) { message.append(locant.getValue()); message.append(" "); } return message.toString(); } private boolean wordLevelLocantsAllowed(BuildState state, Element subOrBracket, int numberOflocants) { Element parentElem =(Element)subOrBracket.getParent(); if (WordType.valueOf(parentElem.getAttributeValue(TYPE_ATR))==WordType.substituent && (XOMTools.getNextSibling(subOrBracket)==null || numberOflocants>=2)){ if (state.currentWordRule == WordRule.ester || state.currentWordRule == WordRule.functionalClassEster || state.currentWordRule == WordRule.multiEster || state.currentWordRule == WordRule.acetal){ return true; } } if ((state.currentWordRule == WordRule.biochemicalEster || (state.currentWordRule == WordRule.ester && (XOMTools.getNextSibling(subOrBracket)==null || numberOflocants>=2))) && parentElem.getLocalName().equals(WORD_EL)){ Element wordRule = (Element) parentElem.getParent(); Elements words = wordRule.getChildElements(WORD_EL); Element ateWord = words.get(words.size()-1); if (parentElem==ateWord){ return true; } } return false; } /** * If a word level multiplier is present e.g. diethyl butandioate then this is processed to ethyl ethyl butandioate * If wordCount is 1 then an exception is thrown if a multiplier is encountered e.g. triphosgene parsed as tri phosgene * @param state * @param word * @param wordCount * @throws StructureBuildingException * @throws ComponentGenerationException */ private void processWordLevelMultiplierIfApplicable(BuildState state, Element word, int wordCount) throws StructureBuildingException, ComponentGenerationException { if (word.getChildCount()==1){ Element subOrBracket = (Element) word.getChild(0); Element multiplier = subOrBracket.getFirstChildElement(MULTIPLIER_EL); if (multiplier !=null){ int multiVal =Integer.parseInt(multiplier.getAttributeValue(VALUE_ATR)); Elements locants =subOrBracket.getChildElements(LOCANT_EL); boolean assignLocants =false; boolean wordLevelLocants = wordLevelLocantsAllowed(state, subOrBracket, locants.size());//something like O,S-dimethyl phosphorothioate if (locants.size()>1){ throw new ComponentGenerationException("Unable to assign all locants"); } String[] locantValues = null; if (locants.size()==1){ locantValues = matchComma.split(locants.get(0).getValue()); if (locantValues.length == multiVal){ assignLocants=true; locants.get(0).detach(); if (wordLevelLocants){ word.addAttribute(new Attribute(LOCANT_ATR, locantValues[0])); } else{ throw new ComponentGenerationException(locantsToDebugString(OpsinTools.elementsToElementArrayList(locants))); } } else{ throw new ComponentGenerationException("Unable to assign all locants"); } } if (multiVal ==1){//mono return; } if (multiplier.getValue().equals("non")){ throw new StructureBuildingException("\"non\" probably means \"not\". If a multiplier of value 9 was intended \"nona\" should be used"); } List<Element> elementsNotToBeMultiplied = new ArrayList<Element>();//anything before the multiplier for (int i = subOrBracket.indexOf(multiplier) -1 ; i >=0 ; i Element el = (Element) subOrBracket.getChild(i); el.detach(); elementsNotToBeMultiplied.add(el); } multiplier.detach(); if (wordCount ==1){ throw new StructureBuildingException("Unexpected multiplier found at start of word. Perhaps the name is trivial e.g. triphosgene"); } for(int i=multiVal -1; i>=1; i Element clone = state.fragManager.cloneElement(state, word); if (assignLocants){ clone.getAttribute(LOCANT_ATR).setValue(locantValues[i]); } XOMTools.insertAfter(word, clone); } for (Element el : elementsNotToBeMultiplied) {//re-add anything before multiplier to original word subOrBracket.insertChild(el, 0); } } } } }
package org.eclipse.xtext.util; import static com.google.common.collect.Sets.*; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Field; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.jar.Attributes; import java.util.jar.Manifest; import com.google.common.base.Objects; import com.google.common.collect.Lists; /** * @author Sven Efftinge - Initial contribution and API * @author Jan Koehnlein - merging of parameterized entries * @since 2.2 moved to org.eclipse.xtext.util */ public class MergeableManifest extends Manifest { public static final Attributes.Name BUNDLE_NAME = new Attributes.Name("Bundle-Name"); public static final Attributes.Name BUNDLE_SYMBOLIC_NAME = new Attributes.Name("Bundle-SymbolicName"); public static final Attributes.Name BUNDLE_VERSION = new Attributes.Name("Bundle-Version"); public static final Attributes.Name BUNDLE_CLASSPATH = new Attributes.Name("Bundle-ClassPath"); public static final Attributes.Name BUNDLE_VENDOR = new Attributes.Name("Bundle-Vendor"); public static final Attributes.Name BUNDLE_REQUIRED_EXECUTION_ENV = new Attributes.Name( "Bundle-RequiredExecutionEnvironment"); public static final Attributes.Name EXPORT_PACKAGE = new Attributes.Name("Export-Package"); public static final Attributes.Name IMPORT_PACKAGE = new Attributes.Name("Import-Package"); public static final Attributes.Name REQUIRE_BUNDLE = new Attributes.Name("Require-Bundle"); public static final Attributes.Name BUNDLE_ACTIVATION_POLICY = new Attributes.Name("Bundle-ActivationPolicy"); public static final Attributes.Name BUNDLE_LOCALIZATION = new Attributes.Name("Bundle-Localization"); public static final Attributes.Name BUNDLE_ACTIVATOR = new Attributes.Name("Bundle-Activator"); private static final String LINEBREAK = "\r\n"; /* * java.util.Manifest throws an exception if line exceeds 512 chars */ /** * @since 2.9 */ public static String make512Safe(StringBuffer lines) { if (lines.length() > 512) { StringBuilder result = new StringBuilder(lines.length()); String[] splitted = lines.toString().split("\\r?\\n"); for(String string: splitted) { if (string.length() > 512) { int idx = 510; StringBuilder temp = new StringBuilder(string); int length = temp.length(); while (idx < length - 2) { temp.insert(idx, LINEBREAK+" "); idx += 512; length += 3; } result.append(temp.toString()); } else { result.append(string); } result.append(LINEBREAK); } return result.toString(); } return lines.toString(); } public class OrderAwareAttributes extends Attributes { public OrderAwareAttributes() { try { Field field = Attributes.class.getDeclaredField("map"); field.setAccessible(true); field.set(this, new LinkedHashMap<Object, Object>()); } catch (Exception e) { throw new IllegalStateException(e); } } @Override public Object put(Object name, Object value) { final Object result = super.put(name, value); if (result != null && !result.equals(value)) modified = true; return result; } /* * Copied from base class, but replaced call to make72Safe(buffer) with make512Safe(buffer) * and does not write empty values */ @SuppressWarnings("deprecation") public void myWriteMain(DataOutputStream out) throws IOException { // write out the *-Version header first, if it exists String vername = Name.MANIFEST_VERSION.toString(); String version = getValue(vername); if (version == null) { vername = Name.SIGNATURE_VERSION.toString(); version = getValue(vername); } if (version != null) { out.writeBytes(vername + ": " + version + LINEBREAK); } // write out all attributes except for the version // we wrote out earlier Iterator<Map.Entry<Object, Object>> it = entrySet().iterator(); while (it.hasNext()) { Map.Entry<Object, Object> e = it.next(); String value = (String) e.getValue(); if (!Strings.isEmpty(value)) { String name = ((Name) e.getKey()).toString(); if ((version != null) && !(name.equalsIgnoreCase(vername))) { StringBuffer buffer = new StringBuffer(name); buffer.append(": "); byte[] vb = value.trim().getBytes("UTF8"); value = new String(vb, 0, 0, vb.length); buffer.append(value); if (it.hasNext()) buffer.append(LINEBREAK); out.writeBytes(make512Safe(buffer)); } } } out.writeBytes(LINEBREAK); } /* * Copied from base class, but omitted call to make72Safe(buffer) * and does not write empty values */ @SuppressWarnings("deprecation") public void myWrite(DataOutputStream out) throws IOException { Iterator<Map.Entry<Object, Object>> it = entrySet().iterator(); while (it.hasNext()) { Map.Entry<Object, Object> e = it.next(); String value = (String) e.getValue(); if (Strings.isEmpty(value)) { StringBuffer buffer = new StringBuffer(((Name) e.getKey()).toString()); buffer.append(": "); byte[] vb = value.trim().getBytes("UTF8"); value = new String(vb, 0, 0, vb.length); buffer.append(value); if (it.hasNext()) buffer.append(LINEBREAK); out.writeBytes(make512Safe(buffer)); } } out.writeBytes(LINEBREAK); } } private boolean modified = false; private String projectName; public MergeableManifest(InputStream in) throws IOException { try { Field field = Manifest.class.getDeclaredField("attr"); field.setAccessible(true); field.set(this, new OrderAwareAttributes()); } catch (Exception e) { throw new IllegalStateException(e); } read(in); // hack: reconstruct linebreaks addRequiredBundles(Collections.<String>emptySet()); addExportedPackages(Collections.<String>emptySet()); addImportedPackages(Collections.<String>emptySet()); modified = false; } public MergeableManifest(InputStream in, String projectName) throws IOException { this(in); this.projectName = projectName; } /** * adds the qualified names to the require-bundle attribute, if not already * present. * * @param bundles - passing parameterized bundled (e.g. versions, etc.) is not supported */ public void addRequiredBundles(Set<String> bundles) { // TODO manage transitive dependencies // don't require self Set<String> bundlesToMerge; String bundleName = (String) getMainAttributes().get(BUNDLE_SYMBOLIC_NAME); if (bundleName != null) { int idx = bundleName.indexOf(';'); if (idx >= 0) { bundleName = bundleName.substring(0, idx); } } if (bundleName != null && bundles.contains(bundleName) || projectName != null && bundles.contains(projectName)) { bundlesToMerge = new LinkedHashSet<String>(bundles); bundlesToMerge.remove(bundleName); bundlesToMerge.remove(projectName); } else { bundlesToMerge = bundles; } String s = (String) getMainAttributes().get(REQUIRE_BUNDLE); Wrapper<Boolean> modified = Wrapper.wrap(this.modified); String result = mergeIntoCommaSeparatedList(s, bundlesToMerge, modified); this.modified = modified.get(); getMainAttributes().put(REQUIRE_BUNDLE, result); } /** * @since 2.9 */ public String getBREE() { return (String) getMainAttributes().get(BUNDLE_REQUIRED_EXECUTION_ENV); } /** * @since 2.9 */ public void setBREE(String bree) { String oldValue = getBREE(); if(Objects.equal(oldValue, bree)) { return; } getMainAttributes().put(BUNDLE_REQUIRED_EXECUTION_ENV, bree); this.modified = true; } /** * @since 2.9 */ public String getBundleActivator() { return (String) getMainAttributes().get(BUNDLE_ACTIVATOR); } /** * @since 2.9 */ public void setBundleActivator(String activator) { String oldValue = getBundleActivator(); if(Objects.equal(oldValue, activator)) { return; } getMainAttributes().put(BUNDLE_ACTIVATOR, activator); this.modified = true; } public boolean isModified() { return modified; } /* * Copied from base class to omit the call to make72Safe(..). */ @SuppressWarnings("deprecation") @Override public void write(OutputStream out) throws IOException { DataOutputStream dos = new DataOutputStream(out); // Write out the main attributes for the manifest ((OrderAwareAttributes) getMainAttributes()).myWriteMain(dos); // Now write out the pre-entry attributes Iterator<Map.Entry<String, Attributes>> it = getEntries().entrySet().iterator(); while (it.hasNext()) { Map.Entry<String, Attributes> e = it.next(); StringBuffer buffer = new StringBuffer("Name: "); String value = e.getKey(); if (value != null) { byte[] vb = value.getBytes("UTF8"); value = new String(vb, 0, 0, vb.length); } buffer.append(value); buffer.append(LINEBREAK); dos.writeBytes(make512Safe(buffer)); ((OrderAwareAttributes) e.getValue()).myWrite(dos); } dos.flush(); } /** * adds the qualified names to the export-package attribute, if not already * present. * * @param packages - passing parameterized packages is not supported */ public void addExportedPackages(Set<String> packages) { String s = (String) getMainAttributes().get(EXPORT_PACKAGE); Wrapper<Boolean> modified = Wrapper.wrap(this.modified); String result = mergeIntoCommaSeparatedList(s, packages, modified); this.modified = modified.get(); getMainAttributes().put(EXPORT_PACKAGE, result); } /** * adds the qualified names to the export-package attribute, if not already * present. * * @param packages - packages to add * * @since 2.9 */ public void addExportedPackages(String... packages) { addExportedPackages(newHashSet(packages)); } public void addImportedPackages(Set<String> packages) { String s = (String) getMainAttributes().get(IMPORT_PACKAGE); Wrapper<Boolean> modified = Wrapper.wrap(this.modified); String result = mergeIntoCommaSeparatedList(s, packages, modified); this.modified = modified.get(); getMainAttributes().put(IMPORT_PACKAGE, result); } /** * @since 2.0 */ protected static String[] splitQuoteAware(String string) { List<StringBuilder> result = Lists.newArrayList(new StringBuilder()); boolean inQuote = false; for (int i = 0; i < string.length(); i++) switch (string.charAt(i)) { case ',': if (inQuote) result.get(result.size() - 1).append(string.charAt(i)); else result.add(new StringBuilder()); break; case '"': inQuote = !inQuote; default: result.get(result.size() - 1).append(string.charAt(i)); } String[] resultArray = new String[result.size()]; for (int i = 0; i < result.size(); i++) resultArray[i] = result.get(i).toString(); return resultArray; } public static String mergeIntoCommaSeparatedList(String currentString, Set<String> toMergeIn, Wrapper<Boolean> modified) { String string = currentString == null ? "" : currentString; String[] split = splitQuoteAware(string); Map<String, String> name2parameters = new LinkedHashMap<String, String>(); for (int i = 0; i < split.length; i++) { String value = split[i].trim(); if (!value.equals("")) { Pair<String, String> nameParameter = getSplitEntry(value); name2parameters.put(nameParameter.getFirst(), nameParameter.getSecond()); } } for (String value : toMergeIn) { if (!value.trim().equals("")) { Pair<String, String> nameParameter = getSplitEntry(value.trim()); String existingParameter = name2parameters.get(nameParameter.getFirst()); if(existingParameter != null) { continue; } boolean newModified = modified.get(); newModified |= name2parameters.put(nameParameter.getFirst(), nameParameter.getSecond()) != null; modified.set(newModified); } } StringBuffer buff = new StringBuffer(string.length()); Iterator<Map.Entry<String, String>> iterator = name2parameters.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, String> entry = iterator.next(); buff.append(entry.getKey()); if(entry.getValue() != null) { buff.append(";").append(entry.getValue()); } if (iterator.hasNext()) buff.append(","+LINEBREAK+" "); } String result = buff.toString(); return result; } /** * @since 2.3 */ protected static Pair<String,String> getSplitEntry(String entry) { int semicolon = entry.indexOf(';'); String name; String parameter; if(semicolon == -1) { name=entry; parameter = null; } else { name = entry.substring(0, semicolon); parameter = entry.substring(semicolon + 1); } return Tuples.create(name, parameter); } }
package org.jkiss.dbeaver.ui.perspective; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IProject; import org.eclipse.core.runtime.IAdaptable; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.IJobChangeEvent; import org.eclipse.core.runtime.jobs.JobChangeAdapter; import org.eclipse.jface.preference.IPreferenceStore; import org.eclipse.jface.util.IPropertyChangeListener; import org.eclipse.jface.util.PropertyChangeEvent; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.swt.SWT; import org.eclipse.swt.events.*; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.*; import org.eclipse.ui.*; import org.eclipse.ui.menus.WorkbenchWindowControlContribution; import org.jkiss.code.Nullable; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.DBeaverPreferences; import org.jkiss.dbeaver.core.CoreMessages; import org.jkiss.dbeaver.core.DBeaverCore; import org.jkiss.dbeaver.core.DBeaverUI; import org.jkiss.dbeaver.ext.IDataSourceContainerProvider; import org.jkiss.dbeaver.ext.IDataSourceContainerProviderEx; import org.jkiss.dbeaver.ext.IDataSourceProvider; import org.jkiss.dbeaver.model.*; import org.jkiss.dbeaver.model.navigator.DBNDatabaseNode; import org.jkiss.dbeaver.model.navigator.DBNModel; import org.jkiss.dbeaver.model.runtime.DBRProgressMonitor; import org.jkiss.dbeaver.model.runtime.DBRRunnableWithProgress; import org.jkiss.dbeaver.model.struct.DBSDataSourceContainer; import org.jkiss.dbeaver.model.struct.DBSObject; import org.jkiss.dbeaver.model.struct.DBSObjectContainer; import org.jkiss.dbeaver.model.struct.DBSObjectSelector; import org.jkiss.dbeaver.registry.DataSourceRegistry; import org.jkiss.dbeaver.runtime.RuntimeUtils; import org.jkiss.dbeaver.runtime.jobs.DataSourceJob; import org.jkiss.dbeaver.ui.DBIcon; import org.jkiss.dbeaver.ui.IActionConstants; import org.jkiss.dbeaver.ui.UIUtils; import org.jkiss.dbeaver.ui.controls.CImageCombo; import org.jkiss.dbeaver.utils.ContentUtils; import org.jkiss.utils.CommonUtils; import java.lang.ref.SoftReference; import java.lang.reflect.InvocationTargetException; import java.text.MessageFormat; import java.util.*; import java.util.List; /** * DataSource Toolbar */ public class DataSourceManagementToolbar implements DBPRegistryListener, DBPEventListener, IPropertyChangeListener, IPageListener, IPartListener, ISelectionListener { static final Log log = LogFactory.getLog(DataSourceManagementToolbar.class); public static final String EMPTY_SELECTION_TEXT = CoreMessages.toolbar_datasource_selector_empty; private IWorkbenchWindow workbenchWindow; private IWorkbenchPart activePart; private Text resultSetSize; private CImageCombo connectionCombo; private CImageCombo databaseCombo; private SoftReference<DBSDataSourceContainer> curDataSourceContainer = null; private final List<DBPDataSourceRegistry> handledRegistries = new ArrayList<DBPDataSourceRegistry>(); private final List<DatabaseListReader> dbListReads = new ArrayList<DatabaseListReader>(); private static class DatabaseListReader extends DataSourceJob { private final CurrentDatabasesInfo databasesInfo; private boolean enabled; public DatabaseListReader(DBPDataSource dataSource) { super(CoreMessages.toolbar_datasource_selector_action_read_databases, null, dataSource); setSystem(true); this.databasesInfo = new CurrentDatabasesInfo(); this.enabled = false; } @Override public IStatus run(DBRProgressMonitor monitor) { DBSObjectContainer objectContainer = DBUtils.getAdapter(DBSObjectContainer.class, getDataSource()); DBSObjectSelector objectSelector = DBUtils.getAdapter(DBSObjectSelector.class, getDataSource()); if (objectContainer == null || objectSelector == null) { return Status.CANCEL_STATUS; } try { monitor.beginTask(CoreMessages.toolbar_datasource_selector_action_read_databases, 1); Class<? extends DBSObject> childType = objectContainer.getChildType(monitor); if (childType == null || !DBSObjectContainer.class.isAssignableFrom(childType)) { enabled = false; } else { enabled = true; Collection<? extends DBSObject> children = objectContainer.getChildren(monitor); databasesInfo.list = CommonUtils.isEmpty(children) ? Collections.<DBSObject>emptyList() : new ArrayList<DBSObject>(children); databasesInfo.active = objectSelector.getSelectedObject(); // Cache navigator nodes if (children != null) { for (DBSObject child : children) { DBeaverCore.getInstance().getNavigatorModel().getNodeByObject(monitor, child, false); } } } } catch (DBException e) { return RuntimeUtils.makeExceptionStatus(e); } finally { monitor.done(); } if (enabled) { // Cache navigator tree if (databasesInfo.list != null && !databasesInfo.list.isEmpty()) { DBNModel navigatorModel = DBeaverCore.getInstance().getNavigatorModel(); for (DBSObject database : databasesInfo.list) { if (DBUtils.getAdapter(DBSObjectContainer.class, database) != null) { navigatorModel.getNodeByObject(monitor, database, false); } } } } return Status.OK_STATUS; } } private static class CurrentDatabasesInfo { Collection<? extends DBSObject> list; DBSObject active; } public DataSourceManagementToolbar(IWorkbenchWindow workbenchWindow) { this.workbenchWindow = workbenchWindow; } private void dispose() { IWorkbenchPage activePage = workbenchWindow.getActivePage(); if (activePage != null) { pageClosed(activePage); } DBeaverCore.getInstance().getDataSourceProviderRegistry().removeDataSourceRegistryListener(this); for (DBPDataSourceRegistry registry : handledRegistries) { registry.removeDataSourceListener(this); } setActivePart(null); this.workbenchWindow.removePageListener(this); } @Override public void handleRegistryLoad(DBPDataSourceRegistry registry) { registry.addDataSourceListener(this); handledRegistries.add(registry); } @Override public void handleRegistryUnload(DBPDataSourceRegistry registry) { handledRegistries.remove(registry); registry.removeDataSourceListener(this); } @Nullable private IAdaptable getActiveObject() { if (activePart instanceof IEditorPart) { return ((IEditorPart) activePart).getEditorInput(); } else if (activePart instanceof IViewPart) { return activePart; } else { return null; } } private IProject getActiveProject() { final IAdaptable activeObject = getActiveObject(); if (activeObject instanceof IEditorInput) { final IFile file = ContentUtils.getFileFromEditorInput((IEditorInput) activeObject); if (file != null) { return file.getProject(); } } return DBeaverCore.getInstance().getProjectRegistry().getActiveProject(); } @Nullable private DBSDataSourceContainer getDataSourceContainer() { if (activePart instanceof IDataSourceContainerProvider) { return ((IDataSourceContainerProvider)activePart).getDataSourceContainer(); } final IAdaptable activeObject = getActiveObject(); if (activeObject == null) { return null; } if (activeObject instanceof IDataSourceContainerProvider) { return ((IDataSourceContainerProvider)activeObject).getDataSourceContainer(); } else if (activeObject instanceof IDataSourceProvider) { final DBPDataSource dataSource = ((IDataSourceProvider) activeObject).getDataSource(); return dataSource == null ? null : dataSource.getContainer(); } else { return null; } } @Nullable private IDataSourceContainerProviderEx getActiveDataSourceUpdater() { if (activePart instanceof IDataSourceContainerProviderEx) { return (IDataSourceContainerProviderEx) activePart; } else { final IAdaptable activeObject = getActiveObject(); if (activeObject == null) { return null; } return activeObject instanceof IDataSourceContainerProviderEx ? (IDataSourceContainerProviderEx)activeObject : null; } } private List<? extends DBSDataSourceContainer> getAvailableDataSources() { final DBSDataSourceContainer dataSourceContainer = getDataSourceContainer(); if (dataSourceContainer != null) { return dataSourceContainer.getRegistry().getDataSources(); } else { final IProject project = getActiveProject(); if (project != null) { DataSourceRegistry dataSourceRegistry = DBeaverCore.getInstance().getProjectRegistry().getDataSourceRegistry(project); return dataSourceRegistry == null ? Collections.<DBSDataSourceContainer>emptyList() : dataSourceRegistry.getDataSources(); } } return Collections.emptyList(); } public void setActivePart(@Nullable IWorkbenchPart part) { if (!(part instanceof IEditorPart)) { if (part == null || part.getSite() == null || part.getSite().getPage() == null) { part = null; } else { // Toolbar works only with active editor // Other parts just doesn't matter part = part.getSite().getPage().getActiveEditor(); } } if (activePart != part || activePart == null) { // Update previous statuses DBSDataSourceContainer container = getDataSourceContainer(); if (container != null) { container.getPreferenceStore().removePropertyChangeListener(this); } activePart = part; container = getDataSourceContainer(); if (container != null) { // Update editor actions container.getPreferenceStore().addPropertyChangeListener(this); } // Update controls and actions updateControls(true); } UIUtils.updateMainWindowTitle(workbenchWindow); } private void fillDataSourceList(boolean force) { if (connectionCombo.isDisposed()) { return; } final List<? extends DBSDataSourceContainer> dataSources = getAvailableDataSources(); boolean update = force; if (!update) { // Check if there are any changes final List<DBSDataSourceContainer> oldDataSources = new ArrayList<DBSDataSourceContainer>(); for (TableItem item : connectionCombo.getItems()) { if (item.getData() instanceof DBSDataSourceContainer) { oldDataSources.add((DBSDataSourceContainer) item.getData()); } } if (oldDataSources.size() == dataSources.size()) { for (int i = 0; i < dataSources.size(); i++) { if (dataSources.get(i) != oldDataSources.get(i)) { update = true; break; } } } else { update = true; } } if (update) { connectionCombo.setRedraw(false); } try { if (update) { connectionCombo.removeAll(); connectionCombo.add(DBIcon.TREE_DATABASE.getImage(), EMPTY_SELECTION_TEXT, null, null); } int selectionIndex = 0; if (activePart != null) { final DBSDataSourceContainer dataSourceContainer = getDataSourceContainer(); if (!CommonUtils.isEmpty(dataSources)) { DBNModel navigatorModel = DBeaverCore.getInstance().getNavigatorModel(); for (int i = 0; i < dataSources.size(); i++) { DBSDataSourceContainer ds = dataSources.get(i); if (ds == null) { continue; } if (update) { DBNDatabaseNode dsNode = navigatorModel.getNodeByObject(ds); connectionCombo.add( dsNode == null ? DBIcon.TREE_DATABASE.getImage() : dsNode.getNodeIconDefault(), ds.getName(), ds.getConnectionInfo().getColor(), ds); } else { TableItem item = connectionCombo.getItem(i + 1); item.setText(ds.getName()); item.setBackground(ds.getConnectionInfo().getColor()); } if (dataSourceContainer == ds) { selectionIndex = i + 1; } } } } connectionCombo.select(selectionIndex); } finally { if (update) { connectionCombo.setRedraw(true); } } } @Override public void handleDataSourceEvent(final DBPEvent event) { if (event.getAction() == DBPEvent.Action.OBJECT_ADD || event.getAction() == DBPEvent.Action.OBJECT_REMOVE || (event.getAction() == DBPEvent.Action.OBJECT_UPDATE && event.getObject() == getDataSourceContainer()) || (event.getAction() == DBPEvent.Action.OBJECT_SELECT && Boolean.TRUE.equals(event.getEnabled()) && event.getObject().getDataSource().getContainer() == getDataSourceContainer()) ) { Display.getDefault().asyncExec( new Runnable() { @Override public void run() { updateControls(true); } } ); } } private void updateControls(boolean force) { final DBSDataSourceContainer dataSourceContainer = getDataSourceContainer(); // Update resultset max size if (resultSetSize != null && !resultSetSize.isDisposed()) { if (dataSourceContainer == null) { resultSetSize.setEnabled(false); resultSetSize.setText(""); //$NON-NLS-1$ } else { resultSetSize.setEnabled(true); resultSetSize.setText(String.valueOf(dataSourceContainer.getPreferenceStore().getInt(DBeaverPreferences.RESULT_SET_MAX_ROWS))); } } // Update datasources combo updateDataSourceList(force); updateDatabaseList(force); } private void changeResultSetSize() { DBSDataSourceContainer dsContainer = getDataSourceContainer(); if (dsContainer != null) { String rsSize = resultSetSize.getText(); if (rsSize.length() == 0) { rsSize = "1"; //$NON-NLS-1$ } IPreferenceStore store = dsContainer.getPreferenceStore(); store.setValue(DBeaverPreferences.RESULT_SET_MAX_ROWS, rsSize); RuntimeUtils.savePreferenceStore(store); } } private void updateDataSourceList(boolean force) { if (connectionCombo != null && !connectionCombo.isDisposed()) { IDataSourceContainerProviderEx containerProvider = getActiveDataSourceUpdater(); if (containerProvider == null) { connectionCombo.removeAll(); connectionCombo.setEnabled(false); } else { connectionCombo.setEnabled(true); } fillDataSourceList(force); } } private void updateDatabaseList(boolean force) { if (!force) { DBSDataSourceContainer dsContainer = getDataSourceContainer(); if (curDataSourceContainer != null && dsContainer == curDataSourceContainer.get()) { // The same DS container - nothing to change in DB list return; } } // Update databases combo fillDatabaseCombo(); } private void fillDatabaseCombo() { if (databaseCombo != null && !databaseCombo.isDisposed()) { final DBSDataSourceContainer dsContainer = getDataSourceContainer(); databaseCombo.setEnabled(dsContainer != null); if (dsContainer != null && dsContainer.isConnected()) { final DBPDataSource dataSource = dsContainer.getDataSource(); synchronized (dbListReads) { for (DatabaseListReader reader : dbListReads) { if (reader.getDataSource() == dataSource) { return; } } DatabaseListReader databaseReader = new DatabaseListReader(dataSource); databaseReader.addJobChangeListener(new JobChangeAdapter() { @Override public void done(final IJobChangeEvent event) { UIUtils.runInUI(null, new Runnable() { @Override public void run() { fillDatabaseList((DatabaseListReader) event.getJob(), dsContainer); } }); } }); dbListReads.add(databaseReader); databaseReader.schedule(); } curDataSourceContainer = new SoftReference<DBSDataSourceContainer>(dsContainer); } else { curDataSourceContainer = null; databaseCombo.removeAll(); } } } private synchronized void fillDatabaseList(DatabaseListReader reader, DBSDataSourceContainer dsContainer) { databaseCombo.setRedraw(false); try { // Remove all but first item (which is constant) databaseCombo.removeAll(); synchronized (dbListReads) { dbListReads.remove(reader); } if (!reader.enabled || dsContainer.getDataSource() != reader.getDataSource()) { databaseCombo.setEnabled(reader.enabled); return; } if (databaseCombo.isDisposed()) { return; } if (reader.databasesInfo.list != null && !reader.databasesInfo.list.isEmpty()) { DBNModel navigatorModel = DBeaverCore.getInstance().getNavigatorModel(); for (DBSObject database : reader.databasesInfo.list) { if (database instanceof DBSObjectContainer) { DBNDatabaseNode dbNode = navigatorModel.getNodeByObject(database); if (dbNode != null) { DBPDataSource dataSource = database.getDataSource(); databaseCombo.add( dbNode.getNodeIconDefault(), database.getName(), dataSource.getContainer().getConnectionInfo().getColor(), database); } } } } if (reader.databasesInfo.active != null) { int dbCount = databaseCombo.getItemCount(); for (int i = 0; i < dbCount; i++) { String dbName = databaseCombo.getItemText(i); if (dbName.equals(reader.databasesInfo.active.getName())) { databaseCombo.select(i); break; } } } databaseCombo.setEnabled(reader.enabled); } finally { databaseCombo.setRedraw(true); } } private void changeDataSourceSelection() { if (connectionCombo == null || connectionCombo.isDisposed()) { return; } IDataSourceContainerProviderEx dataSourceUpdater = getActiveDataSourceUpdater(); if (dataSourceUpdater == null) { return; } DBSDataSourceContainer curDataSource = dataSourceUpdater.getDataSourceContainer(); List<? extends DBSDataSourceContainer> dataSources = getAvailableDataSources(); if (!CommonUtils.isEmpty(dataSources)) { int curIndex = connectionCombo.getSelectionIndex(); if (curIndex == 0) { if (curDataSource == null) { // Nothing changed return; } dataSourceUpdater.setDataSourceContainer(null); } else if (curIndex > dataSources.size()) { log.warn("Connection combo index out of bounds (" + curIndex + ")"); //$NON-NLS-1$ //$NON-NLS-2$ return; } else { // Change data source DBSDataSourceContainer selectedDataSource = dataSources.get(curIndex - 1); if (selectedDataSource == curDataSource) { return; } else { dataSourceUpdater.setDataSourceContainer(selectedDataSource); } } } updateControls(false); } private void changeDataBaseSelection() { if (databaseCombo == null || databaseCombo.isDisposed() || databaseCombo.getSelectionIndex() < 0) { return; } DBSDataSourceContainer dsContainer = getDataSourceContainer(); final String newName = databaseCombo.getItemText(databaseCombo.getSelectionIndex()); if (dsContainer != null && dsContainer.isConnected()) { final DBPDataSource dataSource = dsContainer.getDataSource(); try { DBeaverUI.runInProgressService(new DBRRunnableWithProgress() { @Override public void run(DBRProgressMonitor monitor) throws InvocationTargetException, InterruptedException { try { DBSObjectContainer oc = DBUtils.getAdapter(DBSObjectContainer.class, dataSource); DBSObjectSelector os = DBUtils.getAdapter(DBSObjectSelector.class, dataSource); if (oc != null && os != null && os.supportsObjectSelect()) { DBSObject newChild = oc.getChild(monitor, newName); if (newChild != null) { os.selectObject(monitor, newChild); } else { throw new DBException(MessageFormat.format(CoreMessages.toolbar_datasource_selector_error_database_not_found, newName)); } } else { throw new DBException(CoreMessages.toolbar_datasource_selector_error_database_change_not_supported); } } catch (DBException e) { throw new InvocationTargetException(e); } } }); } catch (InvocationTargetException e) { UIUtils.showErrorDialog( workbenchWindow.getShell(), CoreMessages.toolbar_datasource_selector_error_change_database_title, CoreMessages.toolbar_datasource_selector_error_change_database_message, e.getTargetException()); } catch (InterruptedException e) { // skip } } } @Override public void propertyChange(PropertyChangeEvent event) { if (event.getProperty().equals(DBeaverPreferences.RESULT_SET_MAX_ROWS) && !resultSetSize.isDisposed()) { if (event.getNewValue() != null) { resultSetSize.setText(event.getNewValue().toString()); } } } // IPageListener @Override public void pageActivated(IWorkbenchPage page) { // do nothing } @Override public void pageClosed(IWorkbenchPage page) { page.removePartListener(this); page.removeSelectionListener(this); } @Override public void pageOpened(IWorkbenchPage page) { page.addPartListener(this); page.addSelectionListener(this); } // IPartListener @Override public void partActivated(IWorkbenchPart part) { setActivePart(part); } @Override public void partBroughtToTop(IWorkbenchPart part) { } @Override public void partClosed(IWorkbenchPart part) { if (part == activePart) { setActivePart(null); } } @Override public void partDeactivated(IWorkbenchPart part) { // Do nothing // if (part == activePart) { // setActivePart(null); } @Override public void partOpened(IWorkbenchPart part) { } @Override public void selectionChanged(IWorkbenchPart part, ISelection selection) { if (part == activePart && selection instanceof IStructuredSelection) { final Object element = ((IStructuredSelection) selection).getFirstElement(); if (element != null) { if (RuntimeUtils.getObjectAdapter(element, DBSObject.class) != null) { updateControls(false); } } } } Control createControl(Composite parent) { workbenchWindow.addPageListener(DataSourceManagementToolbar.this); IWorkbenchPage activePage = workbenchWindow.getActivePage(); if (activePage != null) { pageOpened(activePage); } // Register as datasource listener in all datasources // We need it because at this moment there could be come already loaded registries (on startup) final DBeaverCore core = DBeaverCore.getInstance(); core.getDataSourceProviderRegistry().addDataSourceRegistryListener(DataSourceManagementToolbar.this); for (IProject project : core.getLiveProjects()) { if (project.isOpen()) { DataSourceRegistry registry = core.getProjectRegistry().getDataSourceRegistry(project); if (registry != null) { handleRegistryLoad(registry); } } } Composite comboGroup = new Composite(parent, SWT.NONE); GridLayout gl = new GridLayout(3, false); gl.marginWidth = 0; gl.marginHeight = 0; comboGroup.setLayout(gl); connectionCombo = new CImageCombo(comboGroup, SWT.DROP_DOWN | SWT.READ_ONLY | SWT.BORDER); GridData gd = new GridData(); gd.widthHint = 160; gd.minimumWidth = 160; connectionCombo.setLayoutData(gd); connectionCombo.setVisibleItemCount(15); connectionCombo.setWidthHint(160); connectionCombo.setToolTipText(CoreMessages.toolbar_datasource_selector_combo_datasource_tooltip); connectionCombo.add(DBIcon.TREE_DATABASE.getImage(), EMPTY_SELECTION_TEXT, null, null); connectionCombo.select(0); fillDataSourceList(true); connectionCombo.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { changeDataSourceSelection(); } @Override public void widgetDefaultSelected(SelectionEvent e) { widgetSelected(e); } }); databaseCombo = new CImageCombo(comboGroup, SWT.DROP_DOWN | SWT.READ_ONLY | SWT.BORDER); gd = new GridData(); gd.widthHint = 140; gd.minimumWidth = 140; databaseCombo.setLayoutData(gd); databaseCombo.setVisibleItemCount(15); databaseCombo.setWidthHint(140); databaseCombo.setToolTipText(CoreMessages.toolbar_datasource_selector_combo_database_tooltip); databaseCombo.add(DBIcon.TREE_DATABASE.getImage(), EMPTY_SELECTION_TEXT, null, null); databaseCombo.select(0); databaseCombo.addSelectionListener(new SelectionListener() { @Override public void widgetSelected(SelectionEvent e) { changeDataBaseSelection(); } @Override public void widgetDefaultSelected(SelectionEvent e) { widgetSelected(e); } }); updateDatabaseList(true); resultSetSize = new Text(comboGroup, SWT.BORDER); resultSetSize.setTextLimit(10); gd = new GridData(); gd.widthHint = 30; resultSetSize.setToolTipText(CoreMessages.toolbar_datasource_selector_resultset_segment_size); final DBSDataSourceContainer dataSourceContainer = getDataSourceContainer(); if (dataSourceContainer != null) { resultSetSize.setText(String.valueOf(dataSourceContainer.getPreferenceStore().getInt(DBeaverPreferences.RESULT_SET_MAX_ROWS))); } //resultSetSize.setDigits(7); resultSetSize.setLayoutData(gd); resultSetSize.addVerifyListener(UIUtils.getIntegerVerifyListener(Locale.getDefault())); resultSetSize.addFocusListener(new FocusListener() { @Override public void focusGained(FocusEvent e) { } @Override public void focusLost(FocusEvent e) { changeResultSetSize(); } }); comboGroup.addDisposeListener(new DisposeListener() { @Override public void widgetDisposed(DisposeEvent e) { DataSourceManagementToolbar.this.dispose(); } }); if (workbenchWindow != null && workbenchWindow.getActivePage() != null) { setActivePart(workbenchWindow.getActivePage().getActivePart()); } return comboGroup; } public static class ToolbarContribution extends WorkbenchWindowControlContribution { public ToolbarContribution() { super(IActionConstants.TOOLBAR_DATASOURCE); } @Override protected Control createControl(Composite parent) { DataSourceManagementToolbar toolbar = new DataSourceManagementToolbar(DBeaverUI.getActiveWorkbenchWindow()); return toolbar.createControl(parent); } } }
package org.nasdanika.cdo.web.routes.app; import java.io.BufferedReader; import java.io.StringReader; import java.lang.reflect.Field; import java.math.BigDecimal; import java.net.URL; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.ResourceBundle; import java.util.Set; import java.util.TreeMap; import java.util.function.Consumer; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.servlet.http.HttpServletRequest; import org.apache.commons.codec.binary.Hex; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.eclipse.e4.emf.xpath.EcoreXPathContextFactory; import org.eclipse.e4.emf.xpath.XPathContext; import org.eclipse.e4.emf.xpath.XPathContextFactory; import org.eclipse.emf.cdo.CDOObject; import org.eclipse.emf.cdo.common.id.CDOID; import org.eclipse.emf.cdo.view.CDOView; import org.eclipse.emf.common.notify.Notifier; import org.eclipse.emf.common.util.BasicDiagnostic; import org.eclipse.emf.common.util.Diagnostic; import org.eclipse.emf.common.util.Enumerator; import org.eclipse.emf.common.util.TreeIterator; import org.eclipse.emf.ecore.EAnnotation; import org.eclipse.emf.ecore.EAttribute; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.EClassifier; import org.eclipse.emf.ecore.EEnum; import org.eclipse.emf.ecore.EEnumLiteral; import org.eclipse.emf.ecore.EModelElement; import org.eclipse.emf.ecore.ENamedElement; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.EPackage.Registry; import org.eclipse.emf.ecore.EReference; import org.eclipse.emf.ecore.EStructuralFeature; import org.eclipse.emf.ecore.util.Diagnostician; import org.jsoup.Jsoup; import org.nasdanika.cdo.CDOViewContext; import org.nasdanika.cdo.web.CDOIDCodec; import org.nasdanika.core.Context; import org.nasdanika.core.CoreUtil; import org.nasdanika.html.Bootstrap; import org.nasdanika.html.Bootstrap.Color; import org.nasdanika.html.Bootstrap.Glyphicon; import org.nasdanika.html.Bootstrap.Style; import org.nasdanika.html.Breadcrumbs; import org.nasdanika.html.Button; import org.nasdanika.html.Button.Type; import org.nasdanika.html.FieldContainer; import org.nasdanika.html.FieldSet; import org.nasdanika.html.FontAwesome; import org.nasdanika.html.FontAwesome.WebApplication; import org.nasdanika.html.Form; import org.nasdanika.html.FormGroup; import org.nasdanika.html.FormInputGroup; import org.nasdanika.html.Fragment; import org.nasdanika.html.HTMLFactory; import org.nasdanika.html.HTMLFactory.InputType; import org.nasdanika.html.Input; import org.nasdanika.html.JsTree; import org.nasdanika.html.ListGroup; import org.nasdanika.html.Modal; import org.nasdanika.html.RowContainer.Row; import org.nasdanika.html.RowContainer.Row.Cell; import org.nasdanika.html.Select; import org.nasdanika.html.Table; import org.nasdanika.html.Tabs; import org.nasdanika.html.Tag; import org.nasdanika.html.Tag.TagName; import org.nasdanika.html.TextArea; import org.nasdanika.html.UIElement; import org.nasdanika.html.UIElement.Event; import org.nasdanika.web.HttpServletRequestContext; import org.pegdown.Extensions; import org.pegdown.LinkRenderer; import org.pegdown.PegDownProcessor; import org.pegdown.ast.AnchorLinkNode; import org.pegdown.ast.AutoLinkNode; import org.pegdown.ast.ExpLinkNode; import org.pegdown.ast.RefLinkNode; import org.pegdown.ast.WikiLinkNode; /** * Renders HTML elements for a target object such as form inputs, tables, e.t.c. * @author Pavel * * @param <T> */ public interface Renderer<C extends Context, T extends EObject> { public static final String TITLE_KEY = "title"; public static final String NAME_KEY = "name"; public static final String REFERRER_KEY = ".referrer"; public static final String INDEX_HTML = "index.html"; /** * Rendering can be customized by annotating model element with * annotations with this source. * * Adding UI rendering annotations to the model mixes modeling and UI concerns. * Also model annotations allow to define only one way of rendering a particular model element. * * Other customization options include overriding <code>getRenderAnnotation()</code> method or rendering methods, and * UI code generation, which leverages method overriding. */ String RENDER_ANNOTATION_SOURCE = "org.nasdanika.cdo.web.render"; /** * Default pegdown options. */ int PEGDOWN_OPTIONS = Extensions.ALL ^ Extensions.HARDWRAPS ^ Extensions.SUPPRESS_HTML_BLOCKS ^ Extensions.SUPPRESS_ALL_HTML; /** * Source for Ecore GenModel documentation. */ String ECORE_DOC_ANNOTATION_SOURCE = "http: Pattern SENTENCE_PATTERN = Pattern.compile(".+?[\\.?!]+\\s+"); int MIN_FIRST_SENTENCE_LENGTH = 20; int MAX_FIRST_SENTENCE_LENGTH = 250; // multi-line // input type // select options Renderer<Context, EObject> INSTANCE = new Renderer<Context, EObject>() { }; @SuppressWarnings("unchecked") default Renderer<C, EObject> getRenderer(EClass eClass) { // TODO extension point. return (Renderer<C, EObject>) INSTANCE; } /** * Returns renderer for an object. * @param modelObject * @return */ @SuppressWarnings("unchecked") default <M extends EObject> Renderer<C, M> getRenderer(M modelObject) { return modelObject == null ? null : (Renderer<C, M>) getRenderer(modelObject.eClass()); } /** * Returns source value for model annotations to use as the source of rendering annotations. * This implementation returns RENDER_ANNOTATION_SOURCE constant value ``org.nasdanika.cdo.web.render``. * This method can be overridden to "white-label" the model, i.e. to use rendering annotations with source * specific to the development organization, e.g. ``com.mycompany.render``. * * It can also be overridden to use different annotations profiles in different situations, e.g. ``com.mycompany.lob-a.render`` for business A and ``com.mycompany.lob-b.render`` for business B. * * @param context * @return */ default String getRenderAnnotationSource(C context) { return RENDER_ANNOTATION_SOURCE; } default String getRenderAnnotation(C context, EModelElement modelElement, String key) throws Exception { if (modelElement instanceof ENamedElement) { String rs = getResourceString(context, ((ENamedElement) modelElement), "render."+key, false); if (rs != null) { return rs; } } EAnnotation ra = modelElement.getEAnnotation(getRenderAnnotationSource(context)); if (ra != null) { String value = ra.getDetails().get(key); if (value != null) { return value; } } if (modelElement instanceof EClass) { return RenderUtil.getRenderAnnotation(getRenderAnnotationSource(context), (EClass) modelElement, key); } return null; } enum RenderAnnotation { /** * Set this annotation details key to ``false`` to hide structural feature from view. */ VISIBLE("visible"), /** * Set this annotation details key to ``false`` to hide make visible structural feature read-only in the edit form. */ EDITABLE("editable"), /** * On EClass this annotation is a pattern which is interpolated to generate object label. * On features and operations this annotation defines feature/operation label, a.k.a. "Display name". */ LABEL("label"), MODEL_ELEMENT_LABEL("model-element-label"), DOCUMENTATION("documentation"), FORMAT("format"), ICON("icon"), VIEW_TAB("view-tab"), IS_TAB("is-tab"), CHOICES_SELECTOR("choices-selector"), CATEGORY("category"), VIEW("view"), VIEW_FEATURES("view-features"), ELEMENT_TYPES("element-types"), CONTROL("control"), INPUT_TYPE("input-type"), CHOICES("choices"), FORM_INPUT_GROUP("form-input-group"), TREE_REFERENCES("tree-references"), HORIZONTAL_FORM("horizontal-form"), TREE_NODE("tree-node"); public final String literal; private RenderAnnotation(String literal) { this.literal = literal; } } /** * Retrieves render annotation using {@link RenderAnnotation} enum. * @param context * @param modelElement * @param renderAnnotation * @return * @throws Exception */ default String getRenderAnnotation(C context, EModelElement modelElement, RenderAnnotation renderAnnotation) throws Exception { return getRenderAnnotation(context, modelElement, renderAnnotation.literal); } /** * Derives label (display name) from a name. This implementation splits by camel case, * lowercases 1+ segments and capitalizes the 0 segment. E.g. myCoolName becomes My cool name. * @param name * @return */ default String nameToLabel(String name) { String[] cca = StringUtils.splitByCharacterTypeCamelCase(name); cca[0] = StringUtils.capitalize(cca[0]); for (int i=1; i<cca.length; ++i) { cca[i] = cca[i].toLowerCase(); } String classLabel = StringUtils.join(cca, " "); return classLabel; } /** * * @param obj * @return A list of structural features to include into the object view. This implementation * returns all object features authorized to read which are not annotated with <code>visible</code> details annotation set to <code>false</code> * @throws Exception */ default List<EStructuralFeature> getVisibleFeatures(C context, T obj) throws Exception { List<EStructuralFeature> ret = new ArrayList<>(); for (EStructuralFeature sf: obj.eClass().getEAllStructuralFeatures()) { if (!"false".equals(getRenderAnnotation(context, sf, RenderAnnotation.VISIBLE)) && context.authorizeRead(obj, sf.getName(), null)) { ret.add(sf); } } return ret; } /** * Renders object path to breadcrumbs. This implementation traverses the object containment path up to the top level object in the resource. * @param target * @param context * @param action Action, e.g. Edit or Add reference. * @param breadCrumbs * @throws Exception */ default void renderObjectPath(C context, T obj, String action, Breadcrumbs breadCrumbs) throws Exception { List<EObject> cPath = new ArrayList<EObject>(); for (EObject c = obj.eContainer(); c != null; c = c.eContainer()) { cPath.add(c); } Collections.reverse(cPath); for (EObject c: cPath) { Renderer<C, EObject> cRenderer = getRenderer(c); Object cLabel = cRenderer.renderIconAndLabel(context, c); if (cLabel != null) { String objectURI = cRenderer.getObjectURI(context, c); breadCrumbs.item(objectURI == null ? objectURI : objectURI+"/"+INDEX_HTML, cLabel); } } if (action == null) { breadCrumbs.item(null , renderIconAndLabel(context, obj)); } else { String objectURI = getObjectURI(context, obj); breadCrumbs.item(objectURI == null ? objectURI : objectURI+"/"+INDEX_HTML, renderLabel(context, obj)); breadCrumbs.item(null, breadCrumbs.getFactory().tag(TagName.b, action)); } } /** * Renders object path to a fragment with a given separator. This implementation traverses the object containment path up to the top level object in the resource. * @param target * @param context * @param action Action, e.g. Edit or Add reference. * @param breadCrumbs * @throws Exception */ default Fragment renderObjectPath(C context, T obj, Object separator) throws Exception { HTMLFactory htmlFactory = getHTMLFactory(context); Fragment ret = htmlFactory.fragment(); List<EObject> cPath = new ArrayList<EObject>(); for (EObject c = obj.eContainer(); c != null; c = c.eContainer()) { cPath.add(c); } Collections.reverse(cPath); for (EObject c: cPath) { Renderer<C, EObject> cRenderer = getRenderer(c); Object cLink = cRenderer.renderLink(context, c, false); if (cLink != null) { if (!ret.isEmpty()) { ret.content(separator); } ret.content(cLink); } } if (!ret.isEmpty()) { ret.content(separator); } ret.content(renderLink(context, obj, false)); return ret; } default Object renderLabel(C context, T obj) throws Exception { String labelAnnotation = getRenderAnnotation(context, obj.eClass(), RenderAnnotation.LABEL); if (labelAnnotation != null) { Map<String, EStructuralFeature> vsfm = new HashMap<>(); for (EStructuralFeature vsf: getVisibleFeatures(context, obj)) { vsfm.put(vsf.getName(), vsf); } String label = getHTMLFactory(context).interpolate(labelAnnotation, token -> { if ("eclass-name".equals(token)) { return obj.eClass().getName(); } if ("eclass-label".equals(token)) { try { return renderNamedElementLabel(context, obj.eClass()); } catch (Exception e) { e.printStackTrace(); return "*** ERROR ***"; } } EStructuralFeature vsf = vsfm.get(token); return vsf == null ? null : obj.eGet(vsf); }); return StringEscapeUtils.escapeHtml4(label); } for (EStructuralFeature vsf: getVisibleFeatures(context, obj)) { Object label = obj.eGet(vsf); return label == null ? label : StringEscapeUtils.escapeHtml4(String.valueOf(label)); } return null; } /** * Renders icon and label. * @param context * @param obj * @return * @throws Exception */ default Object renderIconAndLabel(C context, T obj) throws Exception { Object label = renderLabel(context, obj); if (label == null) { return renderIcon(context, obj); } Object icon = renderIcon(context, obj); if (icon == null) { return label; } return getHTMLFactory(context).fragment(icon, " ", label); } /** * Invokes getIcon(). If it returns null, this method also returns null. * Otherwise, if the return value contains ``/``, then it returns ``img`` tag with ``src`` attribute set to icon value. * If there is no ``/``, then it returns ``span`` with ``class`` attribute set to icon value (for glyphs, such as {@link Bootstrap.Glyphicon} or {@link FontAwesome}). * @param context * @param modelElement * @return * @throws Exception */ default Object renderIcon(C context, T obj) throws Exception { String icon = getIcon(context, obj); if (icon == null) { return null; } HTMLFactory htmlFactory = getHTMLFactory(context); if (icon.indexOf("/") == -1) { return htmlFactory.span().addClass(icon); } return htmlFactory.tag(TagName.img).attribute("src", icon); } /** * Icon "location" for a given object. This implementation returns icon of the object's {@link EClass}. * If icon contains ``/`` it is treated as URL, otherwise it is treated as css class, e.g. Bootstrap's ``glyphicon glyphicon-close``. * @param context * @param modelElement * @return * @throws Exception */ default String getIcon(C context, T obj) throws Exception { if (obj == null) { return null; } return getModelElementIcon(context, obj.eClass()); } /** * @param context * @param obj * @return Object URI. This implementation returns object path if context is instanceof {@link HttpServletRequestContext} * and ``null`` otherwise. * @throws Exception */ default String getObjectURI(C context, T obj) throws Exception { if (context instanceof HttpServletRequestContext) { return ((HttpServletRequestContext) context).getObjectPath(obj); } return null; } /** * Renders object link using object label and path. * @param context * @param obj * @return * @throws Exception */ default Object renderLink(C context, T obj, boolean withPathTooltip) throws Exception { String objectURI = getObjectURI(context, obj); Tag ret = getHTMLFactory(context).link(objectURI == null ? "#" : objectURI+"/"+INDEX_HTML, renderIconAndLabel(context, obj)); if (withPathTooltip) { String pathTxt = Jsoup.parse(renderObjectPath(context, obj, " > ").toString()).text(); ret.attribute("title", pathTxt); } ret.setData(obj); return ret; } /** * * @param context * @param namedElement * @return Value of ``model-element-label`` render annotation if it is present or element name passed through nameToLabel() conversion. * * @throws Exception */ default Object renderNamedElementLabel(C context, ENamedElement namedElement) throws Exception { String label = getRenderAnnotation(context, namedElement, RenderAnnotation.MODEL_ELEMENT_LABEL); if (label != null) { return label; } return nameToLabel(namedElement.getName()); } /** * * @param context * @param namedElement * @return Named element icon and label. * @throws Exception */ default Object renderNamedElementIconAndLabel(C context, ENamedElement namedElement) throws Exception { Object label = renderNamedElementLabel(context, namedElement); if (label == null) { return renderModelElementIcon(context, namedElement); } Object icon = renderModelElementIcon(context, namedElement); if (icon == null) { return label; } return getHTMLFactory(context).fragment(icon, " ", label); } /** * Invokes getModelElementIcon(). If it returns null, this method also returns null. * Otherwise, if the return value contains ``/``, then it returns ``img`` tag with ``src`` attribute set to icon value. * If there is no ``/``, then it returns ``span`` with ``class`` attribute set to icon value (for glyphs, such as {@link Bootstrap.Glyphicon} or {@link FontAwesome}). * @param context * @param modelElement * @return * @throws Exception */ default Object renderModelElementIcon(C context, EModelElement modelElement) throws Exception { String icon = getModelElementIcon(context, modelElement); if (icon == null) { return null; } HTMLFactory htmlFactory = getHTMLFactory(context); if (icon.indexOf("/") == -1) { return htmlFactory.span().addClass(icon); } return htmlFactory.tag(TagName.img).attribute("src", icon); } /** * Icon "location" for a given model element. This implementation returns ``icon`` render annotation. * If icon contains ``/`` it is treated as URL, otherwise it is treated as css class, e.g. Bootstrap's ``glyphicon glyphicon-close``. * * If annotation is not found and the model element is {@link EStructuralFeature}, then the icon of its type is returned. * @param context * @param modelElement * @return * @throws Exception */ default String getModelElementIcon(C context, EModelElement modelElement) throws Exception { String ret = getRenderAnnotation(context, modelElement, RenderAnnotation.ICON); if (ret == null && modelElement instanceof EStructuralFeature) { return getModelElementIcon(context, ((EStructuralFeature) modelElement).getEType()); } return ret; } /** * Renders individual feature value. This implementation: * * * Nulls are rendered as empty strings. * * For booleans invokes renderTrue() or renderFalse(); * * For dates uses ``format`` annotation to format with {@link SimpleDateFormat}, if the annotation is present. * * For numbers uses ``format`` annotation to format with {@link DecimalFormat}, if the annotation is present. * * Otherwise converts value to string and then html-escapes it. * @param context * @param feature * @param value * @return * @throws Exception */ default Object renderFeatureValue(C context, EStructuralFeature feature, Object value) throws Exception { if (value instanceof EObject) { return getRenderer(((EObject) value).eClass()).renderLink(context, (EObject) value, true); } if (value == null) { return ""; } if (value instanceof Boolean) { return (Boolean) value ? renderTrue(context) : renderFalse(context); } if (value instanceof Enumerator) { Enumerator enumeratorValue = (Enumerator) value; String ret = StringEscapeUtils.escapeHtml4(enumeratorValue.getLiteral()); EClassifier featureType = feature.getEType(); if (featureType instanceof EEnum) { EEnum featureEnum = (EEnum) featureType; EEnumLiteral enumLiteral = featureEnum.getEEnumLiteral(enumeratorValue.getName()); Tag literalDocumentationIcon = renderDocumentationIcon(context, enumLiteral, null, true); if (literalDocumentationIcon != null) { return ret + literalDocumentationIcon; } } return ret; } if (value instanceof Date) { String format = getRenderAnnotation(context, feature, RenderAnnotation.FORMAT); if (format != null) { SimpleDateFormat sdf = new SimpleDateFormat(format); return sdf.format((Date) value); } } else if (value instanceof Number) { String format = getRenderAnnotation(context, feature, RenderAnnotation.FORMAT); if (format != null) { DecimalFormat df = new DecimalFormat(format); return df.format(value); } } return StringEscapeUtils.escapeHtml4(value.toString()); } @SuppressWarnings("unchecked") default Object parseFeatureValue(C context, EStructuralFeature feature, String strValue) throws Exception { Class<?> featureTypeInstanceClass = feature.getEType().getInstanceClass(); if (featureTypeInstanceClass.isInstance(strValue)) { return strValue; } if (Boolean.class == featureTypeInstanceClass || boolean.class == featureTypeInstanceClass) { if (strValue == null) { return false; } switch (strValue) { case "true": case "on": return true; case "false": case "off": return false; default: Map<String,Object> env = new HashMap<>(); env.put("value", strValue); env.put("type", "boolean"); throw new IllegalArgumentException(getHTMLFactory(context).interpolate(getResourceString(context, "convertError", false), env)); } } if (featureTypeInstanceClass.isEnum()) { return featureTypeInstanceClass.getField(strValue).get(null); } if (CDOObject.class.isAssignableFrom(featureTypeInstanceClass) && context instanceof CDOViewContext<?, ?>) { return ((CDOViewContext<CDOView, ?>) context).getView().getObject(CDOIDCodec.INSTANCE.decode(context, strValue)); } if (Date.class == featureTypeInstanceClass) { String format = getRenderAnnotation(context, feature, RenderAnnotation.FORMAT); if (format != null) { SimpleDateFormat sdf = new SimpleDateFormat(format); return sdf.parse(strValue); } } if (Number.class.isAssignableFrom(featureTypeInstanceClass)) { String format = getRenderAnnotation(context, feature, RenderAnnotation.FORMAT); if (format != null) { DecimalFormat df = new DecimalFormat(format); if (BigDecimal.class == featureTypeInstanceClass) { df.setParseBigDecimal(true); return df.parse(strValue); } Number parsed = df.parse(strValue); if (Byte.class == featureTypeInstanceClass) { return parsed.byteValue(); } if (Double.class == featureTypeInstanceClass) { return parsed.doubleValue(); } if (Float.class == featureTypeInstanceClass) { return parsed.floatValue(); } if (Integer.class == featureTypeInstanceClass) { return parsed.intValue(); } if (Long.class == featureTypeInstanceClass) { return parsed.longValue(); } if (Short.class == featureTypeInstanceClass) { return parsed.shortValue(); } return context.convert(parsed, featureTypeInstanceClass); } } Object ret = context.convert(strValue, featureTypeInstanceClass); if (strValue != null && ret == null) { Map<String,Object> env = new HashMap<>(); env.put("value", strValue); env.put("type", featureTypeInstanceClass.getName()); throw new IllegalArgumentException(getHTMLFactory(context).interpolate(getResourceString(context, "convertError", false), env)); } return ret; } /** * Sets feature value from the context to the object. This implementation loads feature value(s) * from the {@link HttpServletRequest} parameters. * @param context * @param feature * @throws Exception */ default void setFeatureValue(C context, T obj, EStructuralFeature feature) throws Exception { if (context instanceof HttpServletRequestContext) { HttpServletRequest request = ((HttpServletRequestContext) context).getRequest(); if (feature.isMany()) { @SuppressWarnings("unchecked") Collection<Object> fv = (Collection<Object>) obj.eGet(feature); fv.clear(); String[] values = request.getParameterValues(feature.getName()); if (values != null) { for (String val: values) { fv.add(parseFeatureValue(context, feature, val)); } } } else { String value = request.getParameter(feature.getName()); if (value == null) { obj.eUnset(feature); } else { obj.eSet(feature, parseFeatureValue(context, feature, value)); } } } } /** * Renders true value. This implementation renders a checkmark of SUCCESS color. * @param context * @return * @throws Exception */ default Object renderTrue(C context) throws Exception { return getHTMLFactory(context).glyphicon(Glyphicon.ok).style().color().bootstrapColor(Color.SUCCESS); } /** * Renders false value. This implementation renders empty string. * @param context * @return * @throws Exception */ default Object renderFalse(C context) throws Exception { return ""; } /** * Renders element documentation. Documentation is retrieved from "documentation" annotation key * and, if not found, from Ecore GenModel annotation. * @param context * @param modelElement * @return gendoc annotation rendered as markdown to HTML or null if there is no documentation. * @throws Exception */ default String renderDocumentation(C context, EModelElement modelElement) throws Exception { String markdown = getRenderAnnotation(context, modelElement, RenderAnnotation.DOCUMENTATION); if (markdown == null) { EAnnotation docAnn = modelElement.getEAnnotation(ECORE_DOC_ANNOTATION_SOURCE); if (docAnn==null) { return null; } markdown = docAnn.getDetails().get(RenderAnnotation.DOCUMENTATION.literal); } if (CoreUtil.isBlank(markdown)) { return null; } return markdownToHtml(context, markdown); } default HTMLFactory getHTMLFactory(C context) throws Exception { HTMLFactory ret = context == null ? HTMLFactory.INSTANCE : context.adapt(HTMLFactory.class); return ret == null ? HTMLFactory.INSTANCE : ret; } /** * @param context * @param obj * @return Documentation reference for EClass or null. * @throws Exception */ default String getEClassifierDocRef(C context, EClassifier eClassifier) throws Exception { return null; } /** * Renders documentation modal if the element has documenation. * @param context * @param modelElement * @return documentation modal or null if the element is not documented. * @throws Exception */ default Modal renderDocumentationModal(C context, EModelElement modelElement) throws Exception { String doc = renderDocumentation(context, modelElement); if (doc == null) { return null; } Modal docModal = getHTMLFactory(context).modal(); if (doc.length() < 500) { docModal.small(); } else if (doc.length() > 2000) { docModal.large(); } docModal.title(getHTMLFactory(context).tag(TagName.h4, modelElement instanceof ENamedElement ? renderNamedElementIconAndLabel(context, (ENamedElement) modelElement) : "Documentation")); docModal.body(getHTMLFactory(context).div(doc).addClass("markdown-body").style().background().color().value("white")); // Forcing white background to work with dark schemes - ugly but visible.. EClass eClass = null; if (modelElement instanceof EClass) { eClass = (EClass) modelElement; } else if (modelElement.eContainer() instanceof EClass) { eClass = (EClass) modelElement.eContainer(); } if (eClass != null) { String href = getEClassifierDocRef(context, eClass); if (href != null) { docModal.footer(getHTMLFactory(context).link(href, getResourceString(context, "informationCenter", false)).attribute("target", "_blank")); } } return docModal; } /** * If element has documentation this method renders a question mark glyph icon with a tooltip containing the first sentence of documentation. * If docModal is not null, then the cursor is set to pointer and click on the icon opens the doc modal. * @param context * @param modelElement * @param docModal Doc modal to open on icon click. Can be null. * @param superscript if true, the icon is wrapped into ``sup`` tag. * @return * @throws Exception */ default Tag renderDocumentationIcon(C context, EModelElement modelElement, Modal docModal, boolean superscript) throws Exception { String doc = renderDocumentation(context, modelElement); if (doc == null) { return null; } String textDoc = Jsoup.parse(doc).text(); String firstSentence = firstSentence(context, textDoc); HTMLFactory htmlFactory = getHTMLFactory(context); Tag helpTag = renderHelpIcon(context); if (superscript) { helpTag = htmlFactory.tag(TagName.sup, helpTag); } helpTag.attribute(TITLE_KEY, firstSentence); // More than one sentence - opens doc modal. if (!textDoc.equals(firstSentence) && docModal != null) { helpTag.on(Event.click, "$('#"+docModal.getId()+"').modal('show')"); helpTag.style("cursor", "pointer"); return helpTag; } // Opens EClass documentation, if configured. EClassifier eClassifier = null; if (modelElement instanceof EClassifier) { eClassifier = (EClassifier) modelElement; } else if (modelElement.eContainer() instanceof EClassifier) { eClassifier = (EClassifier) modelElement.eContainer(); } if (eClassifier != null) { String href = getEClassifierDocRef(context, eClassifier); if (href != null) { helpTag.on(Event.click, "window.open('"+href+"', '_blank');"); helpTag.style("cursor", "pointer"); return helpTag; } } // Shows help icon helpTag.style("cursor", "help"); return helpTag; } /** * Converts markdown to HTML using {@link PegDownProcessor}. * @param context * @param markdown * @return * @throws Exception */ default String markdownToHtml(C context, String markdown) throws Exception { return new PegDownProcessor(PEGDOWN_OPTIONS).markdownToHtml(markdown, createPegDownLinkRenderer(context)); } /** * Creates link renderer. This implementation creates a renderer which opens links in new tabs * @param context * @return * @throws Exception */ default LinkRenderer createPegDownLinkRenderer(C context) throws Exception { return new LinkRenderer() { @Override public Rendering render(AnchorLinkNode node) { return super.render(node).withAttribute("target", "_blank"); } @Override public Rendering render(AutoLinkNode node) { return super.render(node).withAttribute("target", "_blank"); } @Override public Rendering render(ExpLinkNode node, String text) { return super.render(node, text).withAttribute("target", "_blank"); } @Override public Rendering render(RefLinkNode node, String url, String title, String text) { return super.render(node, url, title, text).withAttribute("target", "_blank"); } @Override public Rendering render(WikiLinkNode arg0) { return super.render(arg0).withAttribute("target", "_blank"); } }; } /** * Extracts the first sentence from HTML as plain text. * @param html * @return * @throws Exception */ default String firstHtmlSentence(C context, String html) throws Exception { if (CoreUtil.isBlank(html)) { return ""; } return firstSentence(context, Jsoup.parse(html).text()); } default int getMinFirstSentenceLength() { return MIN_FIRST_SENTENCE_LENGTH; } default int getMaxFirstSentenceLength() { return MAX_FIRST_SENTENCE_LENGTH; } default String firstSentence(C context, String text) throws Exception { if (text == null || text.length() < getMinFirstSentenceLength()) { return text; } Matcher matcher = SENTENCE_PATTERN.matcher(text); Z: while (matcher.find()) { String group = matcher.group(); String[] abbra = getResourceString(context, "abbreviations", false).split("\\|"); for (String abbr: abbra) { if (group.trim().endsWith(abbr)) { continue Z; } } if (matcher.end() > getMinFirstSentenceLength() && matcher.end() < getMaxFirstSentenceLength()) { return text.substring(0, matcher.end()); } } return text.length() < getMaxFirstSentenceLength() ? text : text.substring(0, getMaxFirstSentenceLength())+"..."; } // getHTMLFactory().div(markdownToHtml(context, markdown)).addClass("markdown-body"); default Object renderFirstDocumentationSentence(C context, EModelElement modelElement) throws Exception { Object doc = renderDocumentation(context, modelElement); return doc instanceof String ? firstHtmlSentence(context, (String) doc) : null; } /** * @param context * @param obj * @return true if view shall be rendered in a tab. This implementation return true if <code>view-tab</code> is set to true. * If there is no annotation this method returns true if number of attributes is more then ten. */ default boolean isViewTab(C context, T obj) throws Exception { String viewTabAnnotation = getRenderAnnotation(context, obj.eClass(), RenderAnnotation.VIEW_TAB); return viewTabAnnotation == null ? obj.eClass().getEAllAttributes().size() > 9 : "true".equals(viewTabAnnotation); } /** * @param context * @param obj * @return true if feature shall be rendered in a tab. * This implementation return true if <code>is-tab</code> is set to true. * If there is no annotation this method returns true if <code>isMany()</code> returns true. */ default boolean isTab(C context, EStructuralFeature structuralFeature) throws Exception { String isTabAnnotation = getRenderAnnotation(context, structuralFeature, RenderAnnotation.IS_TAB); if (isTabAnnotation == null) { return !(structuralFeature.getEType() instanceof EEnum) && structuralFeature.isMany(); } return "true".equals(isTabAnnotation); } /** * Renders label for the view tab, if view is rendered in a tab. * @param context * @param obj * @return * @throws Exception */ default Object renderViewTabLabel(C context, T obj) throws Exception { return getResourceString(context, "viewTabLabel", false); } /** * * @param context * @param obj * @return Locale to use in resource strings. This implementation uses request locale if context is {@link HttpServletRequestContext} or default JVM locale. * @throws Exception */ default Locale getLocale(C context) throws Exception { return context instanceof HttpServletRequestContext ? ((HttpServletRequestContext) context).getRequest().getLocale() : Locale.getDefault(); } /** * * @param context * @param obj * @param key * @param interpolate If true, the value of the key, if found, is interpolated using a context that resolves tokens to resource strings. * @return Resource string for a given key. This implementation uses resource bundle. If property with given key is not found in the resource bundle, then * this implementation reads ``<key>@`` property (property reference), e.g. ``documentation@`` for documentation. If such property is present, then a classloader * resource with the name equal to the property value is loaded, if present, and stringified with {@link CoreUtil}.stringify() method. If resource reference property value ends with ``.md``, * then its value is treated as markdown and is converted to HTML. Resource references and markdown conversion can be leveraged in localization of documentation * resources. * @throws Exception */ default String getResourceString(C context, String key, boolean interpolate) throws Exception { LinkedList<Class<?>> resourceBundleClasses = getResourceBundleClasses(context); String rs = null; for (Class<?> rbc: resourceBundleClasses) { ResourceBundle rb = ResourceBundle.getBundle(rbc.getName(), getLocale(context), rbc.getClassLoader()); if (rb.containsKey(key)) { rs = rb.getString(key); break; } String refKey = key + '@'; if (rb.containsKey(refKey)) { String rsRef = rb.getString(refKey); URL rsRes = rbc.getResource(rsRef); if (rsRes != null) { rs = CoreUtil.stringify(rsRes); if (rsRef.endsWith(".md")) { rs = markdownToHtml(context, rs); } break; } } } if (rs != null && interpolate) { return getHTMLFactory(context).interpolate(rs, token -> { try { return getResourceString(context, token, true); } catch (Exception e) { e.printStackTrace(); return null; } }); } return rs; } /** * * @param context * @param obj * @param key * @return Resource for a given key. This implementation uses resource bundle. If property with given key is not found in the resource bundle, then * this implementation reads ``<key>@`` property (property reference), e.g. ``documentation@`` for documentation. If such property is present, then a classloader * resource ({@link URL}) with the name equal to the property value is returned, if present. * @throws Exception */ default Object getResource(C context, String key) throws Exception { LinkedList<Class<?>> resourceBundleClasses = getResourceBundleClasses(context); Object res = null; for (Class<?> rbc: resourceBundleClasses) { ResourceBundle rb = ResourceBundle.getBundle(rbc.getName(), getLocale(context), rbc.getClassLoader()); if (rb.containsKey(key)) { res = rb.getObject(key); break; } String refKey = key + '@'; if (rb.containsKey(refKey)) { String rsRef = rb.getString(refKey); URL rsRes = rbc.getResource(rsRef); if (rsRes != null) { res = rsRes; // TODO - special handling of .properties, .json, and .yml resources - parse and return parse result - Properties, JSONObject or JSONArray, Maps/lists // If URL has a fragment, then treat is as a path in the result e.g. usd/rate. break; } } } return res; } /** * Retrieves resource string for a named element. This method calls getResourceString() with ``<element type>.<element name>.<key>`` key. E.g. ``class.MyClass.myKey``. */ default String getResourceString(C context, ENamedElement namedElement, String key, boolean interpolate) throws Exception { String className = namedElement.eClass().getName(); if (className.startsWith("E")) { className = className.substring(1); } return getResourceString(context, StringUtils.uncapitalize(className)+"."+namedElement.getName()+"."+key, interpolate); } /** * Retrieves resource string for a named element. This method calls getResource() with ``<element type>.<element name>.<key>`` key. E.g. ``class.MyClass.myKey``. */ default Object getResource(C context, ENamedElement namedElement, String key) throws Exception { String className = namedElement.eClass().getName(); if (className.startsWith("E")) { className = className.substring(1); } return getResource(context, StringUtils.uncapitalize(className)+"."+namedElement.getName()+"."+key); } /** * @param context * @return List of classes to load resource bundles from to search for resource strings. * This implementation returns list containing Renderer.class. * * Subtypes may override this method to add additional bundles. * @throws Exception */ default LinkedList<Class<?>> getResourceBundleClasses(C context) throws Exception { LinkedList<Class<?>> ret = new LinkedList<>(); ret.add(Renderer.class); return ret; } /** * Renders feature documentation modal dialogs. * @param context * @param obj * @return * @throws Exception */ default Map<EStructuralFeature, Modal> renderFeaturesDocModals(C context, T obj, Collection<EStructuralFeature> features) throws Exception { Map<EStructuralFeature, Modal> featureDocModals = new HashMap<>(); for (EStructuralFeature feature: features) { Modal fdm = renderDocumentationModal(context, feature); if (fdm != null) { featureDocModals.put(feature, fdm); } } return featureDocModals; } /** * Renders doc modals for visible features. * @param context * @param obj * @return * @throws Exception */ default Map<EStructuralFeature, Modal> renderVisibleFeaturesDocModals(C context, T obj) throws Exception { return renderFeaturesDocModals(context, obj, getVisibleFeatures(context, obj)); } /** * Renders object view. * @param context * @param obj * @param featureDocModals * @return * @throws Exception */ default Object renderView(C context, T obj, Map<EStructuralFeature, Modal> featureDocModals) throws Exception { return getHTMLFactory(context).fragment(renderViewFeatures(context, obj, featureDocModals), renderViewButtons(context, obj)); } /** * Renders view features with <code>!isTab()</code>. This implementation renders them in a table or a group of tables. * Features with ``category`` annotation are grouped into tables in panels by the annotation value. * Panel header shows category icon if ``category.<category name>.icon`` annotation is present on the object's EClass. * Panel header text is set to the value of ``category.<category name>.label`` annotation on the object's EClass, or to the category name if this annotation is not present. * @param context * @param obj * @param featureDocModals * @return * @throws Exception */ default Object renderViewFeatures(C context, T obj, Map<EStructuralFeature, Modal> featureDocModals) throws Exception { HTMLFactory htmlFactory = getHTMLFactory(context); Table featuresTable = htmlFactory.table(); featuresTable.col().bootstrap().grid().col(1); featuresTable.col().bootstrap().grid().col(11); List<EStructuralFeature> visibleFeatures = getVisibleFeatures(context, obj); Map<String,List<EStructuralFeature>> categories = new TreeMap<>(); for (EStructuralFeature vf: visibleFeatures) { String category = getRenderAnnotation(context, vf, RenderAnnotation.CATEGORY); if (!isTab(context, vf)) { if (category == null) { Row fRow = featuresTable.body().row(); Cell fLabelCell = fRow.header(renderNamedElementIconAndLabel(context, vf)).style().whiteSpace().nowrap(); Tag featureDocIcon = renderDocumentationIcon(context, vf, featureDocModals == null ? null : featureDocModals.get(vf), true); if (featureDocIcon != null) { fLabelCell.content(featureDocIcon); } fRow.cell(renderFeatureView(context, obj, vf, false)); } else { List<EStructuralFeature> categoryFeatures = categories.get(category); if (categoryFeatures == null) { categoryFeatures = new ArrayList<>(); categories.put(category, categoryFeatures); } categoryFeatures.add(vf); } } } if (categories.isEmpty()) { return featuresTable; } Fragment ret = htmlFactory.fragment(featuresTable); for (Entry<String, List<EStructuralFeature>> ce: categories.entrySet()) { Table categoryFeaturesTable = htmlFactory.table(); categoryFeaturesTable.col().bootstrap().grid().col(1); categoryFeaturesTable.col().bootstrap().grid().col(11); for (EStructuralFeature vf: ce.getValue()) { Row fRow = categoryFeaturesTable.body().row(); Cell fLabelCell = fRow.header(renderNamedElementIconAndLabel(context, vf)).style().whiteSpace().nowrap(); Tag featureDocIcon = renderDocumentationIcon(context, vf, featureDocModals == null ? null : featureDocModals.get(vf), true); if (featureDocIcon != null) { fLabelCell.content(featureDocIcon); } fRow.cell(renderFeatureView(context, obj, vf, false)); } Object header = ce.getKey(); String categoryIconAnnotation = getRenderAnnotation(context, obj.eClass(), "category."+ce.getKey()+".icon"); if (categoryIconAnnotation != null) { if (categoryIconAnnotation.indexOf("/") == -1) { header = htmlFactory.span().addClass(categoryIconAnnotation) + " " + header; } else { header = htmlFactory.tag(TagName.img).attribute("src", categoryIconAnnotation) + " " + header; } } ret.content(htmlFactory.panel(Style.DEFAULT, header, categoryFeaturesTable, null)); } return ret; } /** * Renders view buttons. This implementation renders Edit and Delete buttons. * @param context * @param obj * @param featureDocModals * @return * @throws Exception */ default Object renderViewButtons(C context, T obj) throws Exception { Tag ret = getHTMLFactory(context).div().style().margin("5px"); ret.content(renderEditButton(context, obj)); ret.content(renderDeleteButton(context, obj)); return ret; } /** * Renders edit button. * @param context * @param obj * @return * @throws Exception */ default Button renderEditButton(C context, T obj) throws Exception { if (context.authorizeUpdate(obj, null, null)) { HTMLFactory htmlFactory = getHTMLFactory(context); Button editButton = htmlFactory.button(renderEditIcon(context).style().margin().right("5px"), getResourceString(context, "edit", false)).style(Style.PRIMARY); wireEditButton(context, obj, editButton); Map<String, Object> env = new HashMap<>(); env.put(NAME_KEY, renderNamedElementLabel(context, obj.eClass())+" '"+renderLabel(context, obj)+"'"); String tooltip = htmlFactory.interpolate(getResourceString(context, "editTooltip", false), env); editButton.attribute(TITLE_KEY, StringEscapeUtils.escapeHtml4(tooltip)); return editButton; } return null; } /** * Assigns an action to the edit button. This implementation adds onClick handler which navigates to edit page. * @param feature * @param idx * @param editButton */ default void wireEditButton(C context, T obj, Button editButton) throws Exception { editButton.on(Event.click, "window.location='edit.html';"); } /** * Renders Save button. * @param context * @param obj * @return * @throws Exception */ default Button renderSaveButton(C context, T obj) throws Exception { if (context.authorizeUpdate(obj, null, null)) { HTMLFactory htmlFactory = getHTMLFactory(context); Button saveButton = htmlFactory.button(renderSaveIcon(context).style().margin().right("5px"), getResourceString(context, "save", false)).style(Style.PRIMARY); wireSaveButton(context, obj, saveButton); Map<String, Object> env = new HashMap<>(); env.put(NAME_KEY, renderNamedElementLabel(context, obj.eClass())+" '"+renderLabel(context, obj)+"'"); String tooltip = htmlFactory.interpolate(getResourceString(context, "saveTooltip", false), env); saveButton.attribute(TITLE_KEY, StringEscapeUtils.escapeHtml4(tooltip)); return saveButton; } return null; } /** * Assigns an action to the save button. This implementation set the button type to Submit. * @param feature * @param idx * @param editButton */ default void wireSaveButton(C context, T obj, Button saveButton) throws Exception { saveButton.type(Type.SUBMIT); } /** * Renders Save button. * @param context * @param obj * @return * @throws Exception */ default Button renderCancelButton(C context, T obj) throws Exception { if (context.authorizeUpdate(obj, null, null)) { HTMLFactory htmlFactory = getHTMLFactory(context); Button cancelButton = htmlFactory.button(renderCancelIcon(context).style().margin().right("5px"), getResourceString(context, "cancel", false)).style(Style.DANGER); wireCancelButton(context, obj, cancelButton); Map<String, Object> env = new HashMap<>(); env.put(NAME_KEY, renderNamedElementLabel(context, obj.eClass())+" '"+renderLabel(context, obj)+"'"); String tooltip = htmlFactory.interpolate(getResourceString(context, "cancelTooltip", false), env); cancelButton.attribute(TITLE_KEY, StringEscapeUtils.escapeHtml4(tooltip)); return cancelButton; } return null; } /** * Assigns an action to the cancel button. If there is "referrer" parameter, then this implementation sets onClick to navigate to the parameter name, * otherwise it sets button type to RESET. * the button type to Submit. * @param feature * @param idx * @param editButton */ default void wireCancelButton(C context, T obj, Button cancelButton) throws Exception { if (context instanceof HttpServletRequestContext) { HttpServletRequest request = ((HttpServletRequestContext) context).getRequest(); String referrer = request.getParameter(REFERRER_KEY); if (referrer == null) { referrer = request.getHeader("referer"); } if (referrer == null) { referrer = ((HttpServletRequestContext) context).getObjectPath(obj)+"/"+INDEX_HTML; } HTMLFactory htmlFactory = getHTMLFactory(context); Map<String, Object> env = new HashMap<>(); env.put(NAME_KEY, renderNamedElementLabel(context, obj.eClass())+" '"+renderLabel(context, obj)+"'"); String cancelConfirmationMessage = StringEscapeUtils.escapeEcmaScript(htmlFactory.interpolate(getResourceString(context, "confirmCancel", false), env)); cancelButton.on(Event.click, "if (confirm('"+cancelConfirmationMessage+"?')) window.location='"+referrer+"';return false;"); return; } cancelButton.type(Type.RESET); } /** * Renders edit icon. This implementation renders Bootstrap Glyphicon pencil. * @param context * @return * @throws Exception */ default Tag renderEditIcon(C context) throws Exception { return getHTMLFactory(context).glyphicon(Glyphicon.edit); } /** * Renders delete icon. This implementation renders Bootstrap Glyphicon trash. * @param context * @return * @throws Exception */ default Tag renderDeleteIcon(C context) throws Exception { return getHTMLFactory(context).glyphicon(Glyphicon.trash); } /** * Renders clear icon. This implementation renders Bootstrap Glyphicon erase. * @param context * @return * @throws Exception */ default Tag renderClearIcon(C context) throws Exception { return getHTMLFactory(context).glyphicon(Glyphicon.erase); } /** * Renders "details" icon. This implementation renders Bootstrap Glyphicon option_horizontal. * @param context * @return * @throws Exception */ default Tag renderDetailsIcon(C context) throws Exception { return getHTMLFactory(context).glyphicon(Glyphicon.option_horizontal); } /** * Renders clear icon. This implementation renders Bootstrap Glyphicon erase. * @param context * @return * @throws Exception */ default Tag renderCreateIcon(C context) throws Exception { return getHTMLFactory(context).fontAwesome().webApplication(WebApplication.magic).getTarget(); } /** * Renders clear icon. This implementation renders Bootstrap Glyphicon erase. * @param context * @return * @throws Exception */ default Tag renderAddIcon(C context) throws Exception { return getHTMLFactory(context).glyphicon(Glyphicon.plus_sign); } /** * Renders clear icon. This implementation renders Bootstrap Glyphicon erase. * @param context * @return * @throws Exception */ default Tag renderCancelIcon(C context) throws Exception { return getHTMLFactory(context).glyphicon(Glyphicon.remove); } /** * Renders clear icon. This implementation renders Bootstrap Glyphicon erase. * @param context * @return * @throws Exception */ default Tag renderSaveIcon(C context) throws Exception { return getHTMLFactory(context).glyphicon(Glyphicon.save); } /** * Renders edit button. * @param context * @param obj * @return * @throws Exception */ default Button renderDeleteButton(C context, T obj) throws Exception { if (obj.eContainer() != null && context.authorizeDelete(obj, null, null)) { HTMLFactory htmlFactory = getHTMLFactory(context); Button deleteButton = htmlFactory.button(renderDeleteIcon(context).style().margin().right("5px"), getResourceString(context, "delete", false)).style(Style.DANGER); Map<String, Object> env = new HashMap<>(); env.put(NAME_KEY, renderNamedElementLabel(context, obj.eClass())+" '"+renderLabel(context, obj)+"'"); String tooltip = htmlFactory.interpolate(getResourceString(context, "deleteTooltip", false), env); deleteButton.attribute(TITLE_KEY, StringEscapeUtils.escapeHtml4(tooltip)); wireDeleteButton(context, obj, deleteButton); return deleteButton; } return null; } /** * Assigns action to the delete button. This implementation sets onClick handler which navigates to the delete page. * @param context * @param obj * @param deleteButton * @throws Exception */ default void wireDeleteButton(C context, T obj, Button deleteButton) throws Exception { HTMLFactory htmlFactory = getHTMLFactory(context); Map<String, Object> env = new HashMap<>(); env.put(NAME_KEY, renderNamedElementLabel(context, obj.eClass())+" '"+renderLabel(context, obj)+"'"); String deleteConfirmationMessage = StringEscapeUtils.escapeEcmaScript(htmlFactory.interpolate(getResourceString(context, "confirmDelete", false), env)); // Delete through GET, not REST-compliant, but works with simple JavaScript. deleteButton.on(Event.click, "if (confirm('"+deleteConfirmationMessage+"?')) window.location='delete.html';"); } /** * Renders tabs. * @param context * @param obj * @param tabs * @param featureDocModals * @throws Exception */ default void renderTabs(C context, T obj, Tabs tabs, Map<EStructuralFeature, Modal> featureDocModals) throws Exception { if (isViewTab(context, obj)) { tabs.item(renderViewTabLabel(context, obj), renderView(context, obj, featureDocModals)); } for (EStructuralFeature vf: getVisibleFeatures(context, obj)) { Tag featureDocIcon = renderDocumentationIcon(context, vf, featureDocModals == null ? null : featureDocModals.get(vf), true); if (isTab(context, vf)) { Tag nameSpan = getHTMLFactory(context).span(renderNamedElementIconAndLabel(context, vf)); if (featureDocIcon != null) { nameSpan.content(featureDocIcon); } tabs.item(nameSpan, tabs.getFactory().div(renderFeatureView(context, obj, vf, true)).style().margin("3px")); } } } /** * Renders a view of the feature value. * A feature is rendered as a list if <code>view</code> annotation value is <code>list</code> or * if it is not present and the feature is rendered in the view (<code>!isTab()</code>). * <P/> * If <code>view</code> annotation value is <code>table</code> or * if it is not present and the feature is rendered in a tab (<code>isTab()</code>), * then the feature value is rendered as a table. Object features to show and their order in the * table can be defined using <code>view-features</code> annotation. Annotation value shall list * the features in the order in appearance, whitespace separated. * If this annotation is not present, all visible single-value features are shown in the order of their declaration. * @param context * @param obj * @param feature * @param showButtons if true, action buttons such as edit/delete/add/create/clear/select are shown if user is authorized to perform action. * @return * @throws Exception */ @SuppressWarnings("unchecked") default Object renderFeatureView(C context, T obj, EStructuralFeature feature, boolean showActionButtons) throws Exception { Fragment ret = getHTMLFactory(context).fragment(); Map<String, Object> env = new HashMap<>(); env.put(NAME_KEY, feature.getName()); Object featureValue = obj.eGet(feature); if (feature.isMany()) { String viewAnnotation = getRenderAnnotation(context, feature, RenderAnnotation.VIEW); boolean asTable = false; if (feature instanceof EReference) { boolean isTab = isTab(context, feature); if (viewAnnotation == null) { asTable = isTab; } else { if (isTab) { asTable = !"view".equals(viewAnnotation); } else { asTable = "table".equals(viewAnnotation); } } } if (asTable) { EClass refType = ((EReference) feature).getEReferenceType(); List<EStructuralFeature> tableFeatures = new ArrayList<EStructuralFeature>(); String viewFeaturesAnnotation = getRenderAnnotation(context, feature, RenderAnnotation.VIEW_FEATURES); if (viewFeaturesAnnotation == null) { for (EStructuralFeature sf: refType.getEAllStructuralFeatures()) { if (!sf.isMany() && context.authorizeRead(obj, feature.getName()+"/"+sf.getName(), null)) { tableFeatures.add(sf); } } } else { for (String vf: viewFeaturesAnnotation.split("\\s+")) { if (!CoreUtil.isBlank(vf)) { EStructuralFeature sf = refType.getEStructuralFeature(vf.trim()); if (sf != null && context.authorizeRead(obj, feature.getName()+"/"+sf.getName(), null)) { tableFeatures.add(sf); } } } } Map<EStructuralFeature, Modal> featureDocModals = new HashMap<>(); for (EStructuralFeature sf: tableFeatures) { Modal fdm = renderDocumentationModal(context, sf); if (fdm != null) { featureDocModals.put(sf, fdm); } ret.content(fdm); } Table featureTable = ret.getFactory().table().bordered().style().margin().bottom("5px"); Row headerRow = featureTable.header().row().style(Style.INFO); for (EStructuralFeature sf: tableFeatures) { Tag featureDocIcon = renderDocumentationIcon(context, sf, featureDocModals == null ? null : featureDocModals.get(sf), true); Cell headerCell = headerRow.header(renderNamedElementIconAndLabel(context, sf)); if (featureDocIcon != null) { headerCell.content(featureDocIcon); } } headerRow.header(getResourceString(context, "actions", false)).style().text().align().center(); int idx = 0; for (EObject fv: (Collection<EObject>) featureValue) { Row vRow = featureTable.body().row(); for (EStructuralFeature sf: tableFeatures) { vRow.cell(getRenderer(fv).renderFeatureView(context, fv, sf, false)); } Cell actionCell = vRow.cell().style().text().align().center(); actionCell.content(renderFeatureValueViewButton(context, obj, feature, idx, fv)); actionCell.content(renderFeatureValueDeleteButton(context, obj, feature, idx, fv)); ++idx; } ret.content(featureTable); ret.content(renderFeatureAddButton(context, obj, feature)); } else { Tag ul = getHTMLFactory(context).tag(TagName.ul); int idx = 0; Collection<Object> featureValues = (Collection<Object>) featureValue; if (featureValues.size() == 1) { Object v = featureValues.iterator().next(); ret.content(renderFeatureValue(context, feature, v)); if (feature instanceof EAttribute) { if (showActionButtons) { ret.content(renderFeatureValueEditButton(context, obj, feature, idx, v)); } } if (showActionButtons) { ret.content(renderFeatureValueDeleteButton(context, obj, feature, idx, v)); } } else if (!featureValues.isEmpty()) { for (Object v: featureValues) { Fragment liFragment = ret.getFactory().fragment(renderFeatureValue(context, feature, v)); if (feature instanceof EAttribute) { if (showActionButtons) { liFragment.content(renderFeatureValueEditButton(context, obj, feature, idx, v)); } } if (showActionButtons) { liFragment.content(renderFeatureValueDeleteButton(context, obj, feature, idx, v)); } ul.content(getHTMLFactory(context).tag(TagName.li, liFragment)); ++idx; } ret.content(ul); } if (showActionButtons) { ret.content(renderFeatureAddButton(context, obj, feature)); } } } else { ret.content(renderFeatureValue(context, feature, featureValue)); if (showActionButtons && feature instanceof EReference) { ret.content(renderFeatureValueEditButton(context, obj, feature, -1, featureValue)); ret.content(renderFeatureValueDeleteButton(context, obj, feature, -1, featureValue)); } } return ret; } /** * Renders a button to add a new value to the feature, maybe by creating one. * @param context * @param obj * @param feature * @return * @throws Exception */ default Button renderFeatureAddButton(C context, T obj, EStructuralFeature feature) throws Exception { if (context.authorizeCreate(obj, feature.getName(), null)) { // Adding to a reference is considered create. HTMLFactory htmlFactory = getHTMLFactory(context); Map<String, Object> env = new HashMap<>(); env.put(NAME_KEY, feature.getName()); boolean isCreate = feature instanceof EReference && ((EReference) feature).isContainment(); String tooltip = htmlFactory.interpolate(getResourceString(context, isCreate ? "createTooltip" : "selectTooltip", false), env); @SuppressWarnings("resource") Tag icon = isCreate ? renderCreateIcon(context) : renderAddIcon(context); Button addButton = htmlFactory.button(icon.style().margin().right("5px"), getResourceString(context, isCreate ? "create" : "select", false)) .style(Style.PRIMARY) .style().margin().left("5px") .attribute(TITLE_KEY, StringEscapeUtils.escapeHtml4(tooltip)); wireFeatureAddButton(context, obj, feature, addButton); return addButton; } return null; } /** * Assigns an action to the button. For containment references this feature invokes getFeatureElementTypes() and creates a drop-down button if there is more than one type. * For other features it adds onClick handler which navigates to add page. * If the feature supports multiple object types which can be added to it, use {@link Button}.item() method to * create a drop-down button with multiple add handlers. * @param context * @param obj * @param feature * @return * @throws Exception */ default void wireFeatureAddButton(C context, T obj, EStructuralFeature feature, Button addButton) throws Exception { if (feature instanceof EReference && ((EReference) feature).isContainment()) { List<EClass> featureElementTypes = getReferenceElementTypes(context, obj, (EReference) feature); if (featureElementTypes.isEmpty()) { addButton.disabled(); } else if (featureElementTypes.size() == 1) { EClass featureElementType = featureElementTypes.iterator().next(); String encodedPackageNsURI = Hex.encodeHexString(featureElementType.getEPackage().getNsURI().getBytes(/* UTF-8? */)); addButton.on(Event.click, "window.location='create/"+feature.getName()+"/"+encodedPackageNsURI+"/"+featureElementType.getName()+".html';"); } else { for (EClass featureElementType: featureElementTypes) { String encodedPackageNsURI = Hex.encodeHexString(featureElementType.getEPackage().getNsURI().getBytes(/* UTF-8? */)); addButton.item(getHTMLFactory(context).link("create/"+feature.getName()+"/"+encodedPackageNsURI+"/"+featureElementType.getName()+".html", getRenderer(featureElementType).renderNamedElementIconAndLabel(context, featureElementType))); } } } else { addButton.on(Event.click, "window.location='select/"+feature.getName()+".html';"); } } /** * Returns a list of {@link EClass}'es which can be instantiated and instances can be added as elements to the specified feature. * This implementation reads element types from ``element-types`` annotation. The list of element types shall be space-separated. Elements shall be in * the following format: ``<eclass name>[@<epackage ns uri>]``. EPackage namespace URI part can be omitted if the class is in the same package with the * feature's declaring EClass. * * If there is no ``element-types`` annotation, this implementation returns a list of all concrete classes from the session package registry which are compatible with the feature type. * @param context * @param obj * @param feature * @return * @throws Exception */ default List<EClass> getReferenceElementTypes(C context, T obj, EReference reference) throws Exception { List<EClass> ret = new ArrayList<>(); String elementTypesAnnotation = getRenderAnnotation(context, reference, RenderAnnotation.ELEMENT_TYPES); if (elementTypesAnnotation == null) { if (context instanceof CDOViewContext) { @SuppressWarnings("unchecked") Registry ePackageRegistry = ((CDOViewContext<CDOView, ?>) context).getView().getSession().getPackageRegistry(); for (String nsURI: ePackageRegistry.keySet()) { EPackage ePackage = ePackageRegistry.getEPackage(nsURI); if (ePackage!=null) { for (EClassifier ec: ePackage.getEClassifiers()) { if (ec instanceof EClass) { EClass eClass = (EClass) ec; if (!eClass.isAbstract() && !eClass.isInterface() && reference.getEReferenceType().isSuperTypeOf(eClass)) { ret.add(eClass); } } } } } } } else { for (String etSpec: elementTypesAnnotation.split("\\s+")) { if (!CoreUtil.isBlank(etSpec)) { int atIdx = etSpec.indexOf("@"); if (atIdx == -1) { EClassifier eClassifier = reference.getEContainingClass().getEPackage().getEClassifier(etSpec.trim()); if (eClassifier instanceof EClass) { ret.add((EClass) eClassifier); } } else if (context instanceof CDOViewContext) { @SuppressWarnings("unchecked") EPackage ePackage = ((CDOViewContext<CDOView, ?>) context).getView().getSession().getPackageRegistry().getEPackage(etSpec.substring(atIdx+1).trim()); if (ePackage != null) { EClassifier eClassifier = ePackage.getEClassifier(etSpec.trim()); if (eClassifier instanceof EClass) { ret.add((EClass) eClassifier); } } } } } } return ret; } /** * Renders delete button for feature value. * @param context * @param obj * @param feature * @param idx * @param value * @return * @throws Exception */ default Button renderFeatureValueDeleteButton(C context, T obj, EStructuralFeature feature, int idx, Object value) throws Exception { boolean authorized; if (value instanceof EObject && feature instanceof EReference && ((EReference) feature).isContainment()) { // Deletion from the repository. authorized = context.authorizeDelete(value, null, null); } else { // Removal from feature. authorized = context.authorizeDelete(obj, feature.getName(), null); } if (authorized) { HTMLFactory htmlFactory = getHTMLFactory(context); Map<String, Object> env = new HashMap<>(); env.put(NAME_KEY, feature.getName()); String tooltip = htmlFactory.interpolate(getResourceString(context, idx == -1 ? "clearTooltip" : "deleteTooltip", false), env); // Again, deletion through GET, not REST-compliant, but JavaScript part is kept simple. Button deleteButton = htmlFactory.button(idx == -1 ? renderClearIcon(context) : renderDeleteIcon(context)) .style(Style.DANGER) .style().margin().left("5px") .attribute(TITLE_KEY, StringEscapeUtils.escapeHtml4(tooltip)); wireFeatureValueDeleteButton(context, obj, feature, idx, value, deleteButton); return deleteButton; } return null; } /** * Assigns an action to the button. This implementation adds onClick handler which navigates to delete page. * @param feature * @param idx * @param editButton */ default void wireFeatureValueDeleteButton(C context, T obj, EStructuralFeature feature, int idx, Object value, Button deleteButton) throws Exception { Map<String, Object> env = new HashMap<>(); env.put(NAME_KEY, feature.getName()); String deleteConfirmationMessage = StringEscapeUtils.escapeEcmaScript(getHTMLFactory(context).interpolate(getResourceString(context, idx == -1 ? "confirmClear" : "confirmDelete", false), env)); String deleteLocation; if (value instanceof EObject && feature instanceof EReference && ((EReference) feature).isContainment()) { deleteLocation = getRenderer(((EObject) value).eClass()).getObjectURI(context, (EObject) value)+"/delete.html"; } else if (idx == -1) { deleteLocation = "delete/"+feature.getName()+".html"; } else { deleteLocation = "delete/"+feature.getName()+"/"+idx+".html"; } deleteButton.on(Event.click, "if (confirm('"+deleteConfirmationMessage+"?')) window.location='"+deleteLocation+"';"); } /** * Renders edit button for feature value * @param context * @param feature * @param idx Value index, shall be -1 for single-value features. * @return * @throws Exception */ default Button renderFeatureValueEditButton(C context, T obj, EStructuralFeature feature, int idx, Object value) throws Exception { if (context.authorizeUpdate(obj, feature.getName(), null)) { Map<String, Object> env = new HashMap<>(); env.put(NAME_KEY, feature.getName()); HTMLFactory htmlFactory = getHTMLFactory(context); String tooltip = htmlFactory.interpolate(getResourceString(context, idx == -1 ? "selectTooltip" : "editTooltip", false), env); Button editButton = htmlFactory.button(renderEditIcon(context)) .style(Style.PRIMARY) .style().margin().left("5px") .attribute(TITLE_KEY, StringEscapeUtils.escapeHtml4(tooltip)); wireFeatureValueEditButton(context, obj, feature, idx, value, editButton); return editButton; } return null; } /** * Assigns an action to the button. This implementation adds onClick handler which navigates to edit page. * @param feature * @param idx * @param editButton */ default void wireFeatureValueEditButton(C context, T obj, EStructuralFeature feature, int idx, Object value, Button editButton) throws Exception { if (idx == -1) { editButton.on(Event.click, "window.location='edit/"+feature.getName()+".html"); } else { editButton.on(Event.click, "window.location='edit/"+feature.getName()+"/"+idx+".html"); } } /** * Renders button which navigates to feature value details page. * @param context * @param feature * @param idx Value index, shall be -1 for single-value features. * @return * @throws Exception */ default Button renderFeatureValueViewButton(C context, T obj, EStructuralFeature feature, int idx, EObject value) throws Exception { if (context.authorizeRead(value, null, null)) { Map<String, Object> env = new HashMap<>(); env.put(NAME_KEY, getRenderer(value).renderLabel(context, value)); HTMLFactory htmlFactory = getHTMLFactory(context); String tooltip = htmlFactory.interpolate(getResourceString(context, "viewTooltip", false), env); Button viewButton = htmlFactory.button(renderDetailsIcon(context)) .style(Style.PRIMARY) .style().margin().left("5px") .attribute(TITLE_KEY, StringEscapeUtils.escapeHtml4(tooltip)); wireFeatureValueViewButton(context, obj, feature, idx, value, viewButton); return viewButton; } return null; } /** * Assigns an action to the button. This implementation adds onClick handler which navigates to the value object page. * @param feature * @param idx * @param editButton * @throws Exception */ default void wireFeatureValueViewButton(C context, T obj, EStructuralFeature feature, int idx, EObject value, Button viewButton) throws Exception { viewButton.on(Event.click, "window.location='"+getRenderer(((EObject) value).eClass()).getObjectURI(context, (EObject) value)+"/index.html'"); } // Forms rendering /** * * @param obj * @return A list of structural features to include into the object edit form. This implementation * returns all visible features with !isTab() and authorized to update unless <code>editable</code> annotation is set to <code>false</code> * @throws Exception */ default List<EStructuralFeature> getEditableFeatures(C context, T obj) throws Exception { List<EStructuralFeature> ret = new ArrayList<>(); for (EStructuralFeature vsf: getVisibleFeatures(context, obj)) { if (context.authorizeUpdate(obj, vsf.getName(), null)) { String eav = getRenderAnnotation(context, vsf, RenderAnnotation.EDITABLE); boolean isEditable = eav == null ? !isTab(context, vsf) : !"false".equals(eav); if (isEditable) { ret.add(vsf); } } } return ret; } /** * Returns feature value to be used in form controls like input, select, e.t.c. * This implementation returns name for enums and {@link CDOID} encoded with {@link CDOIDCodec} for {@link CDOObject}'s. * For all other values it returns HTML-escaped result of ``renderFeatureValue()`` * @param context * @param obj * @param feature * @param featureValue * @return * @throws Exception */ default String getFormControlValue(C context, T obj, EStructuralFeature feature, Object featureValue) throws Exception { if (featureValue == null) { return ""; } if (featureValue.getClass().isEnum()) { return ((Enum<?>) featureValue).name(); } if (featureValue instanceof CDOObject) { return CDOIDCodec.INSTANCE.encode(context, ((CDOObject) featureValue).cdoID()); } Object rfv = renderFeatureValue(context, feature, featureValue); return rfv == null ? "" : StringEscapeUtils.escapeHtml4(rfv.toString()); } // TODO - placeholder - might be an implicit default, placeholder selector /** * Renders control for the feature, e.g. input, select, or text area. * * Annotations: * * * ``control`` - defaults to input for attributes and multi-value features and select for references. * * input (default), * * select * * textarea * * ``input-type`` - for ``input`` control - one of {@link HTMLFactory.InputType} values. Checkbox for booleans and multi-value features, text otherwise. * @param context * @param obj * @param feature * @return Null for checkboxes and radios - they are added directly to the fieldContainer. Control to add to a field group otherwise. * @throws Exception */ @SuppressWarnings({ "unchecked" }) default UIElement<?> renderFeatureControl( C context, T obj, EStructuralFeature feature, FieldContainer<?> fieldContainer, Modal docModal, List<ValidationResult> validationResults, boolean helpTooltip) throws Exception { Object fv = obj.eGet(feature); String controlTypeStr = getRenderAnnotation(context, feature, RenderAnnotation.CONTROL); TagName controlType = controlTypeStr == null ? null : TagName.valueOf(controlTypeStr); if (controlType == null) { if (feature.isMany()) { controlType = TagName.input; } else if (feature instanceof EAttribute) { controlType = feature.getEType() instanceof EEnum ? TagName.select : TagName.input; } else { controlType = TagName.select; } } HTMLFactory htmlFactory = getHTMLFactory(context); Object label = renderNamedElementIconAndLabel(context, feature); String textLabel = Jsoup.parse(label.toString()).text(); if (helpTooltip) { label = getHTMLFactory(context).fragment(label, renderDocumentationIcon(context, feature, docModal, true)); } switch (controlType) { case input: String inputTypeStr = getRenderAnnotation(context, feature, RenderAnnotation.INPUT_TYPE); InputType inputType = inputTypeStr == null ? null : HTMLFactory.InputType.valueOf(inputTypeStr); if (inputType == null) { if (feature.isMany()) { inputType = InputType.checkbox; } else { Class<?> featureTypeInstanceClass = feature.getEType().getInstanceClass(); if (Boolean.class == featureTypeInstanceClass || boolean.class == featureTypeInstanceClass) { inputType = InputType.checkbox; } else if (Number.class.isAssignableFrom(featureTypeInstanceClass)) { inputType = InputType.number; } else if (Date.class == featureTypeInstanceClass) { inputType = InputType.date; } else { inputType = InputType.text; } } } switch (inputType) { case checkbox: if (feature.isMany()) { // Render a checkbox per choice. FieldSet checkboxesFieldSet = fieldContainer.fieldset(); checkboxesFieldSet .style().border().bottom("solid 1px "+Bootstrap.Color.GRAY_LIGHT.code) .style().margin().bottom("5px"); checkboxesFieldSet.legend(label); Set<String> valuesToSelect = new HashSet<>(); for (Object fev: ((Collection<Object>) fv)) { valuesToSelect.add(getFormControlValue(context, obj, feature, fev)); } for (Entry<String, String> fc: getFeatureChoices(context, obj, feature)) { Input checkbox = htmlFactory.input(inputType); checkbox.name(feature.getName()); checkbox.value(StringEscapeUtils.escapeHtml4(fc.getKey())); if (valuesToSelect.contains(fc.getKey())) { checkbox.attribute("checked", "true"); } checkboxesFieldSet.checkbox(fc.getValue(), checkbox, false); } return null; } Input checkbox = htmlFactory.input(inputType); checkbox.name(feature.getName()); checkbox.value(true); if (Boolean.TRUE.equals(fv)) { checkbox.attribute("checked", "true"); } fieldContainer.checkbox(renderNamedElementLabel(context, feature), checkbox, true); return null; case radio: // Radio - get values and labels from options. FieldSet radiosFieldSet = fieldContainer.fieldset(); radiosFieldSet.style() .border().bottom("solid 1px "+Bootstrap.Color.GRAY_LIGHT.code) .style().margin().bottom("5px"); radiosFieldSet.legend(label); String valueToSelect = getFormControlValue(context, obj, feature, fv); for (Entry<String, String> fc: getFeatureChoices(context, obj, feature)) { Input radio = htmlFactory.input(inputType) .name(feature.getName()) .value(StringEscapeUtils.escapeHtml4(fc.getKey())) .placeholder(textLabel) .required(isRequired(context, obj, feature)); if (valueToSelect != null && valueToSelect.equals(fc.getKey())) { radio.attribute("checked", "true"); } radiosFieldSet.radio(fc.getValue(), radio, false); } return null; default: return htmlFactory.input(inputType) .name(feature.getName()) .value(StringEscapeUtils.escapeHtml4(getFormControlValue(context, obj, feature, fv))) .placeholder(textLabel) .required(isRequired(context, obj, feature)); } case select: Select select = htmlFactory.select() .name(feature.getName()) .required(isRequired(context, obj, feature)); String valueToSelect = getFormControlValue(context, obj, feature, fv); for (Entry<String, String> fc: getFeatureChoices(context, obj, feature)) { select.option(StringEscapeUtils.escapeHtml4(fc.getKey()), StringEscapeUtils.escapeHtml4(Jsoup.parse(fc.getValue()).text()), valueToSelect != null && valueToSelect.equals(fc.getKey()), false); } return select; case textarea: TextArea textArea = htmlFactory.textArea() .name(feature.getName()) .placeholder(textLabel) .required(isRequired(context, obj, feature)); textArea.content(getFormControlValue(context, obj, feature, fv)); return textArea; default: throw new IllegalArgumentException("Unsupported control type: "+controlType); } } /** * Returns true if given feature is required. This implementation returns true if feature is not many and lower bound is not 0. * @param context * @param obj * @param feature * @throws Exception */ default boolean isRequired(C context, T obj, EStructuralFeature feature) throws Exception { return !feature.isMany() && feature.getLowerBound() != 0; } default Collection<Map.Entry<String, String>> getFeatureChoices(C context, T obj, EStructuralFeature feature) throws Exception { Map<String,String> collector = new LinkedHashMap<>(); if (feature instanceof EReference) { String choicesSelector = getRenderAnnotation(context, feature, RenderAnnotation.CHOICES_SELECTOR); // Accumulates selections for sorting before adding to the collector. List<String[]> accumulator = new ArrayList<>(); if (choicesSelector == null) { TreeIterator<Notifier> tit = obj.eResource().getResourceSet().getAllContents(); while (tit.hasNext()) { Notifier next = tit.next(); if (feature.getEType().isInstance(next) && next instanceof CDOObject) { CDOObject cdoNext = (CDOObject) next; Object iconAndLabel = getRenderer(cdoNext).renderIconAndLabel(context, cdoNext); if (iconAndLabel != null) { accumulator.add(new String[] { CDOIDCodec.INSTANCE.encode(context, cdoNext.cdoID()), iconAndLabel.toString() }); } } } } else { XPathContextFactory<EObject> xPathFactory = EcoreXPathContextFactory.newInstance(); XPathContext xPathContext = xPathFactory.newContext(obj); Iterator<Object> cit = xPathContext.iterate(choicesSelector); while (cit.hasNext()) { Object selection = cit.next(); if (feature.getEType().isInstance(selection) && selection instanceof CDOObject) { CDOObject cdoSelection = (CDOObject) selection; Object iconAndLabel = getRenderer(cdoSelection).renderIconAndLabel(context, cdoSelection); if (iconAndLabel != null) { accumulator.add(new String[] { CDOIDCodec.INSTANCE.encode(context, cdoSelection.cdoID()), iconAndLabel.toString() }); } } } } Collections.sort(accumulator, (e1, e2) -> { return Jsoup.parse(e1[1]).text().compareTo(Jsoup.parse(e2[1]).text()); }); for (String[] e: accumulator) { collector.put(e[0], e[1]); } } else { String choicesAnnotation = getRenderAnnotation(context, feature, RenderAnnotation.CHOICES); if (choicesAnnotation == null) { Class<?> featureTypeInstanceClass = feature.getEType().getInstanceClass(); if (featureTypeInstanceClass.isEnum()) { for (Field field: featureTypeInstanceClass.getFields()) { if (field.isEnumConstant()) { Object fieldValue = field.get(null); @SuppressWarnings("rawtypes") String name = ((Enum) fieldValue).name(); if (fieldValue instanceof Enumerator) { collector.put(name, ((Enumerator) fieldValue).getLiteral()); } else { collector.put(name, fieldValue.toString()); } } } } } else { try (BufferedReader br = new BufferedReader(new StringReader(choicesAnnotation))) { String line; while ((line = br.readLine()) != null) { if (!CoreUtil.isBlank(line) && !line.startsWith(" int idx = line.indexOf('='); if (idx == -1) { collector.put(line, line); } else { collector.put(line.substring(0, idx), line.substring(idx+1)); } } } } } } return Collections.unmodifiableCollection(collector.entrySet()); } /** * Renders doc modals for editable features. * @param context * @param obj * @return * @throws Exception */ default Map<EStructuralFeature, Modal> renderEditableFeaturesDocModals(C context, T obj) throws Exception { return renderFeaturesDocModals(context, obj, getEditableFeatures(context, obj)); } default Object renderFeatureFormGroupHelpText(C context, T obj, EStructuralFeature feature, Modal docModal) throws Exception { HTMLFactory htmlFactory = getHTMLFactory(context); Fragment ret = htmlFactory.fragment(); String doc = renderDocumentation(context, feature); if (doc != null) { String textDoc = Jsoup.parse(doc).text(); String firstSentence = firstSentence(context, textDoc); ret.content(firstSentence); if (!textDoc.equals(firstSentence) && docModal != null) { Tag helpGlyph = renderHelpIcon(context); helpGlyph.on(Event.click, "$('#"+docModal.getId()+"').modal('show')"); helpGlyph.style("cursor", "pointer"); ret.content(helpGlyph); } } return ret.isEmpty() ? null : ret; } /** * Renders help icon. This implementation uses FontAwesome WebApplication.question_circle_o. * @param context * @param obj * @return * @throws Exception */ default Tag renderHelpIcon(C context) throws Exception { return getHTMLFactory(context).fontAwesome().webApplication(WebApplication.question_circle_o).getTarget(); } /** * Renders form group if renderFeatureControl() returns non-null value. * This implementation renders FormInputGroup if: * * * ``form-input-group`` annotation is true. * * ``form-input-group`` annotation is not present and: * * control is ``input`` tag. * * Feature has either icon (rendered on the left) or help icon (rendered on the right). * * @param context * @param obj * @param feature * @param fieldContainer * @param docModal * @param errorMessage * @param helpTooltip If true, help message is rendered as a tooltip over a help annotation, like in the view. Otherwise it is renders as form group help text * (not visible in some layouts). * @return FormGroup. * @throws Exception */ default FormGroup<?> renderFeatureFormGroup( C context, T obj, EStructuralFeature feature, FieldContainer<?> fieldContainer, Modal docModal, List<ValidationResult> validationResults, boolean helpTooltip) throws Exception { UIElement<?> control = renderFeatureControl(context, obj, feature, fieldContainer, docModal, validationResults, helpTooltip); if (control == null) { return null; } Object icon = renderModelElementIcon(context, feature); Tag docIcon = renderDocumentationIcon(context, feature, docModal, false); boolean isFormInputGroup; String formInputGroupAnnotation = getRenderAnnotation(context, feature, RenderAnnotation.FORM_INPUT_GROUP); if (formInputGroupAnnotation == null) { isFormInputGroup = control instanceof Input && (icon != null || docIcon != null); } else { isFormInputGroup = "true".equals(formInputGroupAnnotation); } Object helpText = helpTooltip ? null : renderFeatureFormGroupHelpText(context, obj, feature, docModal); HTMLFactory htmlFactory = getHTMLFactory(context); FormGroup.Status status = null; if (validationResults != null) { Fragment htf = htmlFactory.fragment(); for (ValidationResult validationResult: validationResults) { htf.content(htmlFactory.label(validationResult.status.toStyle(), validationResult.message), " "); if (status == null || status.ordinal() < validationResult.status.ordinal()) { status = validationResult.status; } } if (!htf.isEmpty()) { helpText = htf.content(helpText); } } if (isFormInputGroup) { Object label = renderNamedElementLabel(context, feature); if (isRequired(context, obj, feature)) { label = htmlFactory.fragment(label, "*"); } FormInputGroup ret = fieldContainer.formInputGroup(label, control, helpText); if (icon != null) { ret.leftAddOn(icon); } if (docIcon != null) { ret.rightAddOn(docIcon); } if (status != null) { ret.status(status); } return ret; } Object label = renderNamedElementIconAndLabel(context, feature); if (isRequired(context, obj, feature)) { label = htmlFactory.fragment(label, "*"); } if (helpTooltip && docIcon != null) { label = htmlFactory.fragment(label, htmlFactory.tag(TagName.sup, docIcon)); } FormGroup<?> ret = fieldContainer.formGroup(label, control, helpText); if (status != null) { ret.status(status); } return ret; } /** * Helper class to pass validation results around. * @author Pavel * */ class ValidationResult { final FormGroup.Status status; final String message; public ValidationResult(FormGroup.Status status, String message) { super(); this.status = status; this.message = message; } } /** * Renders form groups for editable features. * Features with ``category`` annotation are grouped into fieldsets by the annotation value. * Field set legend shows category icon if ``category.<category name>.icon`` annotation is present on the object's EClass. * Legend's text is set to the value of ``category.<category name>.label`` annotation on the object's EClass, or to the category name if this annotation is not present. * @param context * @param obj * @param fieldContainer * @param docModals * @param validationResults * @param helpTooltip * @throws Exception */ default List<FormGroup<?>> renderEditableFeaturesFormGroups( C context, T obj, FieldContainer<?> fieldContainer, Map<EStructuralFeature, Modal> docModals, Map<EStructuralFeature,List<ValidationResult>> validationResults, boolean helpTooltip) throws Exception { Map<String,List<EStructuralFeature>> categories = new TreeMap<>(); List<FormGroup<?>> ret = new ArrayList<>(); for (EStructuralFeature esf: getEditableFeatures(context, obj)) { String category = getRenderAnnotation(context, esf, RenderAnnotation.CATEGORY); if (category == null) { FormGroup<?> fg = renderFeatureFormGroup(context, obj, esf, fieldContainer, docModals.get(esf), validationResults.get(esf), helpTooltip); if (fg != null) { ret.add(fg); } } else { List<EStructuralFeature> categoryFeatures = categories.get(category); if (categoryFeatures == null) { categoryFeatures = new ArrayList<>(); categories.put(category, categoryFeatures); } categoryFeatures.add(esf); } } HTMLFactory htmlFactory = getHTMLFactory(context); for (Entry<String, List<EStructuralFeature>> ce: categories.entrySet()) { FieldSet categoryFieldSet = fieldContainer.fieldset(); categoryFieldSet.style().margin().bottom("5px"); String category = ce.getKey(); String categoryIcon = getRenderAnnotation(context, obj.eClass(), "category."+category+".icon"); String categoryLabel = getRenderAnnotation(context, obj.eClass(), "category."+category+".label"); if (categoryLabel == null) { categoryLabel = category; } if (categoryIcon == null) { categoryFieldSet.legend(categoryLabel); } else if (categoryIcon.indexOf("/") == -1) { categoryFieldSet.legend(htmlFactory.span().addClass(categoryIcon), " ", categoryLabel); } else { categoryFieldSet.legend(htmlFactory.tag(TagName.img).attribute("src", categoryIcon), " ", categoryLabel); } for (EStructuralFeature cesf: ce.getValue()) { FormGroup<?> fg = renderFeatureFormGroup(context, obj, cesf, categoryFieldSet, docModals.get(cesf), validationResults.get(cesf), helpTooltip); if (fg != null) { ret.add(fg); } } } return ret; } /** * Reads feature values for editable features from the request, parses them and sets feature values. * Then validates the object. Invokes diagnostic consumer, if it is not null, for object-level results and results associated with one of editable features. * @return true if there are no errors in object-level and editable features results. */ default boolean setEditableFeatures(C context, T obj, Consumer<Diagnostic> diagnosticConsumer) throws Exception { List<EStructuralFeature> editableFeatures = getEditableFeatures(context, obj); for (EStructuralFeature esf: editableFeatures) { try { setFeatureValue(context, obj, esf); } catch (Exception e) { diagnosticConsumer.accept(new BasicDiagnostic(Diagnostic.ERROR, getClass().getName(), 0, e.getMessage(), new Object[] { obj, esf, e })); } } Diagnostic vr = validate(context, obj); boolean noErrors = true; for (Diagnostic vc: vr.getChildren()) { List<?> vcData = vc.getData(); if (!vcData.isEmpty() && vcData.get(0) == obj && (vcData.size() == 1 || editableFeatures.contains(vcData.get(1)))) { if (vc.getSeverity() == Diagnostic.ERROR) { noErrors = false; } } if (diagnosticConsumer != null) { diagnosticConsumer.accept(vc); } } return noErrors; } default Diagnostic validate(C context, T obj) throws Exception { Diagnostician diagnostician = new Diagnostician() { @Override public String getObjectLabel(EObject eObject) { try { Object label = getRenderer(eObject).renderLabel(context, eObject); String ret = label== null ? null : Jsoup.parse(label.toString()).text(); return ret == null ? super.getObjectLabel(eObject) : ret; } catch (Exception e) { return super.getObjectLabel(eObject); } } @Override public Map<Object, Object> createDefaultContext() { Map<Object, Object> ret = super.createDefaultContext(); ret.put(Context.class, context); ret.put(Renderer.class, this); return ret; } }; return diagnostician.validate(obj); } /** * Renders a tree item for the object with the tree features under. * @param context Context * @param obj Object * @param depth tree depth, -1 - infinite depth. * @param itemFilter If not null, it is invoked when object list items are created. Filters can decorate or replace list items. Filter is invoked twice per item - first for the label and then for * the entire ``li`` tag. In both cases data is set to the object. For the ``li`` invocation ``role`` property is set to ``item`` * @param jsTree If true, list items are rendered for jsTree. It is responsibility of the caller code to create jsTree container and provide event handler for clicks. * @return */ default Object renderTreeItem(C context, T obj, int depth, Function<Object, Object> itemFilter, boolean jsTree) throws Exception { HTMLFactory htmlFactory = getHTMLFactory(context); Tag ret = htmlFactory.tag(TagName.li); ret.setData(obj); ret.setData("role", "item"); if (jsTree) { JsTree jt = ret.jsTree(); jt.icon(getIcon(context, obj)); String objectURI = getObjectURI(context, obj); Object link = htmlFactory.link(objectURI == null ? "#" : objectURI+"/"+INDEX_HTML, renderLabel(context, obj)).setData(obj); if (itemFilter != null) { link = itemFilter.apply(link); } ret.content(link); } else { Object link = renderLink(context, obj, true); if (itemFilter != null) { link = itemFilter.apply(link); } ret.content(link); } ret.content(renderReferencesTree(context, obj, depth, itemFilter, jsTree)); return itemFilter == null ? ret : itemFilter.apply(ret); } /** * Renders an object tree of tree references of the argument object. Tree features are those listed in the ``tree-references`` annotation separated by space. * If there is no annotation, then containing many features are considered as tree features. If ``tree-node`` annotation of the feature is set to false, then feature elements * appear directly under the container. Otherwise, a tree node with feature name and icon (if available) is created to hold feature elements. * @param context Context * @param obj Object * @param depth tree depth, -1 - infinite depth. * @param itemFilter If not null, it is invoked when object list items are created. Filters can decorate or replace list items. * @param jsTree If true, list items are rendered for jsTree. * @return */ @SuppressWarnings("unchecked") default Object renderReferencesTree(C context, T obj, int depth, Function<Object, Object> itemFilter, boolean jsTree) throws Exception { if (depth == 0) { return null; } List<EReference> treeReferences = new ArrayList<EReference>(); EClass eClass = obj.eClass(); String treeReferencesAnnotation = getRenderAnnotation(context, eClass, RenderAnnotation.TREE_REFERENCES); if (treeReferencesAnnotation == null) { for (EReference ref: eClass.getEAllReferences()) { if (ref.isContainment() && ref.isMany() && context.authorizeRead(obj, ref.getName(), null)) { treeReferences.add(ref); } } } else { for (String refName: treeReferencesAnnotation.split("\\s+")) { if (!CoreUtil.isBlank(refName)) { EReference sf = (EReference) eClass.getEStructuralFeature(refName.trim()); if (sf instanceof EReference && context.authorizeRead(obj, sf.getName(), null)) { treeReferences.add(sf); } } } } HTMLFactory htmlFactory = getHTMLFactory(context); Tag ret = htmlFactory.tag(TagName.ul); for (EReference treeReference: treeReferences) { String treeNodeAnnotation = getRenderAnnotation(context, treeReference, RenderAnnotation.TREE_NODE); boolean isTreeNode = !"false".equals(treeNodeAnnotation); Tag itemContainer = ret; if (isTreeNode) { Tag refNode = htmlFactory.tag(TagName.li); refNode.setData(treeReference); refNode.setData("role", "item"); if (jsTree) { JsTree jt = refNode.jsTree(); jt.icon(getModelElementIcon(context, treeReference)); refNode.content(renderNamedElementLabel(context, treeReference)); } else { refNode.content(renderNamedElementIconAndLabel(context, treeReference)); } itemContainer = htmlFactory.tag(TagName.ul); refNode.content(itemContainer); } if (treeReference.isMany()) { for (EObject ref: (Collection<? extends EObject>) obj.eGet(treeReference)) { itemContainer.content(getRenderer(ref).renderTreeItem(context, ref, depth == -1 ? -1 : depth - 1, itemFilter, jsTree)); } } else { Object ref = obj.eGet(treeReference); if (ref instanceof EObject) { itemContainer.content(getRenderer((EObject) ref).renderTreeItem(context, (EObject) ref, depth == -1 ? -1 : depth - 1, itemFilter, jsTree)); } } } return ret.isEmpty() ? null : ret; } /** * Renders object header. This implementation interpolates ``object.header`` resource string with the following tokens: * * * ``icon`` * * ``label`` * * ``eclass-icon`` * * ``eclass-label`` * * ``documentation-icon`` * * @param context * @param obj * @param classDocModal * @return * @throws Exception */ default Object renderObjectHeader(C context, T obj, Modal classDocModal) throws Exception { Map<String, Object> env = new HashMap<>(); Object icon = renderIcon(context, obj); env.put("icon", icon == null ? "" : icon); Object label = renderLabel(context, obj); env.put("label", label == null ? "" : label); Object eClassIcon = renderModelElementIcon(context, obj.eClass()); env.put("eclass-icon", eClassIcon == null ? "" : eClassIcon); Object eClassLabel = renderNamedElementLabel(context, obj.eClass()); env.put("eclass-label", eClassLabel == null || eClassLabel.equals(label) ? "" : eClassLabel); Tag classDocIcon = renderDocumentationIcon(context, obj.eClass(), classDocModal, true); env.put("documentation-icon", classDocIcon == null ? "" : classDocIcon); return getHTMLFactory(context).interpolate(getResourceString(context, "object.header", false), env); } /** * Renders object edit form with feature documentation modals and error messages if any. Action buttons are not rendered. * @param context * @param obj * @param validationResults * @param featureValidationResults * @param horizontalForm * @return * @throws Exception */ default Form renderEditForm( C context, T obj, List<ValidationResult> validationResults, Map<EStructuralFeature, List<ValidationResult>> featureValidationResults, boolean horizontalForm) throws Exception { HTMLFactory htmlFactory = getHTMLFactory(context); Form editForm = htmlFactory.form(); Map<EStructuralFeature, Modal> featureDocModals = renderEditableFeaturesDocModals(context, obj); for (Modal fdm: featureDocModals.values()) { editForm.content(fdm); } ListGroup errorList = htmlFactory.listGroup(); for (ValidationResult vr: validationResults) { errorList.item(vr.message, vr.status.toStyle()); } if (horizontalForm) { for (Entry<EStructuralFeature, List<ValidationResult>> fe: featureValidationResults.entrySet()) { for (ValidationResult fvr: fe.getValue()) { Object featureNameLabel = renderNamedElementIconAndLabel(context, fe.getKey()); errorList.item(htmlFactory.label(fvr.status.toStyle(), featureNameLabel) + " " + fvr.message, fvr.status.toStyle()); } } } if (!errorList.isEmpty()) { editForm.content(errorList); } renderEditableFeaturesFormGroups(context, obj, editForm, featureDocModals, featureValidationResults, horizontalForm).forEach((fg) -> fg.feedback(!horizontalForm)); return editForm; } /** * Renders an edit form for a single feature, e.g. a reference with checkboxes for selecting multiple values and radios or select for selecting a single value. * @param context * @param obj * @param validationResults * @param featureValidationResults * @param horizontalForm * @return * @throws Exception */ default Form renderFeatureEditForm( C context, T obj, EStructuralFeature feature, List<ValidationResult> featureValidationResults, boolean horizontalForm) throws Exception { HTMLFactory htmlFactory = getHTMLFactory(context); Form selectForm = htmlFactory.form(); Modal featureDocModal = renderDocumentationModal(context, feature); selectForm.content(featureDocModal); ListGroup errorList = htmlFactory.listGroup(); if (horizontalForm && featureValidationResults != null) { for (ValidationResult fvr: featureValidationResults) { errorList.item(fvr.message, fvr.status.toStyle()); } } if (!errorList.isEmpty()) { selectForm.content(errorList); } FormGroup<?> fg = renderFeatureFormGroup(context, obj, feature, selectForm, featureDocModal, featureValidationResults, horizontalForm); if (fg != null) { fg.feedback(!horizontalForm); } return selectForm; } }
package org.osgi.util.measurement; import java.util.*; /** * Represents a value with an error, a unit and a time-stamp. * * <p> * A <tt>Measurement</tt> object is used for maintaining the tuple of value, * error, unit and time-stamp. The value and error are represented as doubles * and the time is measured in milliseconds since midnight, January 1, 1970 UTC. * * <p> * Mathematic methods are provided that correctly calculate taking the error * into account. A runtime error will occur when two measurements are used in an * incompatible way. E.g., when a speed (m/s) is added to a distance (m). The * measurement class will correctly track changes in unit during multiplication * and division, always coercing the result to the most simple form. See * {@link Unit}for more information on the supported units. * * <p> * Errors in the measurement class are absolute errors. Measurement errors * should use the P95 rule. Actual values must fall in the range value +/- error * 95% or more of the time. * * <p> * A <tt>Measurement</tt> object is immutable in order to be easily shared. * * <p> * Note: This class has a natural ordering that is inconsistent with equals. See * {@link #compareTo}. * * @version $Revision$ */ public class Measurement implements Comparable { /* package private so it can be accessed by Unit */ final double value; final double error; final long time; final Unit unit; private transient String name; public Measurement(String encoded) { try { StringTokenizer st = new StringTokenizer(encoded, ":"); value = Double.parseDouble(st.nextToken()); unit = Unit.fromString(st.nextToken()); if (st.hasMoreTokens()) { error = Double.parseDouble(st.nextToken()); } else { error = 0.0d; } time = 0l; } catch (NoSuchElementException e) { throw new IllegalArgumentException("Invalid value"); } } /** * Create a new <tt>Measurement</tt> object. * * @param value The value of the <tt>Measurement</tt>. * @param error The error of the <tt>Measurement</tt>. * @param unit The <tt>Unit</tt> object in which the value is measured. If * this argument is <tt>null</tt>, then the unit will be set to * {@link Unit#unity}. * @param time The time measured in milliseconds since midnight, January 1, * 1970 UTC. */ public Measurement(double value, double error, Unit unit, long time) { this.value = value; this.error = Math.abs(error); this.unit = (unit != null) ? unit : Unit.unity; this.time = time; } /** * Create a new <tt>Measurement</tt> object with a time of zero. * * @param value The value of the <tt>Measurement</tt>. * @param error The error of the <tt>Measurement</tt>. * @param unit The <tt>Unit</tt> object in which the value is measured. If * this argument is <tt>null</tt>, then the unit will be set to * {@link Unit#unity}. */ public Measurement(double value, double error, Unit unit) { this(value, error, unit, 0l); } /** * Create a new <tt>Measurement</tt> object with an error of 0.0 and a * time of zero. * * @param value The value of the <tt>Measurement</tt>. * @param unit The <tt>Unit</tt> in which the value is measured. If this * argument is <tt>null</tt>, then the unit will be set to * {@link Unit#unity}. */ public Measurement(double value, Unit unit) { this(value, 0.0d, unit, 0l); } /** * Create a new <tt>Measurement</tt> object with an error of 0.0, a unit * of {@link Unit#unity}and a time of zero. * * @param value The value of the <tt>Measurement</tt>. */ public Measurement(double value) { this(value, 0.0d, null, 0l); } /** * Returns the value of this <tt>Measurement</tt> object. * * @return The value of this <tt>Measurement</tt> object as a double. */ public final double getValue() { return value; } /** * Returns the error of this <tt>Measurement</tt> object. The error is * always a positive value. * * @return The error of this <tt>Measurement</tt> as a double. */ public final double getError() { return error; } /** * Returns the <tt>Unit</tt> object of this <tt>Measurement</tt> object. * * @return The <tt>Unit</tt> object of this <tt>Measurement</tt> object. * * @see Unit */ public final Unit getUnit() { return unit; } /** * Returns the time at which this <tt>Measurement</tt> object was taken. * The time is measured in milliseconds since midnight, January 1, 1970 UTC, * or zero when not defined. * * @return The time at which this <tt>Measurement</tt> object was taken or * zero. */ public final long getTime() { return time; } /** * Returns a new <tt>Measurement</tt> object that is the product of this * object multiplied by the specified object. * * @param m The <tt>Measurement</tt> object that will be multiplied with * this object. * @return A new <tt>Measurement</tt> that is the product of this object * multiplied by the specified object. The error and unit of the new * object are computed. The time of the new object is set to the * time of this object. * @throws ArithmeticException If the <tt>Unit</tt> objects of this object * and the specified object cannot be multiplied. * @see Unit */ public Measurement mul(Measurement m) { double mvalue = m.value; return new Measurement(value * mvalue, Math.abs(value) * m.error + error * Math.abs(mvalue), unit.mul(m.unit), time); } /** * Returns a new <tt>Measurement</tt> object that is the product of this * object multiplied by the specified value. * * @param d The value that will be multiplied with this object. * @param u The <tt>Unit</tt> of the specified value. * @return A new <tt>Measurement</tt> object that is the product of this * object multiplied by the specified value. The error and unit of * the new object are computed. The time of the new object is set to * the time of this object. * @throws ArithmeticException If the units of this object and the specified * value cannot be multiplied. * @see Unit */ public Measurement mul(double d, Unit u) { return new Measurement(value * d, error * Math.abs(d), unit.mul(u), time); } /** * Returns a new <tt>Measurement</tt> object that is the product of this * object multiplied by the specified value. * * @param d The value that will be multiplied with this object. * @return A new <tt>Measurement</tt> object that is the product of this * object multiplied by the specified value. The error of the new * object is computed. The unit and time of the new object is set to * the unit and time of this object. */ public Measurement mul(double d) { return new Measurement(value * d, error * Math.abs(d), unit, time); } /** * Returns a new <tt>Measurement</tt> object that is the quotient of this * object divided by the specified object. * * @param m The <tt>Measurement</tt> object that will be the divisor of * this object. * @return A new <tt>Measurement</tt> object that is the quotient of this * object divided by the specified object. The error and unit of the * new object are computed. The time of the new object is set to the * time of this object. * @throws ArithmeticException If the <tt>Unit</tt> objects of this object * and the specified object cannot be divided. * @see Unit */ public Measurement div(Measurement m) { double mvalue = m.value; return new Measurement(value / mvalue, (Math.abs(value) * m.error + error * Math.abs(mvalue)) / (mvalue * mvalue), unit.div(m.unit), time); } /** * Returns a new <tt>Measurement</tt> object that is the quotient of this * object divided by the specified value. * * @param d The value that will be the divisor of this object. * @param u The <tt>Unit</tt> object of the specified value. * @return A new <tt>Measurement</tt> that is the quotient of this object * divided by the specified value. The error and unit of the new * object are computed. The time of the new object is set to the * time of this object. * @throws ArithmeticException If the <tt>Unit</tt> objects of this object * and the specified object cannot be divided. * @see Unit */ public Measurement div(double d, Unit u) { return new Measurement(value / d, error / Math.abs(d), unit.div(u), time); } /** * Returns a new <tt>Measurement</tt> object that is the quotient of this * object divided by the specified value. * * @param d The value that will be the divisor of this object. * @return A new <tt>Measurement</tt> object that is the quotient of this * object divided by the specified value. The error of the new * object is computed. The unit and time of the new object is set to * the <tt>Unit</tt> and time of this object. */ public Measurement div(double d) { return new Measurement(value / d, error / Math.abs(d), unit, time); } /** * Returns a new <tt>Measurement</tt> object that is the sum of this * object added to the specified object. * * The error and unit of the new object are computed. The time of the new * object is set to the time of this object. * * @param m The <tt>Measurement</tt> object that will be added with this * object. * @return A new <tt>Measurement</tt> object that is the sum of this and * m. * @see Unit * @throws ArithmeticException If the <tt>Unit</tt> objects of this object * and the specified object cannot be added. */ public Measurement add(Measurement m) { return new Measurement(value + m.value, error + m.error, unit .add(m.unit), time); } /** * Returns a new <tt>Measurement</tt> object that is the sum of this * object added to the specified value. * * @param d The value that will be added with this object. * @param u The <tt>Unit</tt> object of the specified value. * @return A new <tt>Measurement</tt> object that is the sum of this * object added to the specified value. The unit of the new object * is computed. The error and time of the new object is set to the * error and time of this object. * @throws ArithmeticException If the <tt>Unit</tt> objects of this object * and the specified value cannot be added. * @see Unit */ public Measurement add(double d, Unit u) { return new Measurement(value + d, error, unit.add(u), time); } /** * Returns a new <tt>Measurement</tt> object that is the sum of this * object added to the specified value. * * @param d The value that will be added with this object. * @return A new <tt>Measurement</tt> object that is the sum of this * object added to the specified value. The error, unit, and time of * the new object is set to the error, <tt>Unit</tt> and time of * this object. */ public Measurement add(double d) { return new Measurement(value + d, error, unit, time); } /** * Returns a new <tt>Measurement</tt> object that is the subtraction of * the specified object from this object. * * @param m The <tt>Measurement</tt> object that will be subtracted from * this object. * @return A new <tt>Measurement</tt> object that is the subtraction of * the specified object from this object. The error and unit of the * new object are computed. The time of the new object is set to the * time of this object. * @throws ArithmeticException If the <tt>Unit</tt> objects of this object * and the specified object cannot be subtracted. * @see Unit */ public Measurement sub(Measurement m) { return new Measurement(value - m.value, error + m.error, unit .sub(m.unit), time); } /** * Returns a new <tt>Measurement</tt> object that is the subtraction of * the specified value from this object. * * @param d The value that will be subtracted from this object. * @param u The <tt>Unit</tt> object of the specified value. * @return A new <tt>Measurement</tt> object that is the subtraction of * the specified value from this object. The unit of the new object * is computed. The error and time of the new object is set to the * error and time of this object. * @throws ArithmeticException If the <tt>Unit</tt> objects of this object * and the specified object cannot be subtracted. * @see Unit */ public Measurement sub(double d, Unit u) { return new Measurement(value - d, error, unit.sub(u), time); } /** * Returns a new <tt>Measurement</tt> object that is the subtraction of * the specified value from this object. * * @param d The value that will be subtracted from this object. * @return A new <tt>Measurement</tt> object that is the subtraction of * the specified value from this object. The error, unit and time of * the new object is set to the error, <tt>Unit</tt> object and * time of this object. */ public Measurement sub(double d) { return new Measurement(value - d, error, unit, time); } /** * Returns a <tt>String</tt> object representing this <tt>Measurement</tt> * object. * * @return a <tt>String</tt> object representing this <tt>Measurement</tt> * object. */ public String toString() { if (name == null) { StringBuffer sb = new StringBuffer(); sb.append(value); if (error != 0.0d) { sb.append(" +/- "); sb.append(error); } String u = unit.toString(); if (u.length() > 0) { sb.append(" "); sb.append(u); } name = sb.toString(); } return name; } /** * Compares this object with the specified object for order. Returns a * negative integer, zero, or a positive integer if this object is less * than, equal to, or greater than the specified object. * * <p> * Note: This class has a natural ordering that is inconsistent with equals. * For this method, another <tt>Measurement</tt> object is considered * equal if there is some <tt>x</tt> such that * * <pre> * getValue() - getError() &lt;= x &lt;= getValue() + getError() * </pre> * * for both <tt>Measurement</tt> objects being compared. * * @param obj The object to be compared. * @return A negative integer, zero, or a positive integer if this object is * less than, equal to, or greater than the specified object. * * @throws ClassCastException If the specified object is not of type * <tt>Measurement</tt>. * @throws ArithmeticException If the unit of the specified * <tt>Measurement</tt> object is not equal to the <tt>Unit</tt> * object of this object. */ public int compareTo(Object obj) { if (this == obj) { return 0; } Measurement that = (Measurement) obj; if (!unit.equals(that.unit)) { throw new ArithmeticException("Cannot compare " + this + " and " + that); } if (value == that.value) { return 0; } if (value < that.value) { if ((value + error) >= (that.value - that.error)) { return 0; } else { return -1; } } else { if ((value - error) <= (that.value + that.error)) { return 0; } else { return 1; } } } /** * Returns a hash code value for this object. * * @return A hash code value for this object. */ public int hashCode() { long bits = Double.doubleToLongBits(value + error); return ((int) (bits ^ (bits >>> 32))) ^ unit.hashCode(); } /** * Returns whether the specified object is equal to this object. Two * <tt>Measurement</tt> objects are equal if they have same value, error * and <tt>Unit</tt>. * * <p> * Note: This class has a natural ordering that is inconsistent with equals. * See {@link #compareTo}. * * @param obj The object to compare with this object. * @return <tt>true</tt> if this object is equal to the specified object; * <tt>false</tt> otherwise. */ public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Measurement)) { return false; } Measurement that = (Measurement) obj; return (value == that.value) && (error == that.error) && unit.equals(that.unit); } }
package org.opencps.processmgt.portlet; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import javax.portlet.ActionRequest; import javax.portlet.ActionResponse; import javax.portlet.PortletException; import javax.portlet.RenderRequest; import javax.portlet.RenderResponse; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.opencps.accountmgt.NoSuchAccountException; import org.opencps.accountmgt.NoSuchAccountFolderException; import org.opencps.accountmgt.NoSuchAccountOwnOrgIdException; import org.opencps.accountmgt.NoSuchAccountOwnUserIdException; import org.opencps.accountmgt.NoSuchAccountTypeException; import org.opencps.backend.message.SendToEngineMsg; import org.opencps.dossiermgt.DuplicateFileGroupException; import org.opencps.dossiermgt.EmptyFileGroupException; import org.opencps.dossiermgt.NoSuchDossierException; import org.opencps.dossiermgt.NoSuchDossierFileException; import org.opencps.dossiermgt.NoSuchDossierPartException; import org.opencps.dossiermgt.NoSuchDossierTemplateException; import org.opencps.dossiermgt.PermissionDossierException; import org.opencps.dossiermgt.RequiredDossierPartException; import org.opencps.dossiermgt.bean.AccountBean; import org.opencps.dossiermgt.model.Dossier; import org.opencps.dossiermgt.model.DossierFile; import org.opencps.dossiermgt.model.DossierPart; import org.opencps.dossiermgt.model.DossierTemplate; import org.opencps.dossiermgt.model.ServiceConfig; import org.opencps.dossiermgt.search.DossierDisplayTerms; import org.opencps.dossiermgt.search.DossierFileDisplayTerms; import org.opencps.dossiermgt.service.DossierFileLocalServiceUtil; import org.opencps.dossiermgt.service.DossierLocalServiceUtil; import org.opencps.dossiermgt.service.DossierPartLocalServiceUtil; import org.opencps.dossiermgt.service.DossierTemplateLocalServiceUtil; import org.opencps.dossiermgt.service.FileGroupLocalServiceUtil; import org.opencps.dossiermgt.service.ServiceConfigLocalServiceUtil; import org.opencps.dossiermgt.util.DossierMgtUtil; import org.opencps.jasperreport.util.JRReportUtil; import org.opencps.pki.HashAlgorithm; import org.opencps.pki.Helper; import org.opencps.pki.PdfPkcs7Signer; import org.opencps.processmgt.model.ProcessOrder; import org.opencps.processmgt.model.ProcessStep; import org.opencps.processmgt.model.ProcessWorkflow; import org.opencps.processmgt.model.ServiceProcess; import org.opencps.processmgt.search.ProcessOrderDisplayTerms; import org.opencps.processmgt.service.ProcessOrderLocalServiceUtil; import org.opencps.processmgt.service.ProcessStepLocalServiceUtil; import org.opencps.processmgt.service.ProcessWorkflowLocalServiceUtil; import org.opencps.processmgt.service.ServiceProcessLocalServiceUtil; import org.opencps.servicemgt.model.ServiceInfo; import org.opencps.servicemgt.service.ServiceInfoLocalServiceUtil; import org.opencps.usermgt.model.Employee; import org.opencps.util.AccountUtil; import org.opencps.util.DLFileEntryUtil; import org.opencps.util.DLFolderUtil; import org.opencps.util.DateTimeUtil; import org.opencps.util.MessageKeys; import org.opencps.util.PDFUtil; import org.opencps.util.PortletConstants; import org.opencps.util.PortletPropsValues; import org.opencps.util.PortletUtil; import org.opencps.util.SignatureUtil; import org.opencps.util.WebKeys; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.json.JSONFactoryUtil; import com.liferay.portal.kernel.json.JSONObject; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.messaging.Message; import com.liferay.portal.kernel.messaging.MessageBusUtil; import com.liferay.portal.kernel.repository.model.FileEntry; import com.liferay.portal.kernel.servlet.SessionErrors; import com.liferay.portal.kernel.upload.UploadPortletRequest; import com.liferay.portal.kernel.util.Base64; import com.liferay.portal.kernel.util.GetterUtil; import com.liferay.portal.kernel.util.MimeTypesUtil; import com.liferay.portal.kernel.util.ParamUtil; import com.liferay.portal.kernel.util.StringPool; import com.liferay.portal.kernel.util.Validator; import com.liferay.portal.service.ServiceContext; import com.liferay.portal.service.ServiceContextFactory; import com.liferay.portal.theme.ThemeDisplay; import com.liferay.portal.util.PortalUtil; import com.liferay.portlet.documentlibrary.DuplicateFileException; import com.liferay.portlet.documentlibrary.FileSizeException; import com.liferay.portlet.documentlibrary.NoSuchFileEntryException; import com.liferay.portlet.documentlibrary.model.DLFolder; import com.liferay.portlet.documentlibrary.service.DLAppServiceUtil; import com.liferay.util.bridges.mvc.MVCPortlet; /** * @author trungnt */ public class ProcessOrderPortlet extends MVCPortlet { private Log _log = LogFactoryUtil.getLog(ProcessOrderPortlet.class.getName()); /** * @param actionRequest * @param actionResponse * @throws IOException */ public void addAttachmentFile( ActionRequest actionRequest, ActionResponse actionResponse) throws IOException { boolean updated = false; AccountBean accountBean = AccountUtil.getAccountBeanFromAttribute(actionRequest); UploadPortletRequest uploadPortletRequest = PortalUtil.getUploadPortletRequest(actionRequest); Dossier dossier = null; DossierFile dossierFile = null; DossierPart dossierPart = null; long dossierId = ParamUtil.getLong(uploadPortletRequest, DossierDisplayTerms.DOSSIER_ID); long dossierFileId = ParamUtil.getLong(uploadPortletRequest, DossierFileDisplayTerms.DOSSIER_FILE_ID); long dossierPartId = ParamUtil.getLong(uploadPortletRequest, DossierFileDisplayTerms.DOSSIER_PART_ID); long fileGroupId = ParamUtil.getLong(uploadPortletRequest, DossierDisplayTerms.FILE_GROUP_ID); long size = uploadPortletRequest.getSize(DossierFileDisplayTerms.DOSSIER_FILE_UPLOAD); int dossierFileType = ParamUtil.getInteger(uploadPortletRequest, DossierFileDisplayTerms.DOSSIER_FILE_TYPE); int dossierFileOriginal = ParamUtil.getInteger(uploadPortletRequest, DossierFileDisplayTerms.DOSSIER_FILE_ORIGINAL); String displayName = ParamUtil.getString(uploadPortletRequest, DossierFileDisplayTerms.DISPLAY_NAME); String dossierFileNo = ParamUtil.getString(uploadPortletRequest, DossierFileDisplayTerms.DOSSIER_FILE_NO); String dossierFileDate = ParamUtil.getString(uploadPortletRequest, DossierFileDisplayTerms.DOSSIER_FILE_DATE); String sourceFileName = uploadPortletRequest.getFileName(DossierFileDisplayTerms.DOSSIER_FILE_UPLOAD); /* * sourceFileName = sourceFileName * .concat(PortletConstants.TEMP_RANDOM_SUFFIX).concat(StringUtil * .randomString()); */ String redirectURL = ParamUtil.getString(uploadPortletRequest, "redirectURL"); InputStream inputStream = null; Date fileDate = DateTimeUtil.convertStringToDate(dossierFileDate); try { dossier = DossierLocalServiceUtil.getDossier(dossierId); ServiceContext serviceContext = ServiceContextFactory.getInstance(uploadPortletRequest); serviceContext.setAddGroupPermissions(true); serviceContext.setAddGuestPermissions(true); validateAddAttachDossierFile(dossierId, dossierPartId, dossierFileId, displayName, size, sourceFileName, inputStream, accountBean); inputStream = uploadPortletRequest.getFileAsStream(DossierFileDisplayTerms.DOSSIER_FILE_UPLOAD); if (dossierFileId > 0) { dossierFile = DossierFileLocalServiceUtil.getDossierFile(dossierFileId); } dossierPart = DossierPartLocalServiceUtil.getDossierPart(dossierPartId); String contentType = uploadPortletRequest.getContentType(DossierFileDisplayTerms.DOSSIER_FILE_UPLOAD); DLFolder dossierFolder = DLFolderUtil.getDossierFolder(serviceContext.getScopeGroupId(), dossier.getUserId(), dossier.getCounter(), serviceContext); DossierFileLocalServiceUtil.addDossierFile( serviceContext.getUserId(), dossierId, dossierPartId, dossierPart.getTemplateFileNo(), StringPool.BLANK, fileGroupId, 0, accountBean.getOwnerUserId(), accountBean.getOwnerOrganizationId(), displayName, StringPool.BLANK, dossierFile != null ? dossierFile.getFileEntryId() : 0, PortletConstants.DOSSIER_FILE_MARK_UNKNOW, dossierFileType, dossierFileNo, fileDate, dossierFileOriginal, PortletConstants.DOSSIER_FILE_SYNC_STATUS_NOSYNC, dossierFolder.getFolderId(), sourceFileName, contentType, displayName, StringPool.BLANK, StringPool.BLANK, inputStream, size, serviceContext); updated = true; } catch (Exception e) { updated = false; if (e instanceof DuplicateFileException) { SessionErrors.add(actionRequest, DuplicateFileException.class); } else if (e instanceof NoSuchDossierException) { SessionErrors.add(actionRequest, NoSuchDossierException.class); } else if (e instanceof NoSuchDossierPartException) { SessionErrors.add(actionRequest, NoSuchDossierPartException.class); } else if (e instanceof NoSuchAccountException) { SessionErrors.add(actionRequest, NoSuchAccountException.class); } else if (e instanceof NoSuchAccountTypeException) { SessionErrors.add(actionRequest, NoSuchAccountTypeException.class); } else if (e instanceof NoSuchAccountFolderException) { SessionErrors.add(actionRequest, NoSuchAccountFolderException.class); } else if (e instanceof NoSuchAccountOwnUserIdException) { SessionErrors.add(actionRequest, NoSuchAccountOwnUserIdException.class); } else if (e instanceof NoSuchAccountOwnOrgIdException) { SessionErrors.add(actionRequest, NoSuchAccountOwnOrgIdException.class); } else if (e instanceof PermissionDossierException) { SessionErrors.add(actionRequest, PermissionDossierException.class); } else if (e instanceof FileSizeException) { SessionErrors.add(actionRequest, FileSizeException.class); } else { SessionErrors.add(actionRequest, "upload-error"); } _log.error(e); } finally { if (updated) { if (Validator.isNotNull(redirectURL)) { actionResponse.sendRedirect(redirectURL); } } else { actionResponse.setRenderParameter("redirectURL", redirectURL); actionResponse.setRenderParameter("content", "upload-file"); actionResponse.setRenderParameter("jspPage", "/html/portlets/processmgt/processorder/modal_dialog.jsp"); } } } /** * @param actionRequest * @param actionResponse * @throws IOException */ public void addIndividualPartGroup( ActionRequest actionRequest, ActionResponse actionResponse) throws IOException { boolean updated = false; long dossierId = ParamUtil.getLong(actionRequest, DossierDisplayTerms.DOSSIER_ID); long dossierPartId = ParamUtil.getLong(actionRequest, DossierFileDisplayTerms.DOSSIER_PART_ID); String partName = ParamUtil.getString(actionRequest, DossierFileDisplayTerms.PART_NAME); String redirectURL = ParamUtil.getString(actionRequest, "redirectURL"); try { ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest); valiadateFileGroup(dossierId, partName); FileGroupLocalServiceUtil.addFileGroup(serviceContext.getUserId(), dossierId, dossierPartId, partName, PortletConstants.DOSSIER_FILE_SYNC_STATUS_NOSYNC, serviceContext); } catch (Exception e) { updated = false; if (e instanceof NoSuchDossierException) { SessionErrors.add(actionRequest, NoSuchDossierException.class); } else if (e instanceof EmptyFileGroupException) { SessionErrors.add(actionRequest, EmptyFileGroupException.class); } else if (e instanceof DuplicateFileGroupException) { SessionErrors.add(actionRequest, DuplicateFileGroupException.class); } else { SessionErrors.add(actionRequest, MessageKeys.DOSSIER_SYSTEM_EXCEPTION_OCCURRED); } _log.error(e); } finally { if (updated) { if (Validator.isNotNull(redirectURL)) { actionResponse.sendRedirect(redirectURL); } } else { actionResponse.setRenderParameter("redirectURL", redirectURL); actionResponse.setRenderParameter("content", "individual"); actionResponse.setRenderParameter("jspPage", "/html/portlets/processmgt/processorder/modal_dialog.jsp"); } } } /** * @param actionRequest * @param actionResponse * @throws IOException */ public void assignToUser( ActionRequest actionRequest, ActionResponse actionResponse) throws IOException { Dossier dossier = null; long assignToUserId = ParamUtil.getLong(actionRequest, ProcessOrderDisplayTerms.ASSIGN_TO_USER_ID); String paymentValue = ParamUtil.getString(actionRequest, ProcessOrderDisplayTerms.PAYMENTVALUE); String estimateDatetime = ParamUtil.getString(actionRequest, ProcessOrderDisplayTerms.ESTIMATE_DATETIME); String redirectURL = ParamUtil.getString(actionRequest, "redirectURL"); String backURL = ParamUtil.getString(actionRequest, "backURL"); long dossierId = ParamUtil.getLong(actionRequest, ProcessOrderDisplayTerms.DOSSIER_ID); long groupId = ParamUtil.getLong(actionRequest, ProcessOrderDisplayTerms.GROUP_ID); long companyId = ParamUtil.getLong(actionRequest, ProcessOrderDisplayTerms.COMPANY_ID); long fileGroupId = ParamUtil.getLong(actionRequest, ProcessOrderDisplayTerms.FILE_GROUP_ID); long processOrderId = ParamUtil.getLong(actionRequest, ProcessOrderDisplayTerms.PROCESS_ORDER_ID); long actionUserId = ParamUtil.getLong(actionRequest, ProcessOrderDisplayTerms.ACTION_USER_ID); long processWorkflowId = ParamUtil.getLong(actionRequest, ProcessOrderDisplayTerms.PROCESS_WORKFLOW_ID); /* * long serviceProcessId = ParamUtil.getLong(actionRequest, * ProcessOrderDisplayTerms.SERVICE_PROCESS_ID); long processStepId = * ParamUtil.getLong(actionRequest, * ProcessOrderDisplayTerms.PROCESS_STEP_ID); */ String actionNote = ParamUtil.getString(actionRequest, ProcessOrderDisplayTerms.ACTION_NOTE); String event = ParamUtil.getString(actionRequest, ProcessOrderDisplayTerms.EVENT); boolean signature = ParamUtil.getBoolean(actionRequest, ProcessOrderDisplayTerms.SIGNATURE); boolean sending = false; Date deadline = null; if (Validator.isNotNull(estimateDatetime)) { deadline = DateTimeUtil.convertStringToDate(estimateDatetime); } try { dossier = DossierLocalServiceUtil.getDossier(dossierId); validateAssignTask(dossier.getDossierId()); Message message = new Message(); SendToEngineMsg sendToEngineMsg = new SendToEngineMsg(); // sendToEngineMsg.setAction(WebKeys.ACTION); sendToEngineMsg.setActionNote(actionNote); sendToEngineMsg.setEvent(event); sendToEngineMsg.setGroupId(groupId); sendToEngineMsg.setCompanyId(companyId); sendToEngineMsg.setAssignToUserId(assignToUserId); sendToEngineMsg.setActionUserId(actionUserId); sendToEngineMsg.setDossierId(dossierId); sendToEngineMsg.setEstimateDatetime(deadline); sendToEngineMsg.setFileGroupId(fileGroupId); sendToEngineMsg.setPaymentValue(GetterUtil.getDouble(paymentValue)); sendToEngineMsg.setProcessOrderId(processOrderId); sendToEngineMsg.setProcessWorkflowId(processWorkflowId); sendToEngineMsg.setReceptionNo(Validator.isNotNull(dossier.getReceptionNo()) ? dossier.getReceptionNo() : StringPool.BLANK); sendToEngineMsg.setSignature(signature ? 1 : 0); message.put("msgToEngine", sendToEngineMsg); MessageBusUtil.sendMessage("opencps/backoffice/engine/destination", message); sending = true; } catch (Exception e) { sending = false; if (e instanceof NoSuchDossierException || e instanceof NoSuchDossierTemplateException || e instanceof RequiredDossierPartException) { SessionErrors.add(actionRequest, e.getClass()); } else { SessionErrors.add(actionRequest, MessageKeys.DOSSIER_SYSTEM_EXCEPTION_OCCURRED); } _log.error(e); } finally { if (sending) { actionResponse.setRenderParameter("jspPage", "/html/portlets/processmgt/processorder/assign_to_user.jsp"); actionResponse.setRenderParameter("backURL", backURL); } else { if (Validator.isNotNull(redirectURL)) { actionResponse.sendRedirect(redirectURL); } } } } /** * @param actionRequest * @param actionResponse * @throws IOException */ public void cloneDossierFile( ActionRequest actionRequest, ActionResponse actionResponse) throws IOException { AccountBean accountBean = AccountUtil.getAccountBeanFromAttribute(actionRequest); Dossier dossier = null; DossierFile dossierFile = null; DossierPart dossierPart = null; boolean updated = false; long cloneDossierFileId = ParamUtil.getLong(actionRequest, "cloneDossierFileId"); long dossierId = ParamUtil.getLong(actionRequest, DossierDisplayTerms.DOSSIER_ID); long dossierPartId = ParamUtil.getLong(actionRequest, DossierFileDisplayTerms.DOSSIER_PART_ID); long groupDossierPartId = ParamUtil.getLong(actionRequest, "groupDossierPartId"); long fileGroupId = ParamUtil.getLong(actionRequest, DossierDisplayTerms.FILE_GROUP_ID); String groupName = ParamUtil.getString(actionRequest, DossierFileDisplayTerms.GROUP_NAME); String redirectURL = ParamUtil.getString(actionRequest, "redirectURL"); try { validateCloneDossierFile(dossierId, dossierPartId, cloneDossierFileId, accountBean); dossierFile = DossierFileLocalServiceUtil.getDossierFile(cloneDossierFileId); long fileEntryId = dossierFile.getFileEntryId(); FileEntry fileEntry = DLAppServiceUtil.getFileEntry(fileEntryId); ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest); serviceContext.setAddGroupPermissions(true); serviceContext.setAddGuestPermissions(true); dossier = DossierLocalServiceUtil.getDossier(dossierId); dossierPart = DossierPartLocalServiceUtil.getDossierPart(dossierPartId); DLFolder accountFolder = accountBean.getAccountFolder(); DLFolder dossierFolder = DLFolderUtil.addFolder(serviceContext.getUserId(), serviceContext.getScopeGroupId(), serviceContext.getScopeGroupId(), false, accountFolder.getFolderId(), String.valueOf(dossier.getCounter()), StringPool.BLANK, false, serviceContext); DossierFileLocalServiceUtil.addDossierFile( serviceContext.getUserId(), dossierId, dossierPartId, dossierPart.getTemplateFileNo(), groupName, fileGroupId, groupDossierPartId, accountBean.getOwnerUserId(), accountBean.getOwnerOrganizationId(), dossierFile.getDisplayName(), StringPool.BLANK, dossierFile != null ? dossierFile.getFileEntryId() : 0, PortletConstants.DOSSIER_FILE_MARK_UNKNOW, dossierFile.getDossierFileType(), dossierFile.getDossierFileNo(), dossierFile.getDossierFileDate(), dossierFile.getOriginal(), PortletConstants.DOSSIER_FILE_SYNC_STATUS_NOSYNC, dossierFolder.getFolderId(), fileEntry.getTitle() + StringPool.PERIOD + fileEntry.getExtension(), fileEntry.getMimeType(), fileEntry.getTitle(), StringPool.BLANK, StringPool.BLANK, fileEntry.getContentStream(), fileEntry.getSize(), serviceContext); updated = true; } catch (Exception e) { updated = false; if (e instanceof DuplicateFileException) { SessionErrors.add(actionRequest, DuplicateFileException.class); } else if (e instanceof NoSuchDossierException) { SessionErrors.add(actionRequest, NoSuchDossierException.class); } else if (e instanceof NoSuchDossierPartException) { SessionErrors.add(actionRequest, NoSuchDossierPartException.class); } else if (e instanceof NoSuchAccountException) { SessionErrors.add(actionRequest, NoSuchAccountException.class); } else if (e instanceof NoSuchAccountTypeException) { SessionErrors.add(actionRequest, NoSuchAccountTypeException.class); } else if (e instanceof NoSuchAccountFolderException) { SessionErrors.add(actionRequest, NoSuchAccountFolderException.class); } else if (e instanceof NoSuchAccountOwnUserIdException) { SessionErrors.add(actionRequest, NoSuchAccountOwnUserIdException.class); } else if (e instanceof NoSuchAccountOwnOrgIdException) { SessionErrors.add(actionRequest, NoSuchAccountOwnOrgIdException.class); } else if (e instanceof PermissionDossierException) { SessionErrors.add(actionRequest, PermissionDossierException.class); } else if (e instanceof NoSuchFileEntryException) { SessionErrors.add(actionRequest, NoSuchFileEntryException.class); } else { SessionErrors.add(actionRequest, "upload-error"); } _log.error(e); } finally { if (updated) { if (Validator.isNotNull(redirectURL)) { actionResponse.sendRedirect(redirectURL); } } else { actionResponse.setRenderParameter("redirectURL", redirectURL); actionResponse.setRenderParameter("content", "upload-file"); actionResponse.setRenderParameter("tab1", "select-file"); actionResponse.setRenderParameter("jspPage", "/html/portlets/processmgt/processorder/modal_dialog.jsp"); } } } /** * @param accountBean * @param dossierId * @param dossierFileId * @param dossierPartId * @param sourceFileName * @param is * @param size * @param serviceContext * @return */ protected DossierFile addSignatureFile( AccountBean accountBean, long dossierId, long dossierFileId, long dossierPartId, String sourceFileName, InputStream is, long size, ServiceContext serviceContext) { DossierFile dossierFile = null; DossierFile signDossierFile = null; try { dossierFile = DossierFileLocalServiceUtil.getDossierFile(dossierFileId); FileEntry fileEntry = DLAppServiceUtil.getFileEntry(dossierFile.getFileEntryId()); signDossierFile = DossierFileLocalServiceUtil.addSignDossierFile(dossierFileId, true, fileEntry.getFolderId(), sourceFileName, fileEntry.getMimeType(), fileEntry.getTitle() + "signed", fileEntry.getDescription(), StringPool.BLANK, is, size, serviceContext); } catch (Exception e) { _log.error(e); } return signDossierFile; } /** * @param actionRequest * @param actionResponse * @throws IOException */ public void createReport( ActionRequest actionRequest, ActionResponse actionResponse) throws IOException { ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY); AccountBean accountBean = AccountUtil.getAccountBeanFromAttribute(actionRequest); long dossierFileId = ParamUtil.getLong(actionRequest, DossierFileDisplayTerms.DOSSIER_FILE_ID); String sourceFileName = StringPool.BLANK; InputStream inputStream = null; File file = null; JSONObject responseJSON = JSONFactoryUtil.createJSONObject(); String fileExportDir = StringPool.BLANK; try { validateCreateDynamicForm(dossierFileId, accountBean); ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest); serviceContext.setAddGroupPermissions(true); serviceContext.setAddGuestPermissions(true); // Get dossier file DossierFile dossierFile = DossierFileLocalServiceUtil.getDossierFile(dossierFileId); // Get dossier part DossierPart dossierPart = DossierPartLocalServiceUtil.getDossierPart(dossierFile.getDossierPartId()); Dossier dossier = DossierLocalServiceUtil.getDossier(dossierFile.getDossierId()); // Get account folder DLFolder accountForlder = accountBean.getAccountFolder(); // Get dossier folder DLFolder dosserFolder = DLFolderUtil.addFolder(themeDisplay.getUserId(), themeDisplay.getScopeGroupId(), themeDisplay.getScopeGroupId(), false, accountForlder.getFolderId(), String.valueOf(dossier.getCounter()), StringPool.BLANK, false, serviceContext); String formData = dossierFile.getFormData(); String jrxmlTemplate = dossierPart.getFormReport(); // Validate json string JSONFactoryUtil.createJSONObject(formData); String outputDestination = PortletPropsValues.OPENCPS_FILE_SYSTEM_TEMP_DIR; String fileName = System.currentTimeMillis() + StringPool.DASH + dossierFileId + StringPool.DASH + dossierPart.getDossierpartId() + ".pdf"; fileExportDir = exportToPDFFile(jrxmlTemplate, formData, null, outputDestination, fileName); if (Validator.isNotNull(fileExportDir)) { file = new File(fileExportDir); inputStream = new FileInputStream(file); if (inputStream != null) { sourceFileName = fileExportDir.substring( fileExportDir.lastIndexOf(StringPool.SLASH) + 1, fileExportDir.length()); String mimeType = MimeTypesUtil.getContentType(file); // Add new version if (dossierFile.getFileEntryId() > 0) { DossierFileLocalServiceUtil.addDossierFile( dossierFile.getDossierFileId(), dosserFolder.getFolderId(), sourceFileName, mimeType, dossierFile.getDisplayName(), StringPool.BLANK, StringPool.BLANK, inputStream, file.length(), serviceContext); } else { // Update version 1 DossierFileLocalServiceUtil.updateDossierFile( dossierFileId, dosserFolder.getFolderId(), sourceFileName, mimeType, dossierFile.getDisplayName(), StringPool.BLANK, StringPool.BLANK, inputStream, file.length(), serviceContext); } } } } catch (Exception e) { if (e instanceof NoSuchDossierFileException) { SessionErrors.add(actionRequest, NoSuchDossierFileException.class); } else if (e instanceof NoSuchAccountException) { SessionErrors.add(actionRequest, NoSuchAccountException.class); } else if (e instanceof NoSuchAccountTypeException) { SessionErrors.add(actionRequest, NoSuchAccountTypeException.class); } else if (e instanceof NoSuchAccountFolderException) { SessionErrors.add(actionRequest, NoSuchAccountFolderException.class); } else if (e instanceof NoSuchAccountOwnUserIdException) { SessionErrors.add(actionRequest, NoSuchAccountOwnUserIdException.class); } else if (e instanceof NoSuchAccountOwnOrgIdException) { SessionErrors.add(actionRequest, NoSuchAccountOwnOrgIdException.class); } else if (e instanceof PermissionDossierException) { SessionErrors.add(actionRequest, PermissionDossierException.class); } else if (e instanceof DuplicateFileException) { SessionErrors.add(actionRequest, DuplicateFileException.class); } else { SessionErrors.add(actionRequest, PortalException.class); } _log.error(e); } finally { responseJSON.put("fileExportDir", fileExportDir); PortletUtil.writeJSON(actionRequest, actionResponse, responseJSON); if (inputStream != null) { inputStream.close(); } if (file.exists()) { file.delete(); } } } public void deleteAttachmentFile( ActionRequest actionRequest, ActionResponse actionResponse) throws IOException { long dossierFileId = ParamUtil.getLong(actionRequest, DossierFileDisplayTerms.DOSSIER_FILE_ID); DossierFile dossierFile = null; JSONObject jsonObject = null; try { if (dossierFileId > 0) { jsonObject = JSONFactoryUtil.createJSONObject(); dossierFile = DossierFileLocalServiceUtil.getDossierFile(dossierFileId); long fileEntryId = dossierFile.getFileEntryId(); DossierFileLocalServiceUtil.deleteDossierFile(dossierFileId, fileEntryId); jsonObject.put("deleted", Boolean.TRUE); } } catch (Exception e) { jsonObject.put("deleted", Boolean.FALSE); _log.error(e); } finally { PortletUtil.writeJSON(actionRequest, actionResponse, jsonObject); } } /** * @param actionRequest * @param actionResponse */ public void hashMultipleFile( ActionRequest actionRequest, ActionResponse actionResponse) { long[] dossierFileIds = ParamUtil.getLongValues(actionRequest, "dossierFileIds"); if (dossierFileIds != null && dossierFileIds.length > 0) { try { for (int i = 0; i < dossierFileIds.length; i++) { DossierFile dossierFile = DossierFileLocalServiceUtil.getDossierFile(dossierFileIds[i]); String tempFilePath = PDFUtil.saveAsPdf( PortletUtil.getTempFolderPath(actionRequest), dossierFile.getFileEntryId()); System.out.println(tempFilePath); } } catch (Exception e) { // TODO: handle exception } } } /** * @param actionRequest * @param actionResponse * @throws IOException */ public void hashSingleFile( ActionRequest actionRequest, ActionResponse actionResponse) throws IOException { JSONObject data = null; long dossierFileId = ParamUtil.getLong(actionRequest, "dossierFileId"); try { DossierFile dossierFile = DossierFileLocalServiceUtil.getDossierFile(dossierFileId); data = computerHash(actionRequest, dossierFile); } catch (Exception e) { _log.error(e); } finally { PortletUtil.writeJSON(actionRequest, actionResponse, data); } } /** * @param actionRequest * @param actionResponse */ public void signature( ActionRequest actionRequest, ActionResponse actionResponse) { AccountBean accountBean = AccountUtil.getAccountBean(actionRequest); String signature = ParamUtil.getString(actionRequest, "signature"); /* * String certificate = ParamUtil .getString(actionRequest, * "certificate"); */ String jsonResource = ParamUtil.getString(actionRequest, "resources"); File inputFile = null; File hashFile = null; File signFile = null; String inputFilePath = StringPool.BLANK; String outputFilePath = StringPool.BLANK; String hashFileTempPath = StringPool.BLANK; String certPath = StringPool.BLANK; String imagePath = StringPool.BLANK; String signatureFieldName = StringPool.BLANK; try { JSONObject resources = JSONFactoryUtil.createJSONObject(jsonResource); ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest); serviceContext.setAddGroupPermissions(true); serviceContext.setAddGuestPermissions(true); inputFilePath = resources.getString("inputFilePath"); outputFilePath = resources.getString("outputFilePath"); hashFileTempPath = resources.getString("hashFileTempPath"); certPath = resources.getString("certPath"); imagePath = resources.getString("imagePath"); signatureFieldName = resources.getString("signatureFieldName"); long dossierFileId = resources.getLong("dossierFileId"); long dossierId = resources.getLong("dossierFileId"); long dossierPartId = resources.getLong("dossierPartId"); PdfPkcs7Signer pdfSigner = SignatureUtil.getPdfPkcs7Signer(inputFilePath, certPath, hashFileTempPath, outputFilePath, false, imagePath); pdfSigner.setHashAlgorithm(HashAlgorithm.SHA1); pdfSigner.setSignatureFieldName(signatureFieldName); _log.info("********************Signature******************** " + signature); pdfSigner.sign(Base64.decode(signature)); signFile = new File(outputFilePath); inputFile = new File(inputFilePath); hashFile = new File(hashFileTempPath); InputStream is = new FileInputStream(signFile); addSignatureFile(accountBean, dossierId, dossierFileId, dossierPartId, signFile.getName(), is, signFile.length(), serviceContext); if (is != null) { is.close(); } } catch (Exception e) { _log.error(e); } finally { if (signFile != null && signFile.exists()) { signFile.delete(); } if (inputFile != null && inputFile.exists()) { inputFile.delete(); } if (hashFile != null && hashFile.exists()) { hashFile.delete(); } } } /** * @param actionRequest * @param dossierFile * @return */ protected JSONObject computerHash( ActionRequest actionRequest, DossierFile dossierFile) { JSONObject data = JSONFactoryUtil.createJSONObject(); JSONObject resources = JSONFactoryUtil.createJSONObject(); AccountBean accountBean = AccountUtil.getAccountBean(actionRequest); String tempFolderPath = PortletUtil.getTempFolderPath(actionRequest); String imageFolderPath = PortletUtil.getResourceFolderPath(actionRequest); String certFolderPath = PortletUtil.getResourceFolderPath(actionRequest); String employeeEmail = ((Employee) accountBean.getAccountInstance()).getEmail(); boolean isVisible = false; String inputFilePath = StringPool.BLANK; String outputFilePath = StringPool.BLANK; String hashFileTempPath = StringPool.BLANK; try { outputFilePath = tempFolderPath + "signed" + StringPool.DASH + dossierFile.getDisplayName() + StringPool.DASH + System.currentTimeMillis() + ".pdf"; hashFileTempPath = tempFolderPath + "hash" + StringPool.DASH + dossierFile.getDisplayName() + StringPool.DASH + System.currentTimeMillis() + ".pdf"; String certPath = certFolderPath + "/" + employeeEmail + ".cer"; String imagePath = imageFolderPath + "/" + employeeEmail + ".png"; inputFilePath = PDFUtil.saveAsPdf(tempFolderPath, dossierFile.getFileEntryId()); PdfPkcs7Signer pdfSigner = SignatureUtil.getPdfPkcs7Signer(inputFilePath, certPath, hashFileTempPath, outputFilePath, isVisible, imagePath); System.out.println("inputFilePath: " + inputFilePath); System.out.println("hashFileTempPath: " + hashFileTempPath); System.out.println("outputFilePath: " + outputFilePath); System.out.println("imagePath: " + imagePath); pdfSigner.setHashAlgorithm(HashAlgorithm.SHA1); byte[] hash = pdfSigner.computeHash(0, 0, 144, 80); String hashHex = Helper.binToHex(hash); data.put("hashHex", hashHex); resources.put("inputFilePath", inputFilePath); resources.put("dossierFileId", dossierFile.getDossierFileId()); resources.put("dossierId", dossierFile.getDossierId()); resources.put("dossierPartId", dossierFile.getDossierPartId()); resources.put("outputFilePath", outputFilePath); resources.put("hashFileTempPath", hashFileTempPath); resources.put("certPath", certPath); resources.put("imagePath", imagePath); resources.put("signatureFieldName", pdfSigner.getSignatureFieldName()); data.put("resources", resources); } catch (Exception e) { _log.error(e); } return data; } /** * @param jrxmlTemplate * @param formData * @param map * @param outputDestination * @param fileName * @return */ protected String exportToPDFFile( String jrxmlTemplate, String formData, Map<String, Object> map, String outputDestination, String fileName) { return JRReportUtil.createReportPDFfFile(jrxmlTemplate, formData, map, outputDestination, fileName); } /** * @param actionRequest * @param actionResponse */ public void previewAttachmentFile( ActionRequest actionRequest, ActionResponse actionResponse) { long dossierFileId = ParamUtil.getLong(actionRequest, DossierFileDisplayTerms.DOSSIER_FILE_ID); ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY); String url = DLFileEntryUtil.getDossierFileAttachmentURL(dossierFileId, themeDisplay); JSONObject jsonObject = JSONFactoryUtil.createJSONObject(); jsonObject.put("url", url); try { PortletUtil.writeJSON(actionRequest, actionResponse, jsonObject); } catch (IOException e) { _log.error(e); } } /** * @param actionRequest * @param actionResponse * @throws IOException */ public void previewDynamicForm( ActionRequest actionRequest, ActionResponse actionResponse) throws IOException { long dossierFileId = ParamUtil.getLong(actionRequest, DossierFileDisplayTerms.DOSSIER_FILE_ID); String redirectURL = ParamUtil.getString(actionRequest, "redirectURL"); HttpServletResponse response = PortalUtil.getHttpServletResponse(actionResponse); response.setContentType("text/html"); PrintWriter writer = null; try { writer = response.getWriter(); // Get dossier file DossierFile dossierFile = DossierFileLocalServiceUtil.getDossierFile(dossierFileId); // Get dossier part DossierPart dossierPart = DossierPartLocalServiceUtil.getDossierPart(dossierFile.getDossierPartId()); String formData = dossierFile.getFormData(); String jrxmlTemplate = dossierPart.getFormReport(); // Validate json string JSONFactoryUtil.createJSONObject(formData); JRReportUtil.renderReportHTMLStream(response, writer, jrxmlTemplate, formData, null); } catch (Exception e) { _log.error(e); } finally { if (Validator.isNotNull(redirectURL)) { response.sendRedirect(redirectURL); } } } /** * @param actionRequest * @param actionResponse * @throws IOException */ public void removeAttachmentFile( ActionRequest actionRequest, ActionResponse actionResponse) throws IOException { long dossierFileId = ParamUtil.getLong(actionRequest, DossierFileDisplayTerms.DOSSIER_FILE_ID); JSONObject jsonObject = null; try { DossierFile dossierFile = DossierFileLocalServiceUtil.getDossierFile(dossierFileId); DossierPart dossierPart = DossierPartLocalServiceUtil.getDossierPart(dossierFile.getDossierPartId()); jsonObject = JSONFactoryUtil.createJSONObject(); if (dossierFileId > 0 && dossierPart.getPartType() != PortletConstants.DOSSIER_PART_TYPE_OTHER) { DossierFileLocalServiceUtil.removeDossierFile(dossierFileId); } else { DossierFileLocalServiceUtil.deleteDossierFile(dossierFileId, dossierFile.getFileEntryId()); } jsonObject.put("deleted", Boolean.TRUE); } catch (Exception e) { jsonObject.put("deleted", Boolean.FALSE); _log.error(e); } finally { PortletUtil.writeJSON(actionRequest, actionResponse, jsonObject); } } @Override public void render( RenderRequest renderRequest, RenderResponse renderResponse) throws PortletException, IOException { long processOrderId = ParamUtil.getLong(renderRequest, ProcessOrderDisplayTerms.PROCESS_ORDER_ID); long dossierFileId = ParamUtil.getLong(renderRequest, DossierFileDisplayTerms.DOSSIER_FILE_ID); long dossierPartId = ParamUtil.getLong(renderRequest, DossierFileDisplayTerms.DOSSIER_PART_ID); if (processOrderId > 0) { try { ServiceContext serviceContext = ServiceContextFactory.getInstance(renderRequest); ProcessOrder processOrder = ProcessOrderLocalServiceUtil.getProcessOrder(processOrderId); ProcessStep processStep = ProcessStepLocalServiceUtil.getProcessStep(processOrder.getProcessStepId()); Dossier dossier = DossierLocalServiceUtil.getDossier(processOrder.getDossierId()); AccountBean accountBean = AccountUtil.getAccountBean(dossier.getUserId(), serviceContext.getScopeGroupId(), serviceContext); ServiceProcess serviceProcess = ServiceProcessLocalServiceUtil.getServiceProcess(processOrder.getServiceProcessId()); ServiceInfo serviceInfo = ServiceInfoLocalServiceUtil.getServiceInfo(processOrder.getServiceInfoId()); ServiceConfig serviceConfig = ServiceConfigLocalServiceUtil.getServiceConfig(dossier.getServiceConfigId()); DossierTemplate dossierTemplate = DossierTemplateLocalServiceUtil.getDossierTemplate(dossier.getDossierTemplateId()); ProcessWorkflow processWorkflow = ProcessWorkflowLocalServiceUtil.getProcessWorkflow(processOrder.getProcessWorkflowId()); renderRequest.setAttribute(WebKeys.PROCESS_ORDER_ENTRY, processOrder); renderRequest.setAttribute(WebKeys.PROCESS_STEP_ENTRY, processStep); renderRequest.setAttribute(WebKeys.DOSSIER_ENTRY, dossier); renderRequest.setAttribute(WebKeys.SERVICE_PROCESS_ENTRY, serviceProcess); renderRequest.setAttribute(WebKeys.SERVICE_INFO_ENTRY, serviceInfo); renderRequest.setAttribute(WebKeys.SERVICE_CONFIG_ENTRY, serviceConfig); renderRequest.setAttribute(WebKeys.DOSSIER_TEMPLATE_ENTRY, dossierTemplate); renderRequest.setAttribute(WebKeys.PROCESS_WORKFLOW_ENTRY, processWorkflow); HttpServletRequest request = PortalUtil.getHttpServletRequest(renderRequest); ServletContext servletContext = request.getServletContext(); servletContext.setAttribute(WebKeys.ACCOUNT_BEAN, accountBean); if (dossierFileId > 0) { DossierFile dossierFile = DossierFileLocalServiceUtil.getDossierFile(dossierFileId); renderRequest.setAttribute(WebKeys.DOSSIER_FILE_ENTRY, dossierFile); } if (dossierPartId > 0) { DossierPart dossierPart = DossierPartLocalServiceUtil.getDossierPart(dossierPartId); renderRequest.setAttribute(WebKeys.DOSSIER_PART_ENTRY, dossierPart); } } catch (Exception e) { _log.error(e.getCause()); } } super.render(renderRequest, renderResponse); } /** * @param actionRequest * @param actionResponse * @throws IOException */ public void updateDynamicFormData( ActionRequest actionRequest, ActionResponse actionResponse) throws IOException { AccountBean accountBean = AccountUtil.getAccountBeanFromAttribute(actionRequest); DossierFile dossierFile = null; long dossierId = ParamUtil.getLong(actionRequest, DossierDisplayTerms.DOSSIER_ID); long dossierPartId = ParamUtil.getLong(actionRequest, DossierFileDisplayTerms.DOSSIER_PART_ID); long dossierFileId = ParamUtil.getLong(actionRequest, DossierFileDisplayTerms.DOSSIER_FILE_ID); long fileGroupId = ParamUtil.getLong(actionRequest, DossierDisplayTerms.FILE_GROUP_ID); long groupDossierPartId = ParamUtil.getLong(actionRequest, "groupDossierPartId"); long fileEntryId = 0; // Default value int dossierFileMark = PortletConstants.DOSSIER_FILE_MARK_UNKNOW; int dossierFileType = ParamUtil.getInteger(actionRequest, DossierFileDisplayTerms.DOSSIER_FILE_TYPE); int syncStatus = PortletConstants.DOSSIER_FILE_SYNC_STATUS_NOSYNC; int original = PortletConstants.DOSSIER_FILE_ORIGINAL; String formData = ParamUtil.getString(actionRequest, DossierFileDisplayTerms.FORM_DATA); // Default value String dossierFileNo = StringPool.BLANK; String templateFileNo = StringPool.BLANK; String displayName = StringPool.BLANK; String groupName = ParamUtil.getString(actionRequest, DossierFileDisplayTerms.GROUP_NAME); Date dossierFileDate = null; try { validateDynamicFormData(dossierId, dossierPartId, accountBean); ServiceContext serviceContext = ServiceContextFactory.getInstance(actionRequest); DossierPart dossierPart = DossierPartLocalServiceUtil.getDossierPart(dossierPartId); if (Validator.isNotNull(dossierPart.getTemplateFileNo())) { templateFileNo = dossierPart.getTemplateFileNo(); } if (Validator.isNotNull(dossierPart.getPartName())) { displayName = dossierPart.getPartName(); } if (dossierFileId == 0) { dossierFile = DossierFileLocalServiceUtil.addDossierFile( serviceContext.getUserId(), dossierId, dossierPartId, templateFileNo, groupName, fileGroupId, groupDossierPartId, accountBean.getOwnerUserId(), accountBean.getOwnerOrganizationId(), displayName, formData, fileEntryId, dossierFileMark, dossierFileType, dossierFileNo, dossierFileDate, original, syncStatus, serviceContext); } else { dossierFile = DossierFileLocalServiceUtil.getDossierFile(dossierFileId); dossierFileMark = dossierFile.getDossierFileMark(); dossierFileType = dossierFile.getDossierFileType(); syncStatus = dossierFile.getSyncStatus(); original = dossierFile.getOriginal(); dossierFileNo = Validator.isNotNull(dossierFile.getDossierFileNo()) ? dossierFile.getDossierFileNo() : StringPool.BLANK; templateFileNo = Validator.isNotNull(dossierFile.getTemplateFileNo()) ? dossierFile.getTemplateFileNo() : StringPool.BLANK; displayName = Validator.isNotNull(dossierFile.getDisplayName()) ? dossierFile.getDisplayName() : StringPool.BLANK; dossierFile = DossierFileLocalServiceUtil.updateDossierFile( dossierFileId, serviceContext.getUserId(), dossierId, dossierPartId, templateFileNo, fileGroupId, accountBean.getOwnerUserId(), accountBean.getOwnerOrganizationId(), displayName, formData, fileEntryId, dossierFileMark, dossierFileType, dossierFileNo, dossierFileDate, original, syncStatus, serviceContext); } } catch (Exception e) { if (e instanceof NoSuchDossierException) { SessionErrors.add(actionRequest, NoSuchDossierException.class); } else if (e instanceof NoSuchDossierPartException) { SessionErrors.add(actionRequest, NoSuchDossierPartException.class); } else if (e instanceof NoSuchAccountException) { SessionErrors.add(actionRequest, NoSuchAccountException.class); } else if (e instanceof NoSuchAccountTypeException) { SessionErrors.add(actionRequest, NoSuchAccountTypeException.class); } else if (e instanceof NoSuchAccountFolderException) { SessionErrors.add(actionRequest, NoSuchAccountFolderException.class); } else if (e instanceof NoSuchAccountOwnUserIdException) { SessionErrors.add(actionRequest, NoSuchAccountOwnUserIdException.class); } else if (e instanceof NoSuchAccountOwnOrgIdException) { SessionErrors.add(actionRequest, NoSuchAccountOwnOrgIdException.class); } else if (e instanceof PermissionDossierException) { SessionErrors.add(actionRequest, PermissionDossierException.class); } else { SessionErrors.add(actionRequest, PortalException.class); } _log.error(e); } finally { actionResponse.setRenderParameter("primaryKey", String.valueOf(dossierFile != null ? dossierFile.getDossierFileId() : 0)); actionResponse.setRenderParameter("content", "declaration-online"); actionResponse.setRenderParameter("jspPage", "/html/portlets/processmgt/processorder/modal_dialog.jsp"); } } /** * @param dossierId * @param partName * @throws NoSuchDossierException * @throws EmptyFileGroupException * @throws DuplicateFileGroupException */ private void valiadateFileGroup(long dossierId, String partName) throws NoSuchDossierException, EmptyFileGroupException, DuplicateFileGroupException { if (dossierId <= 0) { throw new NoSuchDossierException(); } else if (Validator.isNull(partName.trim())) { throw new EmptyFileGroupException(); } int count = 0; try { count = FileGroupLocalServiceUtil.countByD_DN(dossierId, partName.trim()); } catch (Exception e) { } if (count > 0) { throw new DuplicateFileGroupException(); } } /** * @param accountBean * @throws NoSuchAccountTypeException * @throws NoSuchAccountException * @throws NoSuchAccountFolderException * @throws NoSuchAccountOwnUserIdException * @throws NoSuchAccountOwnOrgIdException */ private void validateAccount(AccountBean accountBean) throws NoSuchAccountTypeException, NoSuchAccountException, NoSuchAccountFolderException, NoSuchAccountOwnUserIdException, NoSuchAccountOwnOrgIdException { if (accountBean == null) { throw new NoSuchAccountException(); } else if (Validator.isNull(accountBean.getAccountType())) { throw new NoSuchAccountTypeException(); } else if (accountBean.getAccountFolder() == null) { throw new NoSuchAccountFolderException(); } else if (accountBean.isCitizen() && accountBean.getOwnerUserId() == 0) { throw new NoSuchAccountOwnUserIdException(); } else if (accountBean.isBusiness() && accountBean.getOwnerOrganizationId() == 0) { throw new NoSuchAccountOwnOrgIdException(); } } private void validateAddAttachDossierFile( long dossierId, long dossierPartId, long dossierFileId, String displayName, long size, String sourceFileName, InputStream inputStream, AccountBean accountBean) throws NoSuchDossierException, NoSuchDossierPartException, NoSuchAccountException, NoSuchAccountTypeException, NoSuchAccountFolderException, NoSuchAccountOwnUserIdException, NoSuchAccountOwnOrgIdException, PermissionDossierException, FileSizeException { validateAccount(accountBean); if (dossierId <= 0) { throw new NoSuchDossierException(); } if (dossierPartId < 0) { throw new NoSuchDossierPartException(); } Dossier dossier = null; try { dossier = DossierLocalServiceUtil.getDossier(dossierId); } catch (Exception e) { throw new NoSuchDossierPartException(); } if (accountBean.isBusiness()) { if (dossier.getOwnerOrganizationId() != accountBean.getOwnerOrganizationId()) { throw new PermissionDossierException(); } } else if (accountBean.isCitizen()) { if (dossier.getUserId() != accountBean.getOwnerUserId()) { throw new PermissionDossierException(); } } try { DossierPartLocalServiceUtil.getDossierPart(dossierPartId); } catch (Exception e) { throw new NoSuchDossierPartException(); } if (size == 0) { throw new FileSizeException(); } else if (size > 300000000) { throw new FileSizeException(); } } private void validateCloneDossierFile( long dossierId, long dossierPartId, long dossierFileId, AccountBean accountBean) throws NoSuchDossierException, NoSuchDossierPartException, NoSuchAccountException, NoSuchAccountTypeException, NoSuchAccountFolderException, NoSuchAccountOwnUserIdException, NoSuchAccountOwnOrgIdException, PermissionDossierException, NoSuchDossierFileException, NoSuchFileEntryException { validateAccount(accountBean); if (dossierFileId <= 0) { throw new NoSuchDossierFileException(); } DossierFile dossierFile = null; try { dossierFile = DossierFileLocalServiceUtil.getDossierFile(dossierFileId); } catch (Exception e) { } if (dossierFile == null) { throw new NoSuchDossierFileException(); } if (dossierFile.getFileEntryId() <= 0) { throw new NoSuchFileEntryException(); } if (dossierId <= 0) { throw new NoSuchDossierException(); } if (dossierPartId < 0) { throw new NoSuchDossierPartException(); } Dossier dossier = null; try { dossier = DossierLocalServiceUtil.getDossier(dossierId); } catch (Exception e) { throw new NoSuchDossierPartException(); } if (accountBean.isBusiness()) { if (dossier.getOwnerOrganizationId() != accountBean.getOwnerOrganizationId()) { throw new PermissionDossierException(); } } else if (accountBean.isCitizen()) { if (dossier.getUserId() != accountBean.getOwnerUserId()) { throw new PermissionDossierException(); } } try { DossierPartLocalServiceUtil.getDossierPart(dossierPartId); } catch (Exception e) { throw new NoSuchDossierPartException(); } } /** * @param dossierFileId * @param accountBean * @throws NoSuchAccountTypeException * @throws NoSuchAccountException * @throws NoSuchAccountFolderException * @throws NoSuchAccountOwnUserIdException * @throws NoSuchAccountOwnOrgIdException * @throws NoSuchDossierFileException */ private void validateCreateDynamicForm( long dossierFileId, AccountBean accountBean) throws NoSuchAccountTypeException, NoSuchAccountException, NoSuchAccountFolderException, NoSuchAccountOwnUserIdException, NoSuchAccountOwnOrgIdException, NoSuchDossierFileException { validateAccount(accountBean); if (dossierFileId < 0) { throw new NoSuchDossierFileException(); } DossierFile dossierFile = null; try { dossierFile = DossierFileLocalServiceUtil.getDossierFile(dossierFileId); } catch (Exception e) { // TODO: handle exception } if (dossierFile == null) { throw new NoSuchDossierFileException(); } } private void validateDynamicFormData( long dossierId, long dossierPartId, AccountBean accountBean) throws NoSuchAccountTypeException, NoSuchAccountException, NoSuchAccountFolderException, NoSuchAccountOwnUserIdException, NoSuchAccountOwnOrgIdException, NoSuchDossierException, NoSuchDossierPartException, PermissionDossierException { validateAccount(accountBean); if (dossierId <= 0) { throw new NoSuchDossierException(); } if (dossierPartId < 0) { throw new NoSuchDossierPartException(); } Dossier dossier = null; try { dossier = DossierLocalServiceUtil.getDossier(dossierId); } catch (Exception e) { throw new NoSuchDossierPartException(); } if (accountBean.isBusiness()) { if (dossier.getOwnerOrganizationId() != accountBean.getOwnerOrganizationId()) { throw new PermissionDossierException(); } } else if (accountBean.isCitizen()) { if (dossier.getUserId() != accountBean.getOwnerUserId()) { throw new PermissionDossierException(); } } try { DossierPartLocalServiceUtil.getDossierPart(dossierPartId); } catch (Exception e) { throw new NoSuchDossierPartException(); } } /** * @param dossierId * @throws NoSuchDossierException * @throws NoSuchDossierTemplateException * @throws RequiredDossierPartException */ public void validateAssignTask(long dossierId) throws NoSuchDossierException, NoSuchDossierTemplateException, RequiredDossierPartException { if (dossierId <= 0) { throw new NoSuchDossierException(); } Dossier dossier = null; try { dossier = DossierLocalServiceUtil.getDossier(dossierId); } catch (Exception e) { } if (dossier == null) { throw new NoSuchDossierException(); } DossierTemplate dossierTemplate = null; try { dossierTemplate = DossierTemplateLocalServiceUtil.getDossierTemplate(dossier.getDossierTemplateId()); } catch (Exception e) { } if (dossierTemplate == null) { throw new NoSuchDossierTemplateException(); } List<DossierPart> dossierPartsLevel1 = new ArrayList<DossierPart>(); try { List<DossierPart> lstTmp1 = DossierPartLocalServiceUtil.getDossierPartsByT_P_PT( dossierTemplate.getDossierTemplateId(), 0, PortletConstants.DOSSIER_PART_TYPE_RESULT); if (lstTmp1 != null) { _log.info("************************************************************lstTmp1************************************************************ " + lstTmp1.size()); dossierPartsLevel1.addAll(lstTmp1); } } catch (Exception e) { } try { List<DossierPart> lstTmp2 = DossierPartLocalServiceUtil.getDossierPartsByT_P_PT( dossierTemplate.getDossierTemplateId(), 0, PortletConstants.DOSSIER_PART_TYPE_MULTIPLE_RESULT); if (lstTmp2 != null) { _log.info("************************************************************lstTmp2************************************************************ " + lstTmp2.size()); dossierPartsLevel1.addAll(lstTmp2); } } catch (Exception e) { } _log.info("************************************************************dossierPartsLevel1************************************************************ " + dossierPartsLevel1.size()); boolean requiredFlag = false; if (dossierPartsLevel1 != null) { for (DossierPart dossierPartLevel1 : dossierPartsLevel1) { List<DossierPart> dossierParts = DossierMgtUtil.getTreeDossierPart(dossierPartLevel1.getDossierpartId()); _log.info("************************************************************dossierParts************************************************************ " + dossierParts.size()); if (requiredFlag) { break; } for (DossierPart dossierPart : dossierParts) { _log.info("************************************************************dossierPart.getPartType()************************************************************ " + dossierPart.getPartType()); _log.info("************************************************************dossierPart.isRequired()************************************************************ " + dossierPart.isRequired()); if ((dossierPart.getPartType() == PortletConstants.DOSSIER_PART_TYPE_RESULT || dossierPart.getPartType() == PortletConstants.DOSSIER_PART_TYPE_MULTIPLE_RESULT) && dossierPart.getRequired()) { DossierFile dossierFile = null; try { dossierFile = DossierFileLocalServiceUtil.getDossierFileInUse( dossierId, dossierPart.getDossierpartId()); } catch (Exception e) { // TODO: handle exception } if (dossierFile == null) { requiredFlag = true; break; } } } } } if (requiredFlag) { throw new RequiredDossierPartException(); } } }
package org.pac4j.core.engine; import org.pac4j.core.authorization.checker.AuthorizationChecker; import org.pac4j.core.authorization.checker.DefaultAuthorizationChecker; import org.pac4j.core.client.Client; import org.pac4j.core.client.Clients; import org.pac4j.core.client.DirectClient; import org.pac4j.core.client.IndirectClient; import org.pac4j.core.client.finder.ClientFinder; import org.pac4j.core.client.finder.DefaultSecurityClientFinder; import org.pac4j.core.config.Config; import org.pac4j.core.context.WebContext; import org.pac4j.core.engine.decision.DefaultProfileStorageDecision; import org.pac4j.core.engine.decision.ProfileStorageDecision; import org.pac4j.core.credentials.Credentials; import org.pac4j.core.engine.savedrequest.DefaultSavedRequestHandler; import org.pac4j.core.engine.savedrequest.SavedRequestHandler; import org.pac4j.core.exception.http.ForbiddenAction; import org.pac4j.core.exception.http.HttpAction; import org.pac4j.core.exception.http.UnauthorizedAction; import org.pac4j.core.http.adapter.HttpActionAdapter; import org.pac4j.core.matching.RequireAllMatchersChecker; import org.pac4j.core.http.ajax.AjaxRequestResolver; import org.pac4j.core.matching.MatchingChecker; import org.pac4j.core.profile.ProfileManager; import org.pac4j.core.profile.UserProfile; import java.util.*; import static org.pac4j.core.util.CommonHelper.*; /** * <p>Default security logic:</p> * * <p>If the HTTP request matches the <code>matchers</code> configuration (or no <code>matchers</code> are defined), * the security is applied. Otherwise, the user is automatically granted access.</p> * * <p>First, if the user is not authenticated (no profile) and if some clients have been defined in the <code>clients</code> parameter, * a login is tried for the direct clients.</p> * * <p>Then, if the user has profile, authorizations are checked according to the <code>authorizers</code> configuration. * If the authorizations are valid, the user is granted access. Otherwise, a 403 error page is displayed.</p> * * <p>Finally, if the user is still not authenticated (no profile), he is redirected to the appropriate identity provider * if the first defined client is an indirect one in the <code>clients</code> configuration. Otherwise, a 401 error page is displayed.</p> * * @author Jerome Leleu * @since 1.9.0 */ public class DefaultSecurityLogic<R, C extends WebContext> extends AbstractExceptionAwareLogic<R, C> implements SecurityLogic<R, C> { private ClientFinder clientFinder = new DefaultSecurityClientFinder(); private AuthorizationChecker authorizationChecker = new DefaultAuthorizationChecker(); private MatchingChecker matchingChecker = new RequireAllMatchersChecker(); private ProfileStorageDecision profileStorageDecision = new DefaultProfileStorageDecision(); private SavedRequestHandler savedRequestHandler = new DefaultSavedRequestHandler(); @Override public R perform(final C context, final Config config, final SecurityGrantedAccessAdapter<R, C> securityGrantedAccessAdapter, final HttpActionAdapter<R, C> httpActionAdapter, final String clients, final String authorizers, final String matchers, final Boolean inputMultiProfile, final Object... parameters) { logger.debug("=== SECURITY ==="); HttpAction action; try { // default value final boolean multiProfile; if (inputMultiProfile == null) { multiProfile = false; } else { multiProfile = inputMultiProfile; } // checks assertNotNull("context", context); assertNotNull("config", config); assertNotNull("httpActionAdapter", httpActionAdapter); assertNotNull("clientFinder", clientFinder); assertNotNull("authorizationChecker", authorizationChecker); assertNotNull("matchingChecker", matchingChecker); assertNotNull("profileStorageDecision", profileStorageDecision); final Clients configClients = config.getClients(); assertNotNull("configClients", configClients); // logic logger.debug("url: {}", context.getFullRequestURL()); logger.debug("matchers: {}", matchers); if (matchingChecker.matches(context, matchers, config.getMatchers())) { logger.debug("clients: {}", clients); final List<Client> currentClients = clientFinder.find(configClients, context, clients); logger.debug("currentClients: {}", currentClients); final boolean loadProfilesFromSession = profileStorageDecision.mustLoadProfilesFromSession(context, currentClients); logger.debug("loadProfilesFromSession: {}", loadProfilesFromSession); final ProfileManager manager = getProfileManager(context); List<UserProfile> profiles = manager.getAll(loadProfilesFromSession); logger.debug("profiles: {}", profiles); // no profile and some current clients if (isEmpty(profiles) && isNotEmpty(currentClients)) { boolean updated = false; // loop on all clients searching direct ones to perform authentication for (final Client currentClient : currentClients) { if (currentClient instanceof DirectClient) { logger.debug("Performing authentication for direct client: {}", currentClient); final Optional<Credentials> credentials = currentClient.getCredentials(context); logger.debug("credentials: {}", credentials); if (credentials.isPresent()) { final Optional<UserProfile> profile = currentClient.getUserProfile(credentials.get(), context); logger.debug("profile: {}", profile); if (profile.isPresent()) { final boolean saveProfileInSession = profileStorageDecision.mustSaveProfileInSession(context, currentClients, (DirectClient) currentClient, profile.get()); logger.debug("saveProfileInSession: {} / multiProfile: {}", saveProfileInSession, multiProfile); manager.save(saveProfileInSession, profile.get(), multiProfile); updated = true; if (!multiProfile) { break; } } } } } if (updated) { profiles = manager.getAll(loadProfilesFromSession); logger.debug("new profiles: {}", profiles); } } // we have profile(s) -> check authorizations if (isNotEmpty(profiles)) { logger.debug("authorizers: {}", authorizers); if (authorizationChecker.isAuthorized(context, profiles, authorizers, config.getAuthorizers())) { logger.debug("authenticated and authorized -> grant access"); return securityGrantedAccessAdapter.adapt(context, profiles, parameters); } else { logger.debug("forbidden"); action = forbidden(context, currentClients, profiles, authorizers); } } else { if (startAuthentication(context, currentClients)) { logger.debug("Starting authentication"); saveRequestedUrl(context, currentClients, config.getClients().getAjaxRequestResolver()); action = redirectToIdentityProvider(context, currentClients); } else { logger.debug("unauthorized"); action = unauthorized(context, currentClients); } } } else { logger.debug("no matching for this request -> grant access"); return securityGrantedAccessAdapter.adapt(context, Arrays.asList(), parameters); } } catch (final Exception e) { return handleException(e, httpActionAdapter, context); } return httpActionAdapter.adapt(action, context); } /** * Return a forbidden error. * * @param context the web context * @param currentClients the current clients * @param profiles the current profiles * @param authorizers the authorizers * @return a forbidden error */ protected HttpAction forbidden(final C context, final List<Client> currentClients, final List<UserProfile> profiles, final String authorizers) { return ForbiddenAction.INSTANCE; } /** * Return whether we must start a login process if the first client is an indirect one. * * @param context the web context * @param currentClients the current clients * @return whether we must start a login process */ protected boolean startAuthentication(final C context, final List<Client> currentClients) { return isNotEmpty(currentClients) && currentClients.get(0) instanceof IndirectClient; } /** * Save the requested url. * * @param context the web context * @param currentClients the current clients */ protected void saveRequestedUrl(final C context, final List<Client> currentClients, AjaxRequestResolver ajaxRequestResolver) { if (ajaxRequestResolver == null || !ajaxRequestResolver.isAjax(context)) { savedRequestHandler.save(context); } } /** * Perform a redirection to start the login process of the first indirect client. * * @param context the web context * @param currentClients the current clients * @return the performed redirection */ protected HttpAction redirectToIdentityProvider(final C context, final List<Client> currentClients) { final IndirectClient currentClient = (IndirectClient) currentClients.get(0); return (HttpAction) currentClient.redirect(context).get(); } /** * Return an unauthorized error. * * @param context the web context * @param currentClients the current clients * @return an unauthorized error */ protected HttpAction unauthorized(final C context, final List<Client> currentClients) { return UnauthorizedAction.INSTANCE; } public ClientFinder getClientFinder() { return clientFinder; } public void setClientFinder(final ClientFinder clientFinder) { this.clientFinder = clientFinder; } public AuthorizationChecker getAuthorizationChecker() { return authorizationChecker; } public void setAuthorizationChecker(final AuthorizationChecker authorizationChecker) { this.authorizationChecker = authorizationChecker; } public MatchingChecker getMatchingChecker() { return matchingChecker; } public void setMatchingChecker(final MatchingChecker matchingChecker) { this.matchingChecker = matchingChecker; } public ProfileStorageDecision getProfileStorageDecision() { return profileStorageDecision; } public void setProfileStorageDecision(final ProfileStorageDecision profileStorageDecision) { this.profileStorageDecision = profileStorageDecision; } public SavedRequestHandler getSavedRequestHandler() { return savedRequestHandler; } public void setSavedRequestHandler(final SavedRequestHandler savedRequestHandler) { this.savedRequestHandler = savedRequestHandler; } @Override public String toString() { return toNiceString(this.getClass(), "clientFinder", this.clientFinder, "authorizationChecker", this.authorizationChecker, "matchingChecker", this.matchingChecker, "profileStorageDecision", this.profileStorageDecision, "errorUrl", getErrorUrl(), "savedRequestHandler", savedRequestHandler); } }
package gov.nih.nci.cabig.caaers.domain.expeditedfields; import static gov.nih.nci.cabig.caaers.domain.expeditedfields.ExpeditedReportSection.*; import static gov.nih.nci.cabig.caaers.domain.expeditedfields.ExpeditedReportSection.ADVERSE_EVENT_SECTION; import static gov.nih.nci.cabig.caaers.domain.expeditedfields.ExpeditedReportSection.ATTRIBUTION_SECTION; import static gov.nih.nci.cabig.caaers.domain.expeditedfields.ExpeditedReportSection.BASICS_SECTION; import static gov.nih.nci.cabig.caaers.domain.expeditedfields.ExpeditedReportSection.DESCRIPTION_SECTION; import static gov.nih.nci.cabig.caaers.domain.expeditedfields.ExpeditedReportSection.LABS_SECTION; import static gov.nih.nci.cabig.caaers.domain.expeditedfields.ExpeditedReportSection.MEDICAL_DEVICE_SECTION; import static gov.nih.nci.cabig.caaers.domain.expeditedfields.ExpeditedReportSection.MEDICAL_INFO_SECTION; import static gov.nih.nci.cabig.caaers.domain.expeditedfields.ExpeditedReportSection.OTHER_CAUSE_SECTION; import static gov.nih.nci.cabig.caaers.domain.expeditedfields.ExpeditedReportSection.OUTCOME_SECTION; import static gov.nih.nci.cabig.caaers.domain.expeditedfields.ExpeditedReportSection.RADIATION_INTERVENTION_SECTION; import static gov.nih.nci.cabig.caaers.domain.expeditedfields.ExpeditedReportSection.REPORTER_INFO_SECTION; import static gov.nih.nci.cabig.caaers.domain.expeditedfields.ExpeditedReportSection.SUBMIT_REPORT_SECTION; import static gov.nih.nci.cabig.caaers.domain.expeditedfields.ExpeditedReportSection.SURGERY_INTERVENTION_SECTION; import static gov.nih.nci.cabig.caaers.domain.expeditedfields.ExpeditedReportSection.TREATMENT_INFO_SECTION; import gov.nih.nci.cabig.caaers.CaaersSystemException; import gov.nih.nci.cabig.caaers.domain.ExpeditedAdverseEventReport; import gov.nih.nci.cabig.caaers.domain.ReportPerson; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import org.springframework.beans.PropertyValue; import org.springframework.beans.PropertyValues; /** * Tree representing most of the properties in the * {@link gov.nih.nci.cabig.caaers.domain.ExpeditedAdverseEventReport} model. <p/> Internal nodes in * the tree may represent a subproperty of their parent node, or may indicate a logical grouping * (section) of their children. In the latter case, the {@link #getPropertyName propertyName} * property will be null. * * @author Rhett Sutphin */ public class ExpeditedReportTree extends PropertylessNode { private Map<ExpeditedReportSection, TreeNode> sections; public ExpeditedReportTree() { sections = new LinkedHashMap<ExpeditedReportSection, TreeNode>(); add( section(BASICS_SECTION), section(ADVERSE_EVENT_SECTION, // TODO: figure out how to handle the MedDRA alternative here list("adverseEvents", new AdverseEventsDisplayNameCreator(), property("grade", "Grade"), property("adverseEventCtcTerm", property("term", "CTC term")), property("detailsForOther","Other (specify)"), property("startDate", "Start date"), property("endDate", "End date"), property("attributionSummary","Attribution to study"), property("hospitalization","Hospitalization"), property("expected", "Expected"), property("eventLocation", "Where was the patient when the event occurred?"), property("eventApproximateTime","Time of event"), property("outcomes", "Outcomes"), property("comments", "Comments") ) ), section(REPORTER_INFO_SECTION, createPersonBlock("reporter"), createPersonBlock("physician") ), section(RADIATION_INTERVENTION_SECTION, list("radiationInterventions","RadiationIntervention", property("administration","Type of radiation administration"), // TODO: these should be a component instead property("dosage", "Dosage"), property("dosageUnit","Dosage unit"), property("lastTreatmentDate", "Last treatment date"), property("fractionNumber", "Schedule number of fractions"), property("daysElapsed", "Elapsed days"), property("adjustment", "Adjustment")) ), section(SURGERY_INTERVENTION_SECTION, list("surgeryInterventions", "SurgeryIntervention", property("interventionSite", "Intervention site"), property("interventionDate", "Intervention date") ) ), section(MEDICAL_DEVICE_SECTION, list("medicalDevices", "MedicalDevice", property("brandName", "Brand name"), property("commonName", "Common name"), property("deviceType", "Device type"), property("manufacturerName", "Manufacturer name"), property("manufacturerCity", "Manufacturer city"), property("manufacturerState", "Manufacturer state"), property("modelNumber", "Model number"), property("lotNumber", "Lot number"), property("catalogNumber", "Catalog number"), property("expirationDate", "Expiration date"), property("serialNumber", "Serial number"), property("otherNumber", "Other number"), property("deviceOperator", "Device operator"), property("otherDeviceOperator", "Other device operator"), property("implantedDate", "If implanted, enter a date"), property("explantedDate", "IF explanted, enter a date"), property("deviceReprocessed", "Device reprocessed"), property("reprocessorName", "Reprocessor name"), property("reprocessorAddress", "Reprocessor address"), property("evaluationAvailability","Evaluation availability"), property("returnedDate", "Returned date") ) ), section(DESCRIPTION_SECTION, property("responseDescription", property("eventDescription", "Description"), property("presentStatus", "Present status"), property("recoveryDate","Date of recovery or death"), property("retreated","Has the participant been re-treated?"), property("blindBroken","Was blind broken due to event?"), property("studyDrugInterrupted","Was Study Drug stopped/interrupted/reduced in response to event?"), property("reducedDose","If reduced, specify: New dose"), property("reducedDate","Date dose reduced"), property("daysNotGiven","If interrupted, specify total number of days not given"), property("autopsyPerformed", "Autopsy performed?"), property("causeOfDeath", "Cause of death"), property("eventAbate", "Did event abate after study drug was stopped or dose reduced?"), property("eventReappear","Did event reappear after study drug was reintroduced?") ) ), section(TREATMENT_INFO_SECTION, property("treatmentInformation", property("treatmentAssignment","Treatment assignment code"), property("treatmentAssignmentDescription","Description of treatment assignment or dose level"), property("firstCourseDate","Start date of first course"), property("primaryTreatmentApproximateTime","Treatment time"), // TODO: these should be a component instead property("adverseEventCourse", property("date","Start date of course associated with expedited report"), property("number","Course number on which event occurred") ), property("totalCourses","Total number of courses to date"), // TODO : Need a display name creator???? list("courseAgents","Study Agent", property("studyAgent", "Study Agent"), property("formulation","Formulation"), property("lotNumber", "Lot # (if known)"), property("dose", property("amount","Total dose administered this course"), property("units","Unit of measure") ), // property("durationAndSchedule", // "Duration and schedule"), property("lastAdministeredDate","Date last administered"), // dosage("dose", "Dose"), // //old Dose // TODO: this is a component property("administrationDelayAmount","Administration Delay Amount"), property("administrationDelayUnits","Administration Delay Units"), property("comments", "Comments"),dosage("modifiedDose", "Modified dose") ) ) ), section(LABS_SECTION, list("labs", new LabsDisplayNameCreator(), codedOrOther("labTerm", "Lab test name", "other","Other test name"), property("units","Units"), labValue("baseline", "Baseline"), labValue("nadir", "Worst"), labValue("recovery", "Recovery"), property("site", "Site"), property("labDate", "date"), property("infectiousAgent","Infectious agent") ) ), section(OTHER_CAUSE_SECTION, list("otherCauses", "OtherCauses", property("text", "Cause"))), section(ATTRIBUTION_SECTION), // TODO: how to fill this?? section(ADDITIONAL_INFO_SECTION),// TODO: additional info section section(SUBMIT_REPORT_SECTION),// TODO: just a space filler section section(OUTCOME_SECTION),// TODO: just a space filler section section(PRIOR_THERAPIES_SECTION, list("saeReportPriorTherapies","Prior Therapy", property("priorTherapy", "Prior therapy"), property("other", "Comments (prior therapy)"), property("startDate", "Therapy start Date"), property("endDate", "Therapy end Date"), list("priorTherapyAgents", "PriorTherapyAgent", property("chemoAgent", "Agent") ) ) ), section(PRE_EXISTING_CONDITION_SECTION, list("saeReportPreExistingConditions","Pre-existing condition", codedOrOther("preExistingCondition","Pre-existing condition", "other","Other (pre-existing)") ) ), section(CONCOMITANT_MEDICATION_SECTION, list("concomitantMedications","Medication", property("agentName", "Medication"), property("stillTakingMedications","Continued ?"), property("startDate","Start date"), property("endDate","End date") ) ), section(MEDICAL_INFO_SECTION, //fields - general property("participantHistory", participantMeasure("height"), participantMeasure("weight"), property("baselinePerformanceStatus","Baseline performance") ), //fields related to diseases history property("diseaseHistory", codedOrOther("ctepStudyDisease", "Disease name","otherPrimaryDisease","Other (disease)"), codedOrOther("codedPrimaryDiseaseSite", "Primary site of disease", "otherPrimaryDiseaseSite", "Other (site of primary disease)"), property("diagnosisDate","Date of initial diagnosis"), //fields related to metastatic diseases list("metastaticDiseaseSites","Metastatic disease site", codedOrOther("codedSite","Site name","otherSite","Other(site of metastatic disease)") ) ) ) ); } @Override public TreeNode add(TreeNode... subnodes) { super.add(subnodes); for (TreeNode subnode : subnodes) { if (subnode instanceof SectionNode) { sections.put(((SectionNode) subnode).getSection(), subnode); } } return this; } @Override public String getPropertyName() { return null; } public List<UnsatisfiedProperty> verifyPropertiesPresent(String nodePropertyName, ExpeditedAdverseEventReport report) { return verifyPropertiesPresent(Collections.singleton(nodePropertyName), report); } public List<UnsatisfiedProperty> verifyPropertiesPresent(Collection<String> nodePropertyNames, ExpeditedAdverseEventReport report) { List<TreeNode> propertyNodes = new LinkedList<TreeNode>(); for (String propertyName : nodePropertyNames) { TreeNode node = find(propertyName); // HACK - if there is a property mismatch, node will be null. if (node == null) continue; // continue with next property. propertyNodes.add(node); } return verifyNodesSatisfied(propertyNodes, report); } public List<UnsatisfiedProperty> verifyNodesSatisfied(Collection<TreeNode> propertyNodes, ExpeditedAdverseEventReport report) { if (log.isDebugEnabled()) { log.debug("Examining report for satisfaction of " + propertyNodes); } List<UnsatisfiedProperty> unsatisfied = new LinkedList<UnsatisfiedProperty>(); for (TreeNode node : propertyNodes) { PropertyValues values = node.getPropertyValuesFrom(report); for (PropertyValue pv : values.getPropertyValues()) { if (pv.getValue() == null) { unsatisfied.add(new UnsatisfiedProperty(node, pv.getName())); } } } return unsatisfied; } public TreeNode getNodeForSection(ExpeditedReportSection section) { TreeNode node = sections.get(section); if (node == null && log.isDebugEnabled()) { log.debug("No node in the expedited report tree for " + section); } return node; } public ExpeditedReportSection getSectionForNode(TreeNode node) { if (node == null) throw new NullPointerException("No node provided"); if (node instanceof SectionNode) return ((SectionNode) node).getSection(); if (node.getParent() == null) throw new CaaersSystemException(node + " doesn't belong to a section"); return getSectionForNode(node.getParent()); } // //// TREE CONSTRUCTION HELPERS private static TreeNode createPersonBlock(String person) { return property(person, StringUtils.capitalize(person) + " details", property("title", "Job title"), property("firstName", "First name"), property("middleName", "Middle name"), property("lastName", "Last name"), contactField(ReportPerson.EMAIL, "E-mail address"), contactField(ReportPerson.PHONE), contactField(ReportPerson.FAX), property("address","Address", property("street", "Street"), property("city", "City"), property("state","State"), property("zip", "Zip"))); } private static TreeNode contactField(String contactType) { return contactField(contactType, StringUtils.capitalize(contactType)); } private static TreeNode contactField(String contactType, String displayName) { return property("contactMechanisms[" + contactType + ']', displayName); } private static TreeNode participantMeasure(String baseName) { return property(baseName, StringUtils.capitalize(baseName), property("quantity", "Quantity"), property("unit", "Units")); } private static TreeNode dosage(String baseName, String displayName) { return property(baseName, displayName, property("amount", "Amount"), property("units", "Units") // ,property("route", "Route") ); } private static TreeNode labValue(String baseName, String displayName) { return property(baseName, displayName, property("value", "Value"), property("date", "Date")); } }
package cz.hobrasoft.pdfmu.signature; import cz.hobrasoft.pdfmu.ArgsConfiguration; import cz.hobrasoft.pdfmu.OperationException; import cz.hobrasoft.pdfmu.PasswordArgs; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateException; import java.util.logging.Logger; import net.sourceforge.argparse4j.impl.Arguments; import net.sourceforge.argparse4j.inf.ArgumentParser; import net.sourceforge.argparse4j.inf.Namespace; /** * * @author <a href="mailto:filip.bartek@hobrasoft.cz">Filip Bartek</a> */ class KeystoreParameters implements ArgsConfiguration { public File file = null; public String type = null; public char[] password = null; // TODO: Replace with Console private static final Logger logger = Logger.getLogger(KeystoreParameters.class.getName()); private final PasswordArgs passwordArgs = new PasswordArgs("keystore password", "sp", "storepass", "keystore password (default: <empty>)", "spev", "storepassenvvar", "keystore password environment variable", "PDFMU_STOREPASS"); @Override public void addArguments(ArgumentParser parser) { // Valid types: // https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#KeyStore // Type "pkcs12" file extensions: P12, PFX // Another type: "Windows-MY" - Windows Certificate Store parser.addArgument("-t", "--type") .help("keystore type") .type(String.class) .choices(new String[]{"jceks", "jks", "dks", "pkcs11", "pkcs12", "Windows-MY"}); // TODO?: Guess type from file extension by default // TODO?: Default to "pkcs12" // TODO: Only allow "Windows-MY" when running in Windows // Keystore // CLI inspired by `keytool` parser.addArgument("-ks", "--keystore") .help("keystore file") .type(Arguments.fileType().verifyCanRead()); passwordArgs.addArguments(parser); } @Override public void setFromNamespace(Namespace namespace) { file = namespace.get("keystore"); type = namespace.getString("type"); // Set password passwordArgs.setFromNamespace(namespace); password = passwordArgs.getPassword(); } public void fixType() { // Set keystore type if not set from command line if (type == null) { // TODO: Guess type from `ksFile` file extension logger.info("Keystore type not specified. Using the default type."); type = KeyStore.getDefaultType(); } } public void fixPassword() { if (password == null) { logger.info("Keystore password not set. Using empty password."); password = "".toCharArray(); } } public KeyStore loadKeystore() throws OperationException { fixType(); logger.info(String.format("Keystore type: %s", type)); // digitalsignatures20130304.pdf : Code sample 2.2 // Initialize keystore KeyStore ks; try { ks = KeyStore.getInstance(type); } catch (KeyStoreException ex) { throw new OperationException(String.format("None of the registered security providers supports the keystore type %s.", type), ex); } logger.info(String.format("Keystore security provider: %s", ks.getProvider().getName())); switch (type) { case "Windows-MY": loadWindowsKeystore(ks); break; default: loadFileKeystore(ks); } return ks; } private void loadFileKeystore(KeyStore ks) throws OperationException { if (file == null) { throw new OperationException("Keystore not set but is required. Use --keystore option."); } logger.info(String.format("Keystore file: %s", file)); // ksIs FileInputStream ksIs; try { ksIs = new FileInputStream(file); } catch (FileNotFoundException ex) { throw new OperationException("Could not open keystore file.", ex); } fixPassword(); try { ks.load(ksIs, password); } catch (IOException ex) { throw new OperationException("Could not load keystore. Incorrect keystore password? Incorrect keystore type? Corrupted keystore file?", ex); } catch (NoSuchAlgorithmException | CertificateException ex) { throw new OperationException("Could not load keystore.", ex); } try { ksIs.close(); } catch (IOException ex) { throw new OperationException("Could not close keystore file.", ex); } } private void loadWindowsKeystore(KeyStore ks) throws OperationException { try { ks.load(null, null); } catch (IOException | NoSuchAlgorithmException | CertificateException ex) { throw new OperationException("Could not load keystore.", ex); } } }
package sk.henrichg.phoneprofilesplus; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.preference.ListPreference; import android.preference.Preference; import android.preference.PreferenceManager; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.List; public class Event { public long _id; public String _name; public long _fkProfileStart; public long _fkProfileEnd; //public boolean _undoneProfile; public int _atEndDo; private int _status; public String _notificationSound; public boolean _forceRun; public boolean _blocked; public int _priority; public int _delayStart; public boolean _isInDelay; public boolean _manualProfileActivation; public EventPreferencesTime _eventPreferencesTime; public EventPreferencesBattery _eventPreferencesBattery; public EventPreferencesCall _eventPreferencesCall; public EventPreferencesPeripherals _eventPreferencesPeripherals; public EventPreferencesCalendar _eventPreferencesCalendar; public EventPreferencesWifi _eventPreferencesWifi; public EventPreferencesScreen _eventPreferencesScreen; public EventPreferencesBluetooth _eventPreferencesBluetooth; public EventPreferencesSMS _eventPreferencesSMS; public static final int ESTATUS_STOP = 0; public static final int ESTATUS_PAUSE = 1; public static final int ESTATUS_RUNNING = 2; public static final int ESTATUS_NONE = 99; public static final int EPRIORITY_LOWEST = -5; public static final int EPRIORITY_VERY_LOW = -4; public static final int EPRIORITY_LOWER = -3; public static final int EPRIORITY_LOW = -1; public static final int EPRIORITY_LOWER_MEDIUM = -1; public static final int EPRIORITY_MEDIUM = 0; public static final int EPRIORITY_UPPER_MEDIUM = 1; public static final int EPRIORITY_HIGH = 2; public static final int EPRIORITY_HIGHER = 3; public static final int EPRIORITY_VERY_HIGH = 4; public static final int EPRIORITY_HIGHEST = 5; public static final int EATENDDO_NONE = 0; public static final int EATENDDO_UNDONE_PROFILE = 1; public static final int EATENDDO_RESTART_EVENTS = 2; static final String PREF_EVENT_ENABLED = "eventEnabled"; static final String PREF_EVENT_NAME = "eventName"; static final String PREF_EVENT_PROFILE_START = "eventProfileStart"; static final String PREF_EVENT_PROFILE_END = "eventProfileEnd"; static final String PREF_EVENT_NOTIFICATION_SOUND = "eventNotificationSound"; static final String PREF_EVENT_FORCE_RUN = "eventForceRun"; //static final String PREF_EVENT_UNDONE_PROFILE = "eventUndoneProfile"; static final String PREF_EVENT_PRIORITY = "eventPriority"; static final String PREF_EVENT_DELAY_START = "eventDelayStart"; static final String PREF_EVENT_AT_END_DO = "eventAtEndDo"; static final String PREF_EVENT_MANUAL_PROFILE_ACTIVATION = "manualProfileActivation"; // Empty constructor public Event(){ } // constructor public Event(long id, String name, long fkProfileStart, long fkProfileEnd, int status, String notificationSound, boolean forceRun, boolean blocked, //boolean undoneProfile, int priority, int delayStart, boolean isInDelay, int atEndDo, boolean manualProfileActivation) { this._id = id; this._name = name; this._fkProfileStart = fkProfileStart; this._fkProfileEnd = fkProfileEnd; this._status = status; this._notificationSound = notificationSound; this._forceRun = forceRun; this._blocked = blocked; //this._undoneProfile = undoneProfile; this._priority = priority; this._delayStart = delayStart; this._isInDelay = isInDelay; this._atEndDo = atEndDo; this._manualProfileActivation = manualProfileActivation; createEventPreferences(); } // constructor public Event(String name, long fkProfileStart, long fkProfileEnd, int status, String notificationSound, boolean forceRun, boolean blocked, //boolean undoneProfile, int priority, int delayStart, boolean isInDelay, int atEndDo, boolean manualProfileActivation) { this._name = name; this._fkProfileStart = fkProfileStart; this._fkProfileEnd = fkProfileEnd; this._status = status; this._notificationSound = notificationSound; this._forceRun = forceRun; this._blocked = blocked; //this._undoneProfile = undoneProfile; this._priority = priority; this._delayStart = delayStart; this._isInDelay = isInDelay; this._atEndDo = atEndDo; this._manualProfileActivation = manualProfileActivation; createEventPreferences(); } public void copyEvent(Event event) { this._id = event._id; this._name = event._name; this._fkProfileStart = event._fkProfileStart; this._fkProfileEnd = event._fkProfileEnd; this._status = event._status; this._notificationSound = event._notificationSound; this._forceRun = event._forceRun; this._blocked = event._blocked; //this._undoneProfile = event._undoneProfile; this._priority = event._priority; this._delayStart = event._delayStart; this._isInDelay = event._isInDelay; this._atEndDo = event._atEndDo; this._manualProfileActivation = event._manualProfileActivation; copyEventPreferences(event); } private void createEventPreferencesTime() { this._eventPreferencesTime = new EventPreferencesTime(this, false, false, false, false, false, false, false, false, 0, 0/*, false*/); } private void createEventPreferencesBattery() { this._eventPreferencesBattery = new EventPreferencesBattery(this, false, 0, 100, false); } private void createEventPreferencesCall() { this._eventPreferencesCall = new EventPreferencesCall(this, false, 0, "", "", 0); } private void createEventPreferencesPeripherals() { this._eventPreferencesPeripherals = new EventPreferencesPeripherals(this, false, 0); } private void createEventPreferencesCalendar() { this._eventPreferencesCalendar = new EventPreferencesCalendar(this, false, "", 0, "", 0); } private void createEventPreferencesWiFi() { this._eventPreferencesWifi = new EventPreferencesWifi(this, false, "", 1); } private void createEventPreferencesScreen() { this._eventPreferencesScreen = new EventPreferencesScreen(this, false, 1, false); } private void createEventPreferencesBluetooth() { this._eventPreferencesBluetooth = new EventPreferencesBluetooth(this, false, "", 0); } private void createEventPreferencesSMS() { this._eventPreferencesSMS = new EventPreferencesSMS(this, false, "", "", 0); } public void createEventPreferences() { createEventPreferencesTime(); createEventPreferencesBattery(); createEventPreferencesCall(); createEventPreferencesPeripherals(); createEventPreferencesCalendar(); createEventPreferencesWiFi(); createEventPreferencesScreen(); createEventPreferencesBluetooth(); createEventPreferencesSMS(); } public void copyEventPreferences(Event fromEvent) { if (this._eventPreferencesTime == null) createEventPreferencesTime(); if (this._eventPreferencesBattery == null) createEventPreferencesBattery(); if (this._eventPreferencesCall == null) createEventPreferencesCall(); if (this._eventPreferencesPeripherals == null) createEventPreferencesPeripherals(); if (this._eventPreferencesCalendar == null) createEventPreferencesCalendar(); if (this._eventPreferencesWifi == null) createEventPreferencesWiFi(); if (this._eventPreferencesScreen == null) createEventPreferencesScreen(); if (this._eventPreferencesBluetooth == null) createEventPreferencesBluetooth(); if (this._eventPreferencesSMS == null) createEventPreferencesSMS(); this._eventPreferencesTime.copyPreferences(fromEvent); this._eventPreferencesBattery.copyPreferences(fromEvent); this._eventPreferencesCall.copyPreferences(fromEvent); this._eventPreferencesPeripherals.copyPreferences(fromEvent); this._eventPreferencesCalendar.copyPreferences(fromEvent); this._eventPreferencesWifi.copyPreferences(fromEvent); this._eventPreferencesScreen.copyPreferences(fromEvent); this._eventPreferencesBluetooth.copyPreferences(fromEvent); this._eventPreferencesSMS.copyPreferences(fromEvent); } public boolean isRunnable() { boolean runnable = (this._fkProfileStart != 0); if (!(this._eventPreferencesTime._enabled || this._eventPreferencesBattery._enabled || this._eventPreferencesCall._enabled || this._eventPreferencesPeripherals._enabled || this._eventPreferencesCalendar._enabled || this._eventPreferencesWifi._enabled || this._eventPreferencesScreen._enabled || this._eventPreferencesBluetooth._enabled || this._eventPreferencesSMS._enabled)) runnable = false; if (this._eventPreferencesTime._enabled) runnable = runnable && this._eventPreferencesTime.isRunable(); if (this._eventPreferencesBattery._enabled) runnable = runnable && this._eventPreferencesBattery.isRunable(); if (this._eventPreferencesCall._enabled) runnable = runnable && this._eventPreferencesCall.isRunable(); if (this._eventPreferencesPeripherals._enabled) runnable = runnable && this._eventPreferencesPeripherals.isRunable(); if (this._eventPreferencesCalendar._enabled) runnable = runnable && this._eventPreferencesCalendar.isRunable(); if (this._eventPreferencesWifi._enabled) runnable = runnable && this._eventPreferencesWifi.isRunable(); if (this._eventPreferencesScreen._enabled) runnable = runnable && this._eventPreferencesScreen.isRunable(); if (this._eventPreferencesBluetooth._enabled) runnable = runnable && this._eventPreferencesBluetooth.isRunable(); if (this._eventPreferencesSMS._enabled) runnable = runnable && this._eventPreferencesSMS.isRunable(); return runnable; } public void loadSharedPrefereces(SharedPreferences preferences) { Editor editor = preferences.edit(); editor.putString(PREF_EVENT_NAME, this._name); editor.putString(PREF_EVENT_PROFILE_START, Long.toString(this._fkProfileStart)); editor.putString(PREF_EVENT_PROFILE_END, Long.toString(this._fkProfileEnd)); editor.putBoolean(PREF_EVENT_ENABLED, this._status != ESTATUS_STOP); editor.putString(PREF_EVENT_NOTIFICATION_SOUND, this._notificationSound); editor.putBoolean(PREF_EVENT_FORCE_RUN, this._forceRun); //editor.putBoolean(PREF_EVENT_UNDONE_PROFILE, this._undoneProfile); editor.putString(PREF_EVENT_PRIORITY, Integer.toString(this._priority)); editor.putString(PREF_EVENT_DELAY_START, Integer.toString(this._delayStart)); editor.putString(PREF_EVENT_AT_END_DO, Integer.toString(this._atEndDo)); editor.putBoolean(PREF_EVENT_MANUAL_PROFILE_ACTIVATION, this._manualProfileActivation); this._eventPreferencesTime.loadSharedPrefereces(preferences); this._eventPreferencesBattery.loadSharedPrefereces(preferences); this._eventPreferencesCall.loadSharedPrefereces(preferences); this._eventPreferencesPeripherals.loadSharedPrefereces(preferences); this._eventPreferencesCalendar.loadSharedPrefereces(preferences); this._eventPreferencesWifi.loadSharedPrefereces(preferences); this._eventPreferencesScreen.loadSharedPrefereces(preferences); this._eventPreferencesBluetooth.loadSharedPrefereces(preferences); this._eventPreferencesSMS.loadSharedPrefereces(preferences); editor.commit(); } public void saveSharedPrefereces(SharedPreferences preferences) { this._name = preferences.getString(PREF_EVENT_NAME, ""); this._fkProfileStart = Long.parseLong(preferences.getString(PREF_EVENT_PROFILE_START, "0")); this._fkProfileEnd = Long.parseLong(preferences.getString(PREF_EVENT_PROFILE_END, Long.toString(GlobalData.PROFILE_NO_ACTIVATE))); this._status = (preferences.getBoolean(PREF_EVENT_ENABLED, false)) ? ESTATUS_PAUSE : ESTATUS_STOP; this._notificationSound = preferences.getString(PREF_EVENT_NOTIFICATION_SOUND, ""); this._forceRun = preferences.getBoolean(PREF_EVENT_FORCE_RUN, false); //this._undoneProfile = preferences.getBoolean(PREF_EVENT_UNDONE_PROFILE, true); this._priority = Integer.parseInt(preferences.getString(PREF_EVENT_PRIORITY, Integer.toString(EPRIORITY_MEDIUM))); this._atEndDo = Integer.parseInt(preferences.getString(PREF_EVENT_AT_END_DO, Integer.toString(EATENDDO_UNDONE_PROFILE))); this._manualProfileActivation = preferences.getBoolean(PREF_EVENT_MANUAL_PROFILE_ACTIVATION, false); String sDelayStart = preferences.getString(PREF_EVENT_DELAY_START, "0"); if (sDelayStart.isEmpty()) sDelayStart = "0"; int iDelayStart = Integer.parseInt(sDelayStart); if (iDelayStart < 0) iDelayStart = 0; this._delayStart = iDelayStart; this._eventPreferencesTime.saveSharedPrefereces(preferences); this._eventPreferencesBattery.saveSharedPrefereces(preferences); this._eventPreferencesCall.saveSharedPrefereces(preferences); this._eventPreferencesPeripherals.saveSharedPrefereces(preferences); this._eventPreferencesCalendar.saveSharedPrefereces(preferences); this._eventPreferencesWifi.saveSharedPrefereces(preferences); this._eventPreferencesScreen.saveSharedPrefereces(preferences); this._eventPreferencesBluetooth.saveSharedPrefereces(preferences); this._eventPreferencesSMS.saveSharedPrefereces(preferences); if (!this.isRunnable()) this._status = ESTATUS_STOP; } public void setSummary(PreferenceManager prefMng, String key, String value, Context context) { if (key.equals(PREF_EVENT_NAME)) { Preference preference = prefMng.findPreference(key); preference.setSummary(value); GUIData.setPreferenceTitleStyle(preference, false, true); } if (key.equals(PREF_EVENT_PROFILE_START)||key.equals(PREF_EVENT_PROFILE_END)) { Preference preference = prefMng.findPreference(key); String sProfileId = value; long lProfileId; try { lProfileId = Long.parseLong(sProfileId); } catch (Exception e) { lProfileId = 0; } DataWrapper dataWrapper = new DataWrapper(context, false, false, 0); Profile profile = dataWrapper.getProfileById(lProfileId, false); if (profile != null) { preference.setSummary(profile._name); } else { if (lProfileId == GlobalData.PROFILE_NO_ACTIVATE) preference.setSummary(context.getResources().getString(R.string.profile_preference_profile_end_no_activate)); else preference.setSummary(context.getResources().getString(R.string.profile_preference_profile_not_set)); } if (key.equals(PREF_EVENT_PROFILE_START)) GUIData.setPreferenceTitleStyle(preference, false, true); } if (key.equals(PREF_EVENT_NOTIFICATION_SOUND)) { String ringtoneUri = value.toString(); if (ringtoneUri.isEmpty()) prefMng.findPreference(key).setSummary(R.string.preferences_notificationSound_None); else { Uri uri = Uri.parse(ringtoneUri); Ringtone ringtone = RingtoneManager.getRingtone(context, uri); String ringtoneName; if (ringtone == null) ringtoneName = ""; else ringtoneName = ringtone.getTitle(context); prefMng.findPreference(key).setSummary(ringtoneName); } } if (key.equals(PREF_EVENT_PRIORITY)) { ListPreference listPreference = (ListPreference)prefMng.findPreference(key); int index = listPreference.findIndexOfValue(value); CharSequence summary = (index >= 0) ? listPreference.getEntries()[index] : null; listPreference.setSummary(summary); } if (key.equals(PREF_EVENT_AT_END_DO)) { ListPreference listPreference = (ListPreference)prefMng.findPreference(key); int index = listPreference.findIndexOfValue(value); CharSequence summary = (index >= 0) ? listPreference.getEntries()[index] : null; listPreference.setSummary(summary); } if (key.equals(PREF_EVENT_DELAY_START)) { prefMng.findPreference(key).setSummary(value); } } public void setSummary(PreferenceManager prefMng, String key, SharedPreferences preferences, Context context) { if (key.equals(PREF_EVENT_NAME) || key.equals(PREF_EVENT_PROFILE_START) || key.equals(PREF_EVENT_PROFILE_END) || key.equals(PREF_EVENT_NOTIFICATION_SOUND) || key.equals(PREF_EVENT_PRIORITY) || key.equals(PREF_EVENT_DELAY_START) || key.equals(PREF_EVENT_AT_END_DO)) setSummary(prefMng, key, preferences.getString(key, ""), context); _eventPreferencesTime.setSummary(prefMng, key, preferences, context); _eventPreferencesBattery.setSummary(prefMng, key, preferences, context); _eventPreferencesCall.setSummary(prefMng, key, preferences, context); _eventPreferencesPeripherals.setSummary(prefMng, key, preferences, context); _eventPreferencesCalendar.setSummary(prefMng, key, preferences, context); _eventPreferencesWifi.setSummary(prefMng, key, preferences, context); _eventPreferencesScreen.setSummary(prefMng, key, preferences, context); _eventPreferencesBluetooth.setSummary(prefMng, key, preferences, context); _eventPreferencesSMS.setSummary(prefMng, key, preferences, context); } public void setAllSummary(PreferenceManager prefMng, Context context) { setSummary(prefMng, PREF_EVENT_NAME, _name, context); setSummary(prefMng, PREF_EVENT_PROFILE_START, Long.toString(this._fkProfileStart), context); setSummary(prefMng, PREF_EVENT_PROFILE_END, Long.toString(this._fkProfileEnd), context); setSummary(prefMng, PREF_EVENT_NOTIFICATION_SOUND, this._notificationSound, context); setSummary(prefMng, PREF_EVENT_PRIORITY, Integer.toString(this._priority), context); setSummary(prefMng, PREF_EVENT_DELAY_START, Integer.toString(this._delayStart), context); setSummary(prefMng, PREF_EVENT_AT_END_DO, Integer.toString(this._atEndDo), context); _eventPreferencesTime.setAllSummary(prefMng, context); _eventPreferencesBattery.setAllSummary(prefMng, context); _eventPreferencesCall.setAllSummary(prefMng, context); _eventPreferencesPeripherals.setAllSummary(prefMng, context); _eventPreferencesCalendar.setAllSummary(prefMng, context); _eventPreferencesWifi.setAllSummary(prefMng, context); _eventPreferencesScreen.setAllSummary(prefMng, context); _eventPreferencesBluetooth.setAllSummary(prefMng, context); _eventPreferencesSMS.setAllSummary(prefMng, context); } public String getPreferecesDescription(Context context) { String description; description = ""; description = _eventPreferencesTime.getPreferencesDescription(description, context); if (_eventPreferencesCalendar._enabled && (!description.isEmpty())) description = description + "\n"; description = _eventPreferencesCalendar.getPreferencesDescription(description, context); if (_eventPreferencesBattery._enabled && (!description.isEmpty())) description = description + "\n"; description = _eventPreferencesBattery.getPreferencesDescription(description, context); if (_eventPreferencesCall._enabled && (!description.isEmpty())) description = description + "\n"; description = _eventPreferencesCall.getPreferencesDescription(description, context); if (_eventPreferencesSMS._enabled && (!description.isEmpty())) description = description + "\n"; description = _eventPreferencesSMS.getPreferencesDescription(description, context); if (_eventPreferencesWifi._enabled && (!description.isEmpty())) description = description + "\n"; description = _eventPreferencesWifi.getPreferencesDescription(description, context); if (_eventPreferencesBluetooth._enabled && (!description.isEmpty())) description = description + "\n"; description = _eventPreferencesBluetooth.getPreferencesDescription(description, context); if (_eventPreferencesPeripherals._enabled && (!description.isEmpty())) description = description + "\n"; description = _eventPreferencesPeripherals.getPreferencesDescription(description, context); if (_eventPreferencesScreen._enabled && (!description.isEmpty())) description = description + "\n"; description = _eventPreferencesScreen.getPreferencesDescription(description, context); //description = description.replace(' ', '\u00A0'); return description; } private boolean canActivateReturnProfile() { /* boolean canActivate = false; if (this._eventPreferencesTime._enabled) canActivate = canActivate || this._eventPreferencesTime.activateReturnProfile(); if (this._eventPreferencesBattery._enabled) canActivate = canActivate || this._eventPreferencesBattery.activateReturnProfile(); if (this._eventPreferencesCall._enabled) canActivate = canActivate || this._eventPreferencesCall.activateReturnProfile(); if (this._eventPreferencesPeripherals._enabled) canActivate = canActivate || this._eventPreferencesPeripherals.activateReturnProfile(); if (this._eventPreferencesCalendar._enabled) canActivate = canActivate || this._eventPreferencesCalendar.activateReturnProfile(); if (this._eventPreferencesWifi._enabled) canActivate = canActivate || this._eventPreferencesWifi.activateReturnProfile(); if (this._eventPreferencesScreen._enabled) canActivate = canActivate || this._eventPreferencesScreen.activateReturnProfile(); if (this._eventPreferencesBluetooth._enabled) canActivate = canActivate || this._eventPreferencesBluetooth.activateReturnProfile(); if (this._eventPreferencesSMS._enabled) canActivate = canActivate || this._eventPreferencesSMS.activateReturnProfile(); return canActivate; */ return true; } private int getEventTimelinePosition(List<EventTimeline> eventTimelineList) { boolean exists = false; int eventPosition = -1; for (EventTimeline eventTimeline : eventTimelineList) { eventPosition++; if (eventTimeline._fkEvent == this._id) { exists = true; break; } } if (exists) return eventPosition; else return -1; } private EventTimeline addEventTimeline(DataWrapper dataWrapper, List<EventTimeline> eventTimelineList, Profile mergedProfile) { EventTimeline eventTimeline = new EventTimeline(); eventTimeline._fkEvent = this._id; eventTimeline._eorder = 0; Profile profile = null; if (eventTimelineList.size() == 0) { profile = dataWrapper.getActivatedProfile(); if (profile != null) eventTimeline._fkProfileEndActivated = profile._id; else eventTimeline._fkProfileEndActivated = 0; } else { eventTimeline._fkProfileEndActivated = 0; EventTimeline _eventTimeline = eventTimelineList.get(eventTimelineList.size()-1); if (_eventTimeline != null) { Event event = dataWrapper.getEventById(_eventTimeline._fkEvent); if (event != null) eventTimeline._fkProfileEndActivated = event._fkProfileStart; } } dataWrapper.getDatabaseHandler().addEventTimeline(eventTimeline); eventTimelineList.add(eventTimeline); return eventTimeline; } public void startEvent(DataWrapper dataWrapper, List<EventTimeline> eventTimelineList, boolean ignoreGlobalPref, boolean interactive, boolean reactivate, boolean log, Profile mergedProfile) { // remove delay alarm removeDelayAlarm(dataWrapper, true); // for start delay if ((!GlobalData.getGlobalEventsRuning(dataWrapper.context)) && (!ignoreGlobalPref)) // events are globally stopped return; if (!this.isRunnable()) // event is not runnable, no pause it return; if (GlobalData.getEventsBlocked(dataWrapper.context)) { // blocked by manual profile activation GlobalData.logE("Event.startEvent","event_id="+this._id+" events blocked"); GlobalData.logE("Event.startEvent","event_id="+this._id+" forceRun="+_forceRun); GlobalData.logE("Event.startEvent","event_id="+this._id+" blocked="+_blocked); if (!_forceRun) // event is not forceRun return; if (_blocked) // forceRun event is temporary blocked return; } // search for runing event with higher priority for (EventTimeline eventTimeline : eventTimelineList) { Event event = dataWrapper.getEventById(eventTimeline._fkEvent); if ((event != null) && (event._priority > this._priority)) // is running event with higher priority return; } if (_forceRun) GlobalData.setForceRunEventRunning(dataWrapper.context, true); GlobalData.logE("@@@ Event.startEvent","event_id="+this._id+" GlobalData.logE("@@@ Event.startEvent","-- event_name="+this._name); EventTimeline eventTimeline; /////// delete duplicate from timeline boolean exists = true; while (exists) { exists = false; int timeLineSize = eventTimelineList.size(); // test whenever event exists in timeline eventTimeline = null; int eventPosition = getEventTimelinePosition(eventTimelineList); GlobalData.logE("Event.startEvent","eventPosition="+eventPosition); if (eventPosition != -1) eventTimeline = eventTimelineList.get(eventPosition); exists = eventPosition != -1; if (exists) { // remove event from timeline eventTimelineList.remove(eventTimeline); dataWrapper.getDatabaseHandler().deleteEventTimeline(eventTimeline); if (eventPosition < (timeLineSize-1)) { if (eventPosition > 0) { EventTimeline _eventTimeline = eventTimelineList.get(eventPosition-1); Event event = dataWrapper.getEventById(_eventTimeline._fkEvent); if (event != null) eventTimelineList.get(eventPosition)._fkProfileEndActivated = event._fkProfileStart; else eventTimelineList.get(eventPosition)._fkProfileEndActivated = 0; } else { eventTimelineList.get(eventPosition)._fkProfileEndActivated = eventTimeline._fkProfileEndActivated; } } } } //eventTimeline = addEventTimeline(dataWrapper, eventTimelineList, mergedProfile); setSystemEvent(dataWrapper.context, ESTATUS_RUNNING); int status = this._status; this._status = ESTATUS_RUNNING; dataWrapper.getDatabaseHandler().updateEventStatus(this); if (log && (status != this._status)) { dataWrapper.getDatabaseHandler().addActivityLog(DatabaseHandler.ALTYPE_EVENTSTART, _name, null, null, 0); } long activatedProfileId = 0; Profile activatedProfile = dataWrapper.getActivatedProfile(); if (activatedProfile != null) activatedProfileId = activatedProfile._id; if ((this._fkProfileStart != activatedProfileId) || this._manualProfileActivation || reactivate) { // no activate profile, when is already activated GlobalData.logE("Event.startEvent","event_id="+this._id+" activate profile id="+this._fkProfileStart); if (interactive) { if (mergedProfile == null) dataWrapper.activateProfileFromEvent(this._fkProfileStart, interactive, false, false, _notificationSound, true); else { mergedProfile.mergeProfiles(this._fkProfileStart, dataWrapper); if (this._manualProfileActivation) { dataWrapper.getDatabaseHandler().saveMergedProfile(mergedProfile); dataWrapper.activateProfileFromEvent(mergedProfile._id, interactive, true, true, _notificationSound, true); mergedProfile._id = 0; } } } else { if (mergedProfile == null) dataWrapper.activateProfileFromEvent(this._fkProfileStart, interactive, false, false, "", true); else { mergedProfile.mergeProfiles(this._fkProfileStart, dataWrapper); if (this._manualProfileActivation) { dataWrapper.getDatabaseHandler().saveMergedProfile(mergedProfile); dataWrapper.activateProfileFromEvent(mergedProfile._id, interactive, true, true, "", true); mergedProfile._id = 0; } } } } else { dataWrapper.updateNotificationAndWidgets(activatedProfile, ""); } return; } private void doActivateEndProfile(DataWrapper dataWrapper, int eventPosition, int timeLineSize, List<EventTimeline> eventTimelineList, EventTimeline eventTimeline, boolean activateReturnProfile, Profile mergedProfile) { if (!(eventPosition == (timeLineSize-1))) { // event is not in end of timeline // check whether events behind have set _fkProfileEnd or _undoProfile // when true, no activate "end profile" /*for (int i = eventPosition; i < (timeLineSize-1); i++) { if (_fkProfileEnd != Event.PROFILE_END_NO_ACTIVATE) return; if (_undoneProfile) return; }*/ return; } boolean profileActivated = false; Profile activatedProfile = dataWrapper.getActivatedProfile(); // activate profile only when profile not already activated if (activateReturnProfile && canActivateReturnProfile()) { long activatedProfileId = 0; if (activatedProfile != null) activatedProfileId = activatedProfile._id; // first activate _fkProfileEnd if (_fkProfileEnd != GlobalData.PROFILE_NO_ACTIVATE) { if (_fkProfileEnd != activatedProfileId) { GlobalData.logE("Event.pauseEvent","activate end porfile"); if (mergedProfile == null) dataWrapper.activateProfileFromEvent(_fkProfileEnd, false, false, false, "", true); else mergedProfile.mergeProfiles(_fkProfileEnd, dataWrapper); activatedProfileId = _fkProfileEnd; profileActivated = true; } } // second activate when undone profile is set if (_atEndDo == EATENDDO_UNDONE_PROFILE) { // when in timeline list is event, get start profile from last event in tlimeline list // because last event in timeline list may be changed if (eventTimelineList.size() > 0) { EventTimeline _eventTimeline = eventTimelineList.get(eventTimelineList.size() - 1); if (_eventTimeline != null) { Event event = dataWrapper.getEventById(_eventTimeline._fkEvent); if (event != null) eventTimeline._fkProfileEndActivated = event._fkProfileStart; } } if (eventTimeline._fkProfileEndActivated != activatedProfileId) { GlobalData.logE("Event.pauseEvent","undone profile"); GlobalData.logE("Event.pauseEvent","_fkProfileEndActivated="+eventTimeline._fkProfileEndActivated); if (eventTimeline._fkProfileEndActivated != 0) { if (mergedProfile == null) dataWrapper.activateProfileFromEvent(eventTimeline._fkProfileEndActivated, false, false, false, "", true); else mergedProfile.mergeProfiles(eventTimeline._fkProfileEndActivated, dataWrapper); profileActivated = true; } } } // restart events when is set if (_atEndDo == EATENDDO_RESTART_EVENTS) { GlobalData.logE("Event.pauseEvent","restart events"); dataWrapper.restartEventsWithDelay(3); profileActivated = true; } } if (!profileActivated) { dataWrapper.updateNotificationAndWidgets(activatedProfile, ""); } } public void pauseEvent(DataWrapper dataWrapper, List<EventTimeline> eventTimelineList, boolean activateReturnProfile, boolean ignoreGlobalPref, boolean noSetSystemEvent, boolean log, Profile mergedProfile) { // remove delay alarm removeDelayAlarm(dataWrapper, true); // for start delay if ((!GlobalData.getGlobalEventsRuning(dataWrapper.context)) && (!ignoreGlobalPref)) // events are globally stopped return; if (!this.isRunnable()) // event is not runnable, no pause it return; /* if (GlobalData.getEventsBlocked(dataWrapper.context)) { // blocked by manual profile activation GlobalData.logE("Event.pauseEvent","event_id="+this._id+" events blocked"); if (!_forceRun) // event is not forceRun return; } */ // unblock event when paused dataWrapper.setEventBlocked(this, false); GlobalData.logE("@@@ Event.pauseEvent","event_id="+this._id+" GlobalData.logE("@@@ Event.pauseEvent","-- event_name="+this._name); int timeLineSize = eventTimelineList.size(); // test whenever event exists in timeline boolean exists = false; int eventPosition = getEventTimelinePosition(eventTimelineList); GlobalData.logE("Event.pauseEvent","eventPosition="+eventPosition); exists = eventPosition != -1; EventTimeline eventTimeline = null; if (exists) { eventTimeline = eventTimelineList.get(eventPosition); // remove event from timeline eventTimelineList.remove(eventTimeline); dataWrapper.getDatabaseHandler().deleteEventTimeline(eventTimeline); if (eventPosition < (timeLineSize-1)) // event is not in end of timeline and no only one event in timeline { if (eventPosition > 0) // event is not in start of timeline { // get event prior deleted event EventTimeline _eventTimeline = eventTimelineList.get(eventPosition-1); Event event = dataWrapper.getEventById(_eventTimeline._fkEvent); // set _fkProfileEndActivated for event behind deleted event with _fkProfileStart of deleted event if (event != null) eventTimelineList.get(eventPosition)._fkProfileEndActivated = event._fkProfileStart; else eventTimelineList.get(eventPosition)._fkProfileEndActivated = 0; } else // event is in start of timeline { // set _fkProfileEndActivated of first event with _fkProfileEndActivated of deleted event eventTimelineList.get(eventPosition)._fkProfileEndActivated = eventTimeline._fkProfileEndActivated; } } } if (!noSetSystemEvent) setSystemEvent(dataWrapper.context, ESTATUS_PAUSE); int status = this._status; this._status = ESTATUS_PAUSE; dataWrapper.getDatabaseHandler().updateEventStatus(this); if (log && (status != this._status)) { int alType = DatabaseHandler.ALTYPE_EVENTEND_NONE; if ((_atEndDo == EATENDDO_UNDONE_PROFILE) && (_fkProfileEnd != GlobalData.PROFILE_NO_ACTIVATE)) alType = DatabaseHandler.ALTYPE_EVENTEND_ACTIVATEPROFILE_UNDOPROFILE; if ((_atEndDo == EATENDDO_RESTART_EVENTS) && (_fkProfileEnd != GlobalData.PROFILE_NO_ACTIVATE)) alType = DatabaseHandler.ALTYPE_EVENTEND_ACTIVATEPROFILE_RESTARTEVENTS; else if (_atEndDo == EATENDDO_UNDONE_PROFILE) alType = DatabaseHandler.ALTYPE_EVENTEND_UNDOPROFILE; else if (_atEndDo == EATENDDO_RESTART_EVENTS) alType = DatabaseHandler.ALTYPE_EVENTEND_RESTARTEVENTS; else if (_fkProfileEnd != GlobalData.PROFILE_NO_ACTIVATE) alType = DatabaseHandler.ALTYPE_EVENTEND_ACTIVATEPROFILE; dataWrapper.getDatabaseHandler().addActivityLog(alType, _name, null, null, 0); } //if (_forceRun) //{ look for forcerun events always, not only when forcerun event is paused boolean forceRunRunning = false; for (EventTimeline _eventTimeline : eventTimelineList) { Event event = dataWrapper.getEventById(_eventTimeline._fkEvent); if ((event != null) && (event._forceRun)) { forceRunRunning = true; break; } } if (!forceRunRunning) GlobalData.setForceRunEventRunning(dataWrapper.context, false); if (exists) { doActivateEndProfile(dataWrapper, eventPosition, timeLineSize, eventTimelineList, eventTimeline, activateReturnProfile, mergedProfile); } return; } public void stopEvent(DataWrapper dataWrapper, List<EventTimeline> eventTimelineList, boolean activateReturnProfile, boolean ignoreGlobalPref, boolean saveEventStatus, boolean log) { // remove delay alarm removeDelayAlarm(dataWrapper, true); // for start delay if ((!GlobalData.getGlobalEventsRuning(dataWrapper.context)) && (!ignoreGlobalPref)) // events are globally stopped return; GlobalData.logE("@@@ Event.stopEvent","event_id="+this._id+" GlobalData.logE("@@@ Event.stopEvent", "-- event_name=" + this._name); if (this._status != ESTATUS_STOP) { pauseEvent(dataWrapper, eventTimelineList, activateReturnProfile, ignoreGlobalPref, true, false, null); } setSystemEvent(dataWrapper.context, ESTATUS_STOP); //int status = this._status; this._status = ESTATUS_STOP; if (saveEventStatus) dataWrapper.getDatabaseHandler().updateEventStatus(this); /* if (log && (status != this._status)) { dataWrapper.getDatabaseHandler().addActivityLog(DatabaseHandler.ALTYPE_EVENTSTOP, _name, null, null, 0); }*/ return; } public int getStatus() { return _status; } public int getStatusFromDB(DataWrapper dataWrapper) { return dataWrapper.getDatabaseHandler().getEventStatus(this); } public void setStatus(int status) { _status = status; } public void setSystemEvent(Context context, int forStatus) { if (forStatus == ESTATUS_PAUSE) { // event paused // setup system event for next running status _eventPreferencesTime.setSystemRunningEvent(context); _eventPreferencesBattery.setSystemRunningEvent(context); _eventPreferencesCall.setSystemRunningEvent(context); _eventPreferencesPeripherals.setSystemRunningEvent(context); _eventPreferencesCalendar.setSystemRunningEvent(context); _eventPreferencesWifi.setSystemRunningEvent(context); _eventPreferencesScreen.setSystemRunningEvent(context); _eventPreferencesBluetooth.setSystemRunningEvent(context); _eventPreferencesSMS.setSystemRunningEvent(context); } else if (forStatus == ESTATUS_RUNNING) { // event started // setup system event for pause status _eventPreferencesTime.setSystemPauseEvent(context); _eventPreferencesBattery.setSystemPauseEvent(context); _eventPreferencesCall.setSystemPauseEvent(context); _eventPreferencesPeripherals.setSystemPauseEvent(context); _eventPreferencesCalendar.setSystemPauseEvent(context); _eventPreferencesWifi.setSystemPauseEvent(context); _eventPreferencesScreen.setSystemPauseEvent(context); _eventPreferencesBluetooth.setSystemPauseEvent(context); _eventPreferencesSMS.setSystemPauseEvent(context); } else if (forStatus == ESTATUS_STOP) { // event stopped // remove all system events _eventPreferencesTime.removeSystemEvent(context); _eventPreferencesBattery.removeSystemEvent(context); _eventPreferencesCall.removeSystemEvent(context); _eventPreferencesPeripherals.removeSystemEvent(context); _eventPreferencesCalendar.removeSystemEvent(context); _eventPreferencesWifi.removeSystemEvent(context); _eventPreferencesScreen.removeSystemEvent(context); _eventPreferencesBluetooth.removeSystemEvent(context); _eventPreferencesSMS.removeSystemEvent(context); } } @SuppressLint("SimpleDateFormat") public void setDelayAlarm(DataWrapper dataWrapper, boolean forStart, boolean ignoreGlobalPref, boolean log) { removeDelayAlarm(dataWrapper, forStart); if ((!GlobalData.getGlobalEventsRuning(dataWrapper.context)) && (!ignoreGlobalPref)) // events are globally stopped return; if (!this.isRunnable()) // event is not runnable, no pause it return; if (GlobalData.getEventsBlocked(dataWrapper.context)) { // blocked by manual profile activation GlobalData.logE("Event.setDelayAlarm","event_id="+this._id+" events blocked"); if (!_forceRun) // event is not forceRun return; if (_blocked) // forceRun event is temporary blocked return; } GlobalData.logE("@@@ Event.setDelayAlarm","event_id="+this._id+" GlobalData.logE("@@@ Event.setDelayAlarm","-- event_name="+this._name); GlobalData.logE("@@@ Event.setDelayAlarm","-- delay="+this._delayStart); if (this._delayStart > 0) { // delay for start is > 0 // set alarm Calendar now = Calendar.getInstance(); long alarmTime = now.getTimeInMillis() + 1000 * this._delayStart; SimpleDateFormat sdf = new SimpleDateFormat("EE d.MM.yyyy HH:mm:ss:S"); String result = sdf.format(alarmTime); if (forStart) GlobalData.logE("Event.setDelayAlarm","startTime="+result); else GlobalData.logE("Event.setDelayAlarm","endTime="+result); Intent intent = new Intent(dataWrapper.context, EventDelayBroadcastReceiver.class); intent.putExtra(GlobalData.EXTRA_EVENT_ID, this._id); intent.putExtra(GlobalData.EXTRA_START_SYSTEM_EVENT, forStart); PendingIntent pendingIntent = PendingIntent.getBroadcast(dataWrapper.context.getApplicationContext(), (int) this._id, intent, PendingIntent.FLAG_CANCEL_CURRENT); AlarmManager alarmManager = (AlarmManager) dataWrapper.context.getSystemService(Activity.ALARM_SERVICE); alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent); //alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, alarmTime, 24 * 60 * 60 * 1000 , pendingIntent); //alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, alarmTime, 24 * 60 * 60 * 1000 , pendingIntent); this._isInDelay = true; } else this._isInDelay = false; dataWrapper.getDatabaseHandler().updateEventInDelay(this); if (log && _isInDelay) { dataWrapper.getDatabaseHandler().addActivityLog(DatabaseHandler.ALTYPE_EVENTSTARTDELAY, _name, null, null, _delayStart); } return; } public void removeDelayAlarm(DataWrapper dataWrapper, boolean forStart) { AlarmManager alarmManager = (AlarmManager) dataWrapper.context.getSystemService(Activity.ALARM_SERVICE); Intent intent = new Intent(dataWrapper.context, EventDelayBroadcastReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(dataWrapper.context.getApplicationContext(), (int) this._id, intent, PendingIntent.FLAG_NO_CREATE); if (pendingIntent != null) { GlobalData.logE("Event.removeDelayAlarm","alarm found"); alarmManager.cancel(pendingIntent); pendingIntent.cancel(); } this._isInDelay = false; dataWrapper.getDatabaseHandler().updateEventInDelay(this); } }