List of usage examples for java.util HashMap remove
public V remove(Object key)
From source file:com.lp.server.auftrag.ejbfac.AuftragFacBean.java
public ArrayList<KundeDto> getRechnungsadressenEinerAuftragsadresseSortiertNachHaeufigkeit( Integer kundeIIdAuftragsadresse, TheClientDto theClientDto) { HashMap<Integer, Integer> anzahlRechnungsadressen = new HashMap<Integer, Integer>(); Query query = em.createNamedQuery("AuftragfindByKundeIIdAuftragsadresseMandantCNr"); query.setParameter(1, kundeIIdAuftragsadresse); query.setParameter(2, theClientDto.getMandant()); Collection<?> cl = query.getResultList(); Iterator it = cl.iterator();//from ww w. ja va 2s .c om while (it.hasNext()) { Auftrag auftrag = (Auftrag) it.next(); if (anzahlRechnungsadressen.containsKey(auftrag.getKundeIIdRechnungsadresse())) { Integer iAnzahl = anzahlRechnungsadressen.get(auftrag.getKundeIIdRechnungsadresse()); iAnzahl++; anzahlRechnungsadressen.put(auftrag.getKundeIIdRechnungsadresse(), iAnzahl); } else { anzahlRechnungsadressen.put(auftrag.getKundeIIdRechnungsadresse(), new Integer(1)); } } ArrayList<KundeDto> kunden = new ArrayList<KundeDto>(); while (anzahlRechnungsadressen.size() > 0) { Iterator itAnzahl = anzahlRechnungsadressen.keySet().iterator(); Integer iGroessteAnzahl = null; Integer keyGroessteAnzahl = null; while (itAnzahl.hasNext()) { Integer key = (Integer) itAnzahl.next(); Integer value = anzahlRechnungsadressen.get(key); if (iGroessteAnzahl == null) { iGroessteAnzahl = value; } if (keyGroessteAnzahl == null) { keyGroessteAnzahl = key; } if (value >= iGroessteAnzahl) { iGroessteAnzahl = value; keyGroessteAnzahl = key; } } anzahlRechnungsadressen.remove(keyGroessteAnzahl); kunden.add(getKundeFac().kundeFindByPrimaryKey(keyGroessteAnzahl, theClientDto)); } return kunden; }
From source file:com.wasteofplastic.acidisland.commands.Challenges.java
/** * Checks if a player has enough for a challenge. Supports two types of * checks, inventory and island. Removes items if required. * //w w w . j a v a 2 s .c o m * @param player * @param challenge * @param type * @return true if the player has everything required */ @SuppressWarnings("deprecation") public boolean hasRequired(final Player player, final String challenge, final String type) { // Check money double moneyReq = 0D; if (Settings.useEconomy) { moneyReq = getChallengeConfig().getDouble("challenges.challengeList." + challenge + ".requiredMoney", 0D); if (moneyReq > 0D) { if (!VaultHelper.econ.has(player, Settings.worldName, moneyReq)) { player.sendMessage( ChatColor.RED + plugin.myLocale(player.getUniqueId()).challengeserrorNotEnoughItems); player.sendMessage(ChatColor.RED + getChallengeConfig() .getString("challenges.challengeList." + challenge + ".description")); return false; } } } final String[] reqList = getChallengeConfig() .getString("challenges.challengeList." + challenge + ".requiredItems").split(" "); // The format of the requiredItems is as follows: // Material:Qty // or // Material:DamageModifier:Qty // This second one is so that items such as potions or variations on // standard items can be collected if (type.equalsIgnoreCase("inventory")) { List<ItemStack> toBeRemoved = new ArrayList<ItemStack>(); Material reqItem; int reqAmount = 0; for (final String s : reqList) { final String[] part = s.split(":"); // Material:Qty if (part.length == 2) { try { // Correct some common mistakes if (part[0].equalsIgnoreCase("potato")) { part[0] = "POTATO_ITEM"; } else if (part[0].equalsIgnoreCase("brewing_stand")) { part[0] = "BREWING_STAND_ITEM"; } else if (part[0].equalsIgnoreCase("carrot")) { part[0] = "CARROT_ITEM"; } else if (part[0].equalsIgnoreCase("cauldron")) { part[0] = "CAULDRON_ITEM"; } else if (part[0].equalsIgnoreCase("skull")) { part[0] = "SKULL_ITEM"; } // TODO: add netherwart vs. netherstalk? if (StringUtils.isNumeric(part[0])) { reqItem = Material.getMaterial(Integer.parseInt(part[0])); } else { reqItem = Material.getMaterial(part[0].toUpperCase()); } reqAmount = Integer.parseInt(part[1]); ItemStack item = new ItemStack(reqItem); // plugin.getLogger().info("DEBUG: required item = " + // reqItem.toString()); // plugin.getLogger().info("DEBUG: item amount = " + // reqAmount); if (!player.getInventory().contains(reqItem)) { return false; } else { // check amount int amount = 0; // plugin.getLogger().info("DEBUG: Amount in inventory = " // + player.getInventory().all(reqItem).size()); // Go through all the inventory and try to find // enough required items for (Entry<Integer, ? extends ItemStack> en : player.getInventory().all(reqItem) .entrySet()) { // Get the item ItemStack i = en.getValue(); // Map needs special handling because the // durability increments every time a new one is // made by the player // TODO: if there are any other items that act // in the same way, they need adding too... if (i.getDurability() == 0 || (reqItem == Material.MAP && i.getType() == Material.MAP)) { // Clear any naming, or lore etc. i.setItemMeta(null); player.getInventory().setItem(en.getKey(), i); // #1 item stack qty + amount is less than // required items - take all i // #2 item stack qty + amount = required // item - // take all // #3 item stack qty + amount > req items - // take // portion of i // amount += i.getAmount(); if ((amount + i.getAmount()) < reqAmount) { // Remove all of this item stack - clone // otherwise it will keep a reference to // the // original toBeRemoved.add(i.clone()); amount += i.getAmount(); // plugin.getLogger().info("DEBUG: amount is <= req Remove " // + i.toString() + ":" + // i.getDurability() + " x " + // i.getAmount()); } else if ((amount + i.getAmount()) == reqAmount) { // plugin.getLogger().info("DEBUG: amount is = req Remove " // + i.toString() + ":" + // i.getDurability() + " x " + // i.getAmount()); toBeRemoved.add(i.clone()); amount += i.getAmount(); break; } else { // Remove a portion of this item // plugin.getLogger().info("DEBUG: amount is > req Remove " // + i.toString() + ":" + // i.getDurability() + " x " + // i.getAmount()); item.setAmount(reqAmount - amount); item.setDurability(i.getDurability()); toBeRemoved.add(item); amount += i.getAmount(); break; } } } // plugin.getLogger().info("DEBUG: amount "+ // amount); if (amount < reqAmount) { return false; } } } catch (Exception e) { plugin.getLogger().severe("Problem with " + s + " in challenges.yml!"); player.sendMessage( ChatColor.RED + plugin.myLocale(player.getUniqueId()).errorCommandNotReady); String materialList = ""; boolean hint = false; for (Material m : Material.values()) { materialList += m.toString() + ","; if (m.toString().contains(s.substring(0, 3).toUpperCase())) { plugin.getLogger().severe("Did you mean " + m.toString() + "?"); hint = true; } } if (!hint) { plugin.getLogger() .severe("Sorry, I have no idea what " + s + " is. Pick from one of these:"); plugin.getLogger().severe(materialList.substring(0, materialList.length() - 1)); } else { plugin.getLogger().severe("Correct challenges.yml with the correct material."); } return false; } } else if (part.length == 3) { // This handles items with durability or potions try { // Correct some common mistakes if (part[0].equalsIgnoreCase("potato")) { part[0] = "POTATO_ITEM"; } else if (part[0].equalsIgnoreCase("brewing_stand")) { part[0] = "BREWING_STAND_ITEM"; } else if (part[0].equalsIgnoreCase("carrot")) { part[0] = "CARROT_ITEM"; } else if (part[0].equalsIgnoreCase("cauldron")) { part[0] = "CAULDRON_ITEM"; } else if (part[0].equalsIgnoreCase("skull")) { part[0] = "SKULL_ITEM"; } if (StringUtils.isNumeric(part[0])) { reqItem = Material.getMaterial(Integer.parseInt(part[0])); } else { reqItem = Material.getMaterial(part[0].toUpperCase()); } reqAmount = Integer.parseInt(part[2]); int reqDurability = Integer.parseInt(part[1]); int count = reqAmount; // plugin.getLogger().info("DEBUG: 3 part " + // reqItem.toString() + ":" + reqDurability + " x " + // reqAmount); ItemStack item = new ItemStack(reqItem); // Check for potions if (reqItem.equals(Material.POTION)) { //Logger.logger(2,"DEBUG: Potion"); // Contains at least does not work for potions ItemStack[] playerInv = player.getInventory().getContents(); for (ItemStack i : playerInv) { if (i != null && i.getType().equals(Material.POTION)) { // plugin.getLogger().info("DEBUG: Potion found, durability = "+ // i.getDurability()); // Potion type was given by number // Only included for backward compatibility if (i.getDurability() == reqDurability) { item = i.clone(); if (item.getAmount() > reqAmount) { item.setAmount(reqAmount); } count = count - item.getAmount(); // plugin.getLogger().info("Matched! count = " // + count); // If the item stack has more in it than // required, just take the minimum // plugin.getLogger().info("DEBUG: Found " // + item.toString() + ":" + // item.getDurability() + " x " + // item.getAmount()); toBeRemoved.add(item); } } if (count == 0) { break; } } if (count > 0) { return false; } // They have enough } else { // Item item.setDurability((short) reqDurability); // plugin.getLogger().info("DEBUG: item with durability " // + item.toString()); // item.setAmount(reqAmount); /* * if (!player.getInventory().containsAtLeast(item, * reqAmount)) { * plugin.getLogger().info( * "DEBUG: item with durability not enough"); * return false; * } */ // check amount int amount = 0; // Go through all the inventory and try to find // enough required items for (Entry<Integer, ? extends ItemStack> en : player.getInventory().all(reqItem) .entrySet()) { // Get the item ItemStack i = en.getValue(); if (i.getDurability() == reqDurability) { // Clear any naming, or lore etc. i.setItemMeta(null); player.getInventory().setItem(en.getKey(), i); // #1 item stack qty + amount is less than // required items - take all i // #2 item stack qty + amount = required // item - // take all // #3 item stack qty + amount > req items - // take // portion of i // amount += i.getAmount(); if ((amount + i.getAmount()) < reqAmount) { // Remove all of this item stack - clone // otherwise it will keep a reference to // the // original toBeRemoved.add(i.clone()); amount += i.getAmount(); // plugin.getLogger().info("DEBUG: amount is <= req Remove " // + i.toString() + ":" + // i.getDurability() // + " x " + i.getAmount()); } else if ((amount + i.getAmount()) == reqAmount) { toBeRemoved.add(i.clone()); amount += i.getAmount(); break; } else { // Remove a portion of this item // plugin.getLogger().info("DEBUG: amount is > req Remove " // + i.toString() + ":" + // i.getDurability() // + " x " + i.getAmount()); item.setAmount(reqAmount - amount); item.setDurability(i.getDurability()); toBeRemoved.add(item); amount += i.getAmount(); break; } } } // plugin.getLogger().info("DEBUG: amount is " + // amount); // plugin.getLogger().info("DEBUG: req amount is " + // reqAmount); if (amount < reqAmount) { return false; } } // plugin.getLogger().info("DEBUG: before set amount " + // item.toString() + ":" + item.getDurability() + " x " // + item.getAmount()); // item.setAmount(reqAmount); // plugin.getLogger().info("DEBUG: after set amount " + // item.toString() + ":" + item.getDurability() + " x " // + item.getAmount()); // toBeRemoved.add(item); } catch (Exception e) { plugin.getLogger().severe("Problem with " + s + " in challenges.yml!"); player.sendMessage( ChatColor.RED + plugin.myLocale(player.getUniqueId()).errorCommandNotReady); if (part[0].equalsIgnoreCase("POTION")) { plugin.getLogger() .severe("Format POTION:TYPE:QTY where TYPE is the number of the following:"); for (PotionType p : PotionType.values()) { plugin.getLogger().info(p.toString() + ":" + p.getDamageValue()); } } else { String materialList = ""; boolean hint = false; for (Material m : Material.values()) { materialList += m.toString() + ","; if (m.toString().contains(s.substring(0, 3))) { plugin.getLogger().severe("Did you mean " + m.toString() + "?"); hint = true; } } if (!hint) { plugin.getLogger() .severe("Sorry, I have no idea what " + s + " is. Pick from one of these:"); plugin.getLogger().severe(materialList.substring(0, materialList.length() - 1)); } else { plugin.getLogger().severe("Correct challenges.yml with the correct material."); } return false; } return false; } } else if (part.length == 6) { //plugin.getLogger().info("DEBUG:6 part potion check!"); // POTION:Name:Level:Extended:Splash:Qty try { if (StringUtils.isNumeric(part[0])) { reqItem = Material.getMaterial(Integer.parseInt(part[0])); } else { reqItem = Material.getMaterial(part[0].toUpperCase()); } reqAmount = Integer.parseInt(part[5]); ItemStack item = new ItemStack(reqItem); int count = reqAmount; // Compare if (reqItem == Material.POTION) { //plugin.getLogger().info("DEBUG: required item is a potion"); ItemStack[] playerInv = player.getInventory().getContents(); for (ItemStack i : playerInv) { if (i != null && i.getType().equals(Material.POTION)) { //plugin.getLogger().info("DEBUG: Item in inventory = " + i.toString()); Potion p = fromDamage(i.getDurability()); // Check type //Potion p = Potion.fromItemStack(i); //plugin.getLogger().info("DEBUG: " + p.getType() + ":" + p.getLevel() + ":" + p.hasExtendedDuration() + ":" + p.isSplash() ); // Check type PotionType typeCheck = PotionType.valueOf(part[1].toUpperCase()); //plugin.getLogger().info("DEBUG: potion type is:" + p.getType().toString() + " desired is:" + part[1].toUpperCase()); //if (p.getType().toString().equalsIgnoreCase(part[1].toUpperCase())) { if (p.getType().equals(typeCheck)) { //plugin.getLogger().info("DEBUG: potion type is the same"); // Check level //plugin.getLogger().info("DEBUG: check level " + part[2] + " = " + p.getLevel()); if (part[2].isEmpty() || p.getLevel() == Integer.valueOf(part[2])) { //plugin.getLogger().info("DEBUG: level is ok "); //plugin.getLogger().info("DEBUG: check splash = " + part[4] + " = " + p.isSplash()); if (part[4].isEmpty() || (p.isSplash() && part[4].equalsIgnoreCase("SPLASH")) || (!p.isSplash() && part[4].equalsIgnoreCase("NOSPLASH"))) { //plugin.getLogger().info("DEBUG: splash is ok = " + part[4] + " = " + p.isSplash()); //plugin.getLogger().info("DEBUG: check extended = " + part[4] + " = " + p.hasExtendedDuration()); if (part[3].isEmpty() || (p.hasExtendedDuration() && part[3].equalsIgnoreCase("EXTENDED")) || (!p.hasExtendedDuration() && part[3].equalsIgnoreCase("NOTEXTENDED"))) { //plugin.getLogger().info("DEBUG: Everything is matching"); item = i.clone(); if (item.getAmount() > reqAmount) { item.setAmount(reqAmount); } count = count - item.getAmount(); toBeRemoved.add(item); } } } } } if (count <= 0) { break; } } if (count > 0) { return false; } } else { plugin.getLogger().severe("Problem with " + s + " in challenges.yml!"); } } catch (Exception e) { plugin.getLogger().severe("Problem with " + s + " in challenges.yml!"); //e.printStackTrace(); player.sendMessage( ChatColor.RED + plugin.myLocale(player.getUniqueId()).errorCommandNotReady); if (part[0].equalsIgnoreCase("POTION")) { plugin.getLogger().severe( "Format POTION:NAME:<LEVEL>:<EXTENDED/NOTEXTENDED>:<SPLASH/NOSPLASH>:QTY"); plugin.getLogger().severe("LEVEL, EXTENDED and SPLASH are optional"); plugin.getLogger().severe("LEVEL is a number"); plugin.getLogger().severe("Examples:"); plugin.getLogger().severe("POTION:STRENGTH:1:EXTENDED:SPLASH:1"); plugin.getLogger().severe("POTION:JUMP:2:NOTEXTENDED:NOSPLASH:1"); plugin.getLogger().severe("POTION:WEAKNESS::::1 - any weakness potion"); plugin.getLogger().severe("Available names are:"); String potionNames = ""; for (PotionType p : PotionType.values()) { potionNames += p.toString() + ", "; } plugin.getLogger().severe(potionNames.substring(0, potionNames.length() - 2)); } return false; } } } // Build up the items in the inventory and remove them if they are // all there. if (getChallengeConfig().getBoolean("challenges.challengeList." + challenge + ".takeItems")) { // checkChallengeItems(player, challenge); // int qty = 0; // plugin.getLogger().info("DEBUG: Removing items"); for (ItemStack i : toBeRemoved) { // qty += i.getAmount(); // plugin.getLogger().info("DEBUG: Remove " + i.toString() + // "::" + i.getDurability() + " x " + i.getAmount()); HashMap<Integer, ItemStack> leftOver = player.getInventory().removeItem(i); if (!leftOver.isEmpty()) { plugin.getLogger().warning("Exploit? Could not remove the following in challenge " + challenge + " for player " + player.getName() + ":"); for (ItemStack left : leftOver.values()) { plugin.getLogger().info(left.toString()); } return false; } } // Remove money if (moneyReq > 0D) { EconomyResponse er = VaultHelper.econ.withdrawPlayer(player, moneyReq); if (!er.transactionSuccess()) { plugin.getLogger().warning("Exploit? Could not remove " + VaultHelper.econ.format(moneyReq) + " from " + player.getName() + " in challenge " + challenge); plugin.getLogger().warning("Player's balance is " + VaultHelper.econ.format(VaultHelper.econ.getBalance(player))); } } // plugin.getLogger().info("DEBUG: total = " + qty); } return true; } if (type.equalsIgnoreCase("island")) { final HashMap<Material, Integer> neededItem = new HashMap<Material, Integer>(); final HashMap<EntityType, Integer> neededEntities = new HashMap<EntityType, Integer>(); for (int i = 0; i < reqList.length; i++) { final String[] sPart = reqList[i].split(":"); // Parse the qty required first try { final int qty = Integer.parseInt(sPart[1]); // Find out if the needed item is a Material or an Entity boolean isEntity = false; for (EntityType entityType : EntityType.values()) { if (entityType.toString().equalsIgnoreCase(sPart[0])) { isEntity = true; break; } } if (isEntity) { // plugin.getLogger().info("DEBUG: Item " + // sPart[0].toUpperCase() + " is an entity"); EntityType entityType = EntityType.valueOf(sPart[0].toUpperCase()); if (entityType != null) { neededEntities.put(entityType, qty); // plugin.getLogger().info("DEBUG: Needed entity is " // + Integer.parseInt(sPart[1]) + " x " + // EntityType.valueOf(sPart[0].toUpperCase()).toString()); } } else { Material item; if (StringUtils.isNumeric(sPart[0])) { item = Material.getMaterial(Integer.parseInt(sPart[0])); } else { item = Material.getMaterial(sPart[0].toUpperCase()); } if (item != null) { neededItem.put(item, qty); // plugin.getLogger().info("DEBUG: Needed item is " // + Integer.parseInt(sPart[1]) + " x " + // Material.getMaterial(sPart[0]).toString()); } else { plugin.getLogger().warning("Problem parsing required item for challenge " + challenge + " in challenges.yml!"); return false; } } } catch (Exception intEx) { plugin.getLogger().warning("Problem parsing required items for challenge " + challenge + " in challenges.yml - skipping"); return false; } } // We now have two sets of required items or entities // Check the items first final Location l = player.getLocation(); // if (!neededItem.isEmpty()) { final int px = l.getBlockX(); final int py = l.getBlockY(); final int pz = l.getBlockZ(); for (int x = -10; x <= 10; x++) { for (int y = -10; y <= 10; y++) { for (int z = -10; z <= 10; z++) { final Material b = new Location(l.getWorld(), px + x, py + y, pz + z).getBlock().getType(); if (neededItem.containsKey(b)) { if (neededItem.get(b) == 1) { neededItem.remove(b); } else { // Reduce the require amount by 1 neededItem.put(b, neededItem.get(b) - 1); } } } } } // } // Check if all the needed items have been amassed if (!neededItem.isEmpty()) { // plugin.getLogger().info("DEBUG: Insufficient items around"); for (Material missing : neededItem.keySet()) { player.sendMessage( ChatColor.RED + plugin.myLocale(player.getUniqueId()).challengeserrorYouAreMissing + " " + neededItem.get(missing) + " x " + Util.prettifyText(missing.toString())); } return false; } else { // plugin.getLogger().info("DEBUG: Items are there"); // Check for needed entities for (Entity entity : player.getNearbyEntities(10, 10, 10)) { // plugin.getLogger().info("DEBUG: Entity found:" + // entity.getType().toString()); if (neededEntities.containsKey(entity.getType())) { // plugin.getLogger().info("DEBUG: Entity in list"); if (neededEntities.get(entity.getType()) == 1) { neededEntities.remove(entity.getType()); // plugin.getLogger().info("DEBUG: Entity qty satisfied"); } else { neededEntities.put(entity.getType(), neededEntities.get(entity.getType()) - 1); // plugin.getLogger().info("DEBUG: Entity qty reduced by 1"); } } else { // plugin.getLogger().info("DEBUG: Entity not in list"); } } if (neededEntities.isEmpty()) { return true; } else { for (EntityType missing : neededEntities.keySet()) { player.sendMessage(ChatColor.RED + plugin.myLocale(player.getUniqueId()).challengeserrorYouAreMissing + " " + neededEntities.get(missing) + " x " + Util.prettifyText(missing.toString())); } return false; } } } return true; }
From source file:nz.govt.natlib.ndha.manualdeposit.ManualDepositPresenter.java
private void renumberEntityTypes(ArrayList<FileGroupCollection> entitiesSuper) { HashMap<RepresentationTypes, Integer> typeCount = new HashMap<RepresentationTypes, Integer>(); for (FileGroupCollection entities : entitiesSuper) { for (FileGroup entityTest : entities) { int entityNo = 1; if (typeCount.containsKey(entityTest.getEntityType())) { entityNo = typeCount.get(entityTest.getEntityType()); entityNo++;/* w ww . j a v a 2s . co m*/ typeCount.remove(entityTest.getEntityType()); } typeCount.put(entityTest.getEntityType(), entityNo); entityTest.setEntityName(getEntityName(entityTest.getEntityType(), entityNo)); } } }
From source file:com.MainFiles.Functions.java
public String PIN_Verify(String strReferenceNo, String strNarration, String strProcCode, String strAmount, String strProcessingCode, String strClearPIN, String strPAN, String strExpiryDate, String strTerminalSerial, String strField35, String strField37, String strPhoneNumber, String strDebitAccount, String strCreditAccount, String strField68) { try {//from w w w. j av a2s .c o m PinBlock pin = new PinBlock(); String response; String STAN = "" + GetSequenceNumber(); String strPINBlock = pin.pinProcess(strClearPIN, trimLeftString(strPAN), PIN_VERIFICATION_ENCRYPT_KEYS); // String strPINBlock = generatePINBlock.DESEncrypt(strClearPIN, trimLeftString(strPAN), PIN_VERIFICATION_ENCRYPT_KEYS); String Track2Data = trimLeftString(strField35); String cardSequenceNumber = null; if (Track2Data != null && Track2Data.length() >= 3) { cardSequenceNumber = Track2Data.substring(Track2Data.length() - 3); } HashMap<String, String> data = new HashMap<String, String>(); data.put("MTI", "0200"); // Message Type data.put("2", trimLeftString(strPAN)); // Primary Account Number (PAN) data.put("3", "320000");//Processing code data.put("4", "000000000000");//Amount data.put("7", (new SimpleDateFormat("MMddHHmmss")).format(new java.util.Date())); // Valuedate data.put("11", STAN); // Transaction Unique Reference (STAN) data.put("12", (new SimpleDateFormat("hhmmss")).format(new java.util.Date())); // Time, local transaction data.put("13", (new SimpleDateFormat("MMdd")).format(new java.util.Date())); //Local Transaction Date data.put("14", strExpiryDate);// Card Expiry date data.put("15", (new SimpleDateFormat("MMdd")).format(new java.util.Date()));//Settlement date data.put("22", "902");//POS Entry Mode data.put("23", cardSequenceNumber);//Card Sequence Number data.put("25", "00");//POS Condition Mode data.put("26", "12");//POS Entry Mode data.put("28", "C00000000");//Amount, Transaction Fee data.put("30", "C00000000");//Amount, Transaction Processing Fee data.put("32", "639673");//Acquiring institution code(BIN) data.put("35", trimLeftString(strField35));//TRACK2 DATA data.put("37", strField37);//Retrieval Reference Number data.put("41", "22310001");//Card Acceptor terminal ID data.put("42", "TPDF ");// Card Acceptor ID code data.put("43", "NMB House Test Dar Es Salaam TZ");// Card Acceptor terminal ID data.put("49", "834");// Currency Code data.put("52", strPINBlock);// PIN BLOCK data.put("56", "1510");// Message reason code data.put("59", PadZeros(10, STAN));// Echo Data data.put("123", "21010121014C101");// POS Data Code String requestISO = iso.CreateISO(data); requestISO = requestISO.replace(strPINBlock, new String(HexString2Bytes(strPINBlock), "ISO8859_1")); String header = (new DataConversions()).IntegertoASCII(requestISO.length()); requestISO = header + requestISO; if (ISO8583Adaptor.isConnectedClient) { ClientSocketHandler.chEv.getChannel().write(requestISO); // Mask the PAN [replace PAN,Pin Block data during logging] String strnewpan = strPAN; strnewpan = strnewpan.replace(strPAN.substring(6, 14), "xxxxxxxxxxxxxx"); String strField_35 = strField35.replace(strField35.substring(6, 32), "xxxxxxxxxxxxxxxxxxxxxxxxx"); data.remove("2"); data.remove("52"); data.remove("35"); data.put("2", strnewpan); data.put("35", strField_35); data.put("52", "*********************************"); // Save map details on the OuterHashMap Collection data.put("88", strNarration); data.remove("3"); data.put("3", strProcessingCode); data.put("4", strAmount); data.put("88", strNarration); data.put("65", strReferenceNo); data.put("68", strField68); data.put("100", strProcCode); data.put("102", strDebitAccount); data.put("103", strCreditAccount); data.put("104", strTerminalSerial); data.put("PhoneNumber", strPhoneNumber); data.put("timestamp", this.anyDate("")); OuterHoldingQueue.put(strField37, data); } else { String strMessageToPOS = ""; System.out.println("Message Failed to be Sent Postilion"); String strnewpan = strPAN; strnewpan = strnewpan.replace(strPAN.substring(6, 14), "xxxxxxxxxxxxxx"); String strField_35 = strField35.replace(strField35.substring(6, 32), "xxxxxxxxxxxxxxxxxxxxxxxxx"); data.remove("2"); data.remove("52"); data.remove("35"); data.put("2", strnewpan); data.put("39", "Failed Connecting to Postilion"); data.put("52", "*********************************"); data.put("35", strField_35); data.put("timestamp", this.anyDate("")); strMessageToPOS += this.strResponseHeader(strField68) + "#"; strMessageToPOS += "AGENT ID: " + strTerminalSerial.toString() + "#"; strMessageToPOS += "TRAN NUM: " + strField37 + "#"; strMessageToPOS += "--------------------------------" + "#"; strMessageToPOS += " " + "#"; strMessageToPOS += " PIN VERIFICATION " + "#"; strMessageToPOS += " " + "#"; strMessageToPOS += " FAILED CONNECTING TO POSTILION " + "#"; strMessageToPOS += " " + "#"; strMessageToPOS += this.strResponseFooter(strTerminalSerial.toString()) + "#"; SendPOSResponse(strMessageToPOS, strField37); } /* data.put("39", "00"); if (strDebitAccount.isEmpty() || strDebitAccount == null) { strDebitAccount = "20201200003"; } data.put("88", strNarration); data.remove("3"); data.put("3", strProcessingCode); data.put("4", strAmount); data.put("88", strNarration); data.put("65", strReferenceNo); data.put("100", strProcCode); data.put("102", strDebitAccount); data.put("103", strCreditAccount); data.put("104", strTerminalSerial); data.put("PhoneNumber", strPhoneNumber); data.put("timestamp", this.anyDate("")); OuterHoldingQueue.put(strField37, data); getSwitchResponse(data); */ this.log(data.toString() + "\n\n", "PinVerification"); } catch (Exception ex) { this.log("Error on Function PIN_Verify() " + ex.getMessage() + "\n" + this.StackTraceWriter(ex), "ERROR"); return ""; } return ""; }
From source file:au.org.theark.core.dao.StudyDao.java
/**This method modified on 2016-05-25. Due to "java.util.ConcurrentModificationException". The rule is "You may not modify (add or remove elements from the list) while iterating over it using an Iterator (which happens when you use a for-each loop)". JavaDocs: The iterators returned by this class's iterator and listIterator methods are fail-fast: if the list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Hence if you want to modify the list (or any collection in general), use iterator, because then it is aware of the modifications and hence those will be handled properly. @param study @param allTheData @param biospecimenIdsAfterFiltering @param biocollectionIds @param idsAfterFiltering *///from www . ja v a 2s. c o m private void wipeBiospecimenDataNotMatchingThisList(Study study, DataExtractionVO allTheData, List<Long> biospecimenIdsAfterFiltering, List<Long> biocollectionIds, List<Long> idsAfterFiltering) { HashMap<String, ExtractionVO> data = allTheData.getBiospecimenData(); Collection<String> uidsInData = data.keySet(); Collection<String> uidsToDelete = getBiospecimenUIDsNotMatchingTheseBiospecimenIdsOrSubjectIds(study, uidsInData, biospecimenIdsAfterFiltering, biocollectionIds, idsAfterFiltering); Collection<String> uidsToDeleteCopy = new ArrayList<String>(uidsToDelete); //This is an exact copy of the array so ConcurrentModificationException can not be thrown. for (String uid : uidsToDeleteCopy) { log.info("wipeBiospecimenDataNotMatchingThisList: removed biospecimen uid = " + uid); data.remove(uid); } }
From source file:au.org.theark.core.dao.StudyDao.java
private void wipeBiocollectionDataNotMatchThisList(Study study, DataExtractionVO allTheData, List<Long> bioCollectionIdsAfterFiltering, List<Long> subjectIds, List<Long> biospecimenIds, List<QueryFilter> biospecimenQueryFilters) { HashMap<String, ExtractionVO> data = allTheData.getBiocollectionData(); HashMap<String, ExtractionVO> customData = allTheData.getBiocollectionCustomData(); Collection<String> uidsInData = new HashSet(data.keySet()); Collection<String> uidsToDelete = (Collection<String>) new HashSet(); uidsToDelete = getBioCollectionUIDsNotMatchingTheseBioCollectionIdsOrSubjectIds(study, uidsInData, bioCollectionIdsAfterFiltering, subjectIds, biospecimenIds, biospecimenQueryFilters); for (String uid : uidsToDelete) { log.info("wipeBioCollectionDataNotMatchingThisList: removed bioCollection uid = " + uid); data.remove(uid); customData.remove(uid);/*ww w . j a v a 2s .com*/ } log.info("what is left in data?" + data); }
From source file:org.akaza.openclinica.control.submit.DataEntryServlet.java
protected boolean unloadFiles(HashMap<String, String> newUploadedFiles) { boolean success = true; Iterator iter = newUploadedFiles.keySet().iterator(); while (iter.hasNext()) { String itemId = (String) iter.next(); String filename = newUploadedFiles.get(itemId); File f = new File(filename); if (f.exists()) { if (f.delete()) { newUploadedFiles.remove("filename"); } else { success = false;/*from www. j a va 2 s. co m*/ } } else { newUploadedFiles.remove("filename"); // success = false; } } return success; }
From source file:org.geotools.xml.impl.BindingPropertyExtractor.java
public List properties(Object object, XSDElementDeclaration element) { List properties = new ArrayList(); //first get all the properties that can be infered from teh schema List children = encoder.getSchemaIndex().getChildElementParticles(element); O: for (Iterator itr = children.iterator(); itr.hasNext();) { XSDParticle particle = (XSDParticle) itr.next(); XSDElementDeclaration child = (XSDElementDeclaration) particle.getContent(); if (child.isElementDeclarationReference()) { child = child.getResolvedElementDeclaration(); }/*ww w.jav a 2 s . c o m*/ //get the object(s) for this element GetPropertyExecutor executor = new GetPropertyExecutor(object, child); BindingVisitorDispatch.walk(object, encoder.getBindingWalker(), element, executor, context); if (executor.getChildObject() != null) { properties.add(new Object[] { particle, executor.getChildObject() }); } } //second, get the properties which cannot be infereed from the schema GetPropertiesExecutor executor = new GetPropertiesExecutor(object, element); BindingVisitorDispatch.walk(object, encoder.getBindingWalker(), element, executor, context); if (!executor.getProperties().isEmpty()) { //group into a map of name, list MultiHashMap map = new MultiHashMap(); for (Iterator p = executor.getProperties().iterator(); p.hasNext();) { Object[] property = (Object[]) p.next(); map.put(property[0], property[1]); } //turn each map entry into a particle HashMap particles = new HashMap(); for (Iterator e = map.entrySet().iterator(); e.hasNext();) { Map.Entry entry = (Map.Entry) e.next(); //key could be a name or a particle if (entry.getKey() instanceof XSDParticle) { XSDParticle particle = (XSDParticle) entry.getKey(); particles.put(Schemas.getParticleName(particle), particle); continue; } QName name = (QName) entry.getKey(); Collection values = (Collection) entry.getValue(); //check for comment if (Encoder.COMMENT.equals(name)) { //create a dom element which text nodes for the comments Element comment = encoder.getDocument().createElement(Encoder.COMMENT.getLocalPart()); for (Iterator v = values.iterator(); v.hasNext();) { comment.appendChild(encoder.getDocument().createTextNode(v.next().toString())); } XSDParticle particle = XSDFactory.eINSTANCE.createXSDParticle(); XSDElementDeclaration elementDecl = XSDFactory.eINSTANCE.createXSDElementDeclaration(); elementDecl.setTargetNamespace(Encoder.COMMENT.getNamespaceURI()); elementDecl.setName(Encoder.COMMENT.getLocalPart()); elementDecl.setElement(comment); particle.setContent(elementDecl); particles.put(name, particle); continue; } //find hte element XSDElementDeclaration elementDecl = encoder.getSchemaIndex().getElementDeclaration(name); if (elementDecl == null) { //look for the element declaration as a particle of the containing type XSDParticle particle = Schemas.getChildElementParticle(element.getType(), name.getLocalPart(), true); if (particle != null) { particles.put(name, particle); continue; } } if (elementDecl == null) { //TODO: resolving like this will return an element no // matter what, modifying the underlying schema, this might // be dangerous. What we shold do is force the schema to // resolve all of it simports when the encoder starts elementDecl = encoder.getSchema().resolveElementDeclaration(name.getNamespaceURI(), name.getLocalPart()); } //look for a particle in the containing type which is either // a) a base type of the element // b) in the same subsittuion group // if found use the particle to dervice multiplicity XSDParticle reference = null; for (Iterator p = Schemas.getChildElementParticles(element.getType(), true).iterator(); p .hasNext();) { XSDParticle particle = (XSDParticle) p.next(); XSDElementDeclaration el = (XSDElementDeclaration) particle.getContent(); if (el.isElementDeclarationReference()) { el = el.getResolvedElementDeclaration(); } if (Schemas.isBaseType(elementDecl, el)) { reference = particle; break; } } //wrap the property in a particle XSDParticle particle = XSDFactory.eINSTANCE.createXSDParticle(); XSDElementDeclaration wrapper = XSDFactory.eINSTANCE.createXSDElementDeclaration(); wrapper.setResolvedElementDeclaration(elementDecl); particle.setContent(wrapper); //particle.setContent(elementDecl); //if there is a reference, derive multiplicity if (reference != null) { particle.setMaxOccurs(reference.getMaxOccurs()); } else { //dervice from collection if (values.size() > 1) { //make a multi property particle.setMaxOccurs(-1); } else { //single property particle.setMaxOccurs(1); } } particles.put(name, particle); } //process the particles in order in which we got the properties for (Iterator p = executor.getProperties().iterator(); p.hasNext();) { Object[] property = (Object[]) p.next(); Collection values = (Collection) map.get(property[0]); QName name; if (property[0] instanceof XSDParticle) { name = Schemas.getParticleName((XSDParticle) property[0]); } else { name = (QName) property[0]; } XSDParticle particle = (XSDParticle) particles.get(name); if (particle == null) { continue; //already processed, must be a multi property } if (values.size() > 1) { //add as is, the encoder will unwrap properties.add(new Object[] { particle, values }); } else { //unwrap it properties.add(new Object[] { particle, values.iterator().next() }); } //done with this particle particles.remove(name); } } //return properties; if (properties.size() <= 1) { return properties; } /* feature properties in the "properties" list may not be in the same order as they appear in the schema, because in the above implementation, simple attributes and complex attributes are processed separately. to maintain the feature properties order, sort the properties to their original order as in "children" list */ if (object instanceof ComplexAttributeImpl && propertiesSortable(properties, children)) { List sortedProperties = new ArrayList(); //sort properties according to their XSDParticle order in "children" for (int i = 0; i < children.size(); i++) { XSDParticle particle = (XSDParticle) children.get(i); XSDElementDeclaration child = (XSDElementDeclaration) particle.getContent(); if (child.getResolvedElementDeclaration() != null) { child = child.getResolvedElementDeclaration(); } for (Iterator itr = properties.iterator(); itr.hasNext();) { Object[] prop = (Object[]) itr.next(); XSDParticle part = (XSDParticle) prop[0]; XSDElementDeclaration partContent = (XSDElementDeclaration) part.getContent(); if (partContent.getResolvedElementDeclaration() != null) { partContent = partContent.getResolvedElementDeclaration(); } if (child.getName().equals(partContent.getName()) && ((child.getTargetNamespace() != null && partContent.getTargetNamespace() != null) ? child.getTargetNamespace().equals(partContent.getTargetNamespace()) : true)) { sortedProperties.add(prop); properties.remove(prop); i--; break; } } } //return properties in order they appear in the schema return sortedProperties; } else { return properties; } }
From source file:com.MainFiles.Functions.java
public HashMap getESBResponse(String strAgentID, String cardNumber, String processingCode, String amount, String referenceNumber, String narration, String transactionIdentifier, String strAccountNumber, String creditAccount, String strField65, String Phonenumber, String strField68) throws InterruptedException { String response = ""; String strField_02 = ""; String strField_00 = ""; String strFieldPRD = ""; String strProcessingCode = ""; String strMessageToPOS = ""; String STAN = "" + GetSequenceNumber(); try {/*from w w w .j a v a 2 s . c o m*/ if (Phonenumber.toString().trim().equals("") || Phonenumber.toString().trim() == null) { strField_02 = cardNumber; } else { strField_02 = "255" + Phonenumber.substring(Phonenumber.length() - 9); } switch (processingCode) { case "120000": // MERCHANT PAYMENTS strProcessingCode = "400000"; strField_00 = "0200"; strFieldPRD = "AGMP"; narration = "PAYMENT OF GOODS AND SERVICES FOR " + strAccountNumber; break; case "310000":// BALANCE ENQUIRY strProcessingCode = processingCode; strField_00 = "0200"; narration = "BALANCE ENQUIRY FOR ACCOUNT " + strAccountNumber; break; case "300000": // AGENT FLOAT (we do BI for Agent float) strProcessingCode = "310000"; strField_00 = "0200"; strFieldPRD = "FLBI"; narration = "AGENT FLOAT FOR ACCOUNT " + strAccountNumber; break; case "380000": //MINI STATEMENT strProcessingCode = processingCode; strField_00 = "0200"; narration = "MINI STATEMENT FOR ACCOUNT " + strAccountNumber; break; case "340000": // CARD ACTIVATION strProcessingCode = processingCode; strField_00 = "0100"; break; case "010000": // CASH WITHDRAWAL strProcessingCode = processingCode; strFieldPRD = "CHWL"; strField_00 = "0200"; narration = "CASH WITHDRAWAL FOR ACCOUNT " + strAccountNumber; break; case "500000": // BILL PAYMENTS strProcessingCode = processingCode; strFieldPRD = ""; strField_00 = "0200"; break; case "400000": // FUNDS TRANSFER strProcessingCode = processingCode; strFieldPRD = "AGFT"; strField_00 = "0200"; narration = "FUNDS TRANSFER FOR ACCOUNT " + strAccountNumber; break; case "210000": // CASH DEPOSIT strProcessingCode = processingCode; strFieldPRD = "CHDP"; strField_00 = "0200"; break; case "420000": // TOPUPS strField_00 = "0200"; strField65 = strField_02; strProcessingCode = processingCode; break; default: strField_00 = "0200"; strProcessingCode = processingCode; break; } Map<String, String> ISOdetails = new HashMap<>(); ISOdetails.put("0", strField_00); ISOdetails.put("2", strField_02); ISOdetails.put("3", strProcessingCode); ISOdetails.put("4", amount); ISOdetails.put("7", this.anyDate("MMddHHmmss")); ISOdetails.put("11", STAN); ISOdetails.put("32", SOURCE_ID); ISOdetails.put("37", referenceNumber); ISOdetails.put("65", strField65); ISOdetails.put("66", getTerminalID(strField68)); ISOdetails.put("68", strField68); ISOdetails.put("88", narration); ISOdetails.put("100", transactionIdentifier); ISOdetails.put("102", strAccountNumber); ISOdetails.put("103", creditAccount); ISOdetails.put("104", strAgentID); ISOdetails.put("CorrelationID", referenceNumber); ISOdetails.put("PRD", strFieldPRD); ISOdetails.put("HASH", sendTransactionHash(strAgentID, strField68).toLowerCase()); this.log("REQUEST :: " + referenceNumber + "\n" + ISOdetails.toString() + "\n\n", "ESB_Request"); boolean sentToWebLogic = false; HashMap ParamsFromAdapter = new HashMap(); QueueWriter queueWriter = new QueueWriter(QUEUE_REQUEST, PROVIDER_URL); int trials = 0; do { sentToWebLogic = queueWriter.sendObject((HashMap) ISOdetails, referenceNumber); trials++; } while (sentToWebLogic == false & trials < 3); if (sentToWebLogic) { long Start = System.currentTimeMillis(); long Stop = Start + (Integer.parseInt(ISO8583Adaptor.ESB_TIMEOUT) * 1000); do { Thread.currentThread().sleep(100); ParamsFromAdapter = this.getWeblogicMessageFromQueue(referenceNumber); } while (ParamsFromAdapter.isEmpty() && System.currentTimeMillis() < Stop); if (ParamsFromAdapter.isEmpty()) { //Excempt for processing code 340000 if (!ISOdetails.get("3").equals("340000")) { //printMsg:No reponse from ESB System.out.println("===================== "); System.out.println("===================== "); System.out.println("ESB Timeout Response at " + (new SimpleDateFormat("MMMM dd,yyyy hh:mm:ss.SSS a zzzz")) .format(new java.util.Date())); System.out.println("LoggedError:CorrelationID:" + referenceNumber + ""); System.out.println("LoggedError:StatusCode:999"); System.out.println("LoggedError:Status Description:Response timeout from ESB Gateway"); //Send Failed Response to POS String TransactionType = getTransactionType(ISOdetails.get("3").toString()); strMessageToPOS += this.strResponseHeader(strField68) + "#"; strMessageToPOS += "AGENT ID: " + ISOdetails.get("104").toString() + "#"; strMessageToPOS += "TRAN NUM: " + ISOdetails.get("37").toString() + "#"; strMessageToPOS += "--------------------------------" + "#"; strMessageToPOS += " " + "#"; strMessageToPOS += padEqual(TransactionType.toUpperCase()) + "#"; strMessageToPOS += " " + "#"; strMessageToPOS += " NO RESPONSE FROM ESB GATEWAY " + "#"; strMessageToPOS += " " + "#"; strMessageToPOS += this.strResponseFooter(ISOdetails.get("104").toString()) + "#"; SendPOSResponse(strMessageToPOS, ISOdetails.get("37").toString()); } } else { switch (processingCode) { case "340000":// For Card Activation Return Array return ParamsFromAdapter; case "300000"://AgentFloat ParamsFromAdapter.remove("3"); ParamsFromAdapter.put("3", "300000"); break; case "120000": ParamsFromAdapter.remove("3"); ParamsFromAdapter.put("3", "120000"); break; default: break; } printScreenMessage(ParamsFromAdapter); response = this.genHashDelimiterString(ParamsFromAdapter, referenceNumber); } } } catch (Exception ex) { this.log("Error on getESBResponse " + ex.getMessage() + "\n" + this.StackTraceWriter(ex), "getESBResponse"); } return null; }
From source file:sh.isaac.convert.rxnorm.standard.RxNormMojo.java
/** * Load relationship metadata.//from w ww . j a v a 2s. c o m * * @throws Exception the exception */ private void loadRelationshipMetadata() throws Exception { ConsoleUtil.println("Creating relationship types"); // Both of these get added as extra attributes on the relationship definition final HashMap<String, ArrayList<String>> snomedCTRelaMappings = new HashMap<>(); // Maps something like 'has_specimen_source_morphology' to '118168003' (may be more than one target SCT code) final HashMap<String, String> snomedCTRelMappings = new HashMap<>(); // Maps something like '118168003' to 'RO' this.nameToRel = new HashMap<>(); Statement s = this.db.getConnection().createStatement(); // get the inverses of first, before the expanded forms ResultSet rs = s.executeQuery("SELECT DOCKEY, VALUE, TYPE, EXPL FROM " + this.tablePrefix + "DOC where DOCKEY ='REL' or DOCKEY = 'RELA' order by TYPE DESC "); while (rs.next()) { final String dockey = rs.getString("DOCKEY"); final String value = rs.getString("VALUE"); final String type = rs.getString("TYPE"); final String expl = rs.getString("EXPL"); if (value == null) { continue; // don't need this one } switch (type) { case "snomedct_rela_mapping": ArrayList<String> targetSCTIDs = snomedCTRelaMappings.get(expl); if (targetSCTIDs == null) { targetSCTIDs = new ArrayList<>(); snomedCTRelaMappings.put(expl, targetSCTIDs); } targetSCTIDs.add(value); break; case "snomedct_rel_mapping": snomedCTRelMappings.put(value, expl); break; default: Relationship rel = this.nameToRel.get(value); if (rel == null) { if (type.endsWith("_inverse")) { rel = this.nameToRel.get(expl); if (rel == null) { rel = new Relationship(dockey.equals("RELA")); this.nameToRel.put(value, rel); this.nameToRel.put(expl, rel); } else { throw new RuntimeException("shouldn't happen due to query order"); } } else { // only cases where there is no inverse rel = new Relationship(dockey.equals("RELA")); this.nameToRel.put(value, rel); } } switch (type) { case "expanded_form": rel.addDescription(value, expl); break; case "rela_inverse": case "rel_inverse": rel.addRelInverse(value, expl); break; default: throw new RuntimeException("Oops"); } break; } } rs.close(); s.close(); final HashSet<String> actuallyUsedRelsOrRelas = new HashSet<>(); for (final Entry<String, ArrayList<String>> x : snomedCTRelaMappings.entrySet()) { if (!this.nameToRel.containsKey(x.getKey())) { // metamorphosys doesn't seem to remove these when the sct rel types aren't included - just silently remove them // unless it seems that they should map. // may_be_a appears to be a bug in RxNorm 2013-12-02. silently ignore... // TODO see if they fix it in the future, make this check version specific? // seems to be getting worse... now it fails to remove 'has_life_circumstance' too in 2014AA, and a few others. // Changing to a warning. ConsoleUtil.printErrorln("Warning - The 'snomedct_rela_mapping' '" + x.getKey() + "' does not have a corresponding REL entry! Skipping"); // if (!x.getKey().equals("may_be_a") && !x.getKey().equals("has_life_circumstance")) // { // throw new RuntimeException("ERROR - No rel for " + x.getKey() + "."); // } x.getValue().forEach((sctId) -> { snomedCTRelMappings.remove(sctId); }); } else { x.getValue().stream().map((sctid) -> { this.nameToRel.get(x.getKey()).addSnomedCode(x.getKey(), sctid); return sctid; }).map((sctid) -> snomedCTRelMappings.remove(sctid)).filter((relType) -> (relType != null)) .map((relType) -> { this.nameToRel.get(x.getKey()).addRelType(x.getKey(), relType); return relType; }).forEachOrdered((relType) -> { // Shouldn't need this, but there are some cases where the metadata is inconsistent - with how it is actually used. actuallyUsedRelsOrRelas.add(relType); }); } } if (snomedCTRelMappings.size() > 0) { snomedCTRelMappings.entrySet().forEach((x) -> { ConsoleUtil.printErrorln(x.getKey() + ":" + x.getValue()); }); throw new RuntimeException("oops - still have (things listed above)"); } this.ptRelationships = new BPT_Relations(rxNormName) { }; this.ptRelationships.indexByAltNames(); this.ptAssociations = new BPT_Associations() { }; this.ptAssociations.indexByAltNames(); s = this.db.getConnection().createStatement(); rs = s.executeQuery("select distinct REL, RELA from " + this.tablePrefix + "REL where " + createSabQueryPart("", this.linkSnomedCT)); while (rs.next()) { actuallyUsedRelsOrRelas.add(rs.getString("REL")); if (rs.getString("RELA") != null) { actuallyUsedRelsOrRelas.add(rs.getString("RELA")); } } rs.close(); s.close(); final HashSet<Relationship> uniqueRels = new HashSet<>(this.nameToRel.values()); // Sort the generic relationships first, these are needed when processing primary final ArrayList<Relationship> sortedRels = new ArrayList<>(uniqueRels); Collections.sort(sortedRels, (o1, o2) -> { if (o1.getIsRela() && !o2.getIsRela()) { return 1; } if (o2.getIsRela() && !o1.getIsRela()) { return -1; } return 0; }); for (final Relationship r : sortedRels) { r.setSwap(this.db.getConnection(), this.tablePrefix); if (!actuallyUsedRelsOrRelas.contains(r.getFQName()) && !actuallyUsedRelsOrRelas.contains(r.getInverseFQName())) { continue; } Property p = null; final Boolean relTypeMap = this.mapToIsa.get(r.getFQName()); if (relTypeMap != null) // true or false, make it a rel { p = new Property(((r.getAltName() == null) ? r.getFQName() : r.getAltName()), ((r.getAltName() == null) ? null : r.getFQName()), r.getDescription(), MetaData.IS_A____SOLOR.getPrimordialUuid()); // map to isA this.ptRelationships.addProperty(p); // conveniently, the only thing we will treat as relationships are things mapped to isa. } if ((relTypeMap == null) || (relTypeMap == false)) // don't make it an association if set to true { p = new PropertyAssociation(null, ((r.getAltName() == null) ? r.getFQName() : r.getAltName()), ((r.getAltName() == null) ? null : r.getFQName()), ((r.getInverseAltName() == null) ? r.getInverseFQName() : r.getInverseAltName()), r.getDescription(), false); this.ptAssociations.addProperty(p); } final ComponentReference cr = ComponentReference.fromConcept(p.getUUID()); // associations already handle inverse names if (!(p instanceof PropertyAssociation) && (r.getInverseFQName() != null)) { this.importUtil.addDescription(cr, ((r.getInverseAltName() == null) ? r.getInverseFQName() : r.getInverseAltName()), DescriptionType.FULLY_QUALIFIED_NAME, false, this.ptDescriptions.getProperty("Inverse FQN").getUUID(), Status.ACTIVE); } if (r.getAltName() != null) { // Need to create this UUID to be different than forward name, in case forward and reverse are identical (like 'RO') final UUID descUUID = ConverterUUID.createNamespaceUUIDFromStrings( cr.getPrimordialUuid().toString(), r.getInverseFQName(), DescriptionType.REGULAR_NAME.name(), "false", "inverse"); // Yes, this looks funny, no its not a copy/paste error. We swap the FULLY_QUALIFIED_NAME and alt names for... it a long story. 42. this.importUtil.addDescription(cr, descUUID, r.getInverseFQName(), DescriptionType.REGULAR_NAME, false, null, null, null, null, this.ptDescriptions.getProperty("Inverse Synonym").getUUID(), Status.ACTIVE, null); } if (r.getInverseDescription() != null) { this.importUtil.addDescription(cr, r.getInverseDescription(), DescriptionType.DEFINITION, true, this.ptDescriptions.getProperty("Inverse Description").getUUID(), Status.ACTIVE); } if (r.getRelType() != null) { final Relationship generalRel = this.nameToRel.get(r.getRelType()); this.importUtil.addUUIDAnnotation(cr, (this.mapToIsa.containsKey(generalRel.getFQName()) ? this.ptRelationships.getProperty(generalRel.getFQName()) : this.ptAssociations.getProperty(generalRel.getFQName())).getUUID(), this.ptRelationshipMetadata.getProperty("General Rel Type").getUUID()); } if (r.getInverseRelType() != null) { final Relationship generalRel = this.nameToRel.get(r.getInverseRelType()); this.importUtil.addUUIDAnnotation(cr, (this.mapToIsa.containsKey(generalRel.getFQName()) ? this.ptRelationships.getProperty(generalRel.getFQName()) : this.ptAssociations.getProperty(generalRel.getFQName())).getUUID(), this.ptRelationshipMetadata.getProperty("Inverse General Rel Type").getUUID()); } r.getRelSnomedCode().forEach((sctCode) -> { this.importUtil.addUUIDAnnotation(cr, UuidT3Generator.fromSNOMED(sctCode), this.ptRelationshipMetadata.getProperty("Snomed Code").getUUID()); }); r.getInverseRelSnomedCode().forEach((sctCode) -> { this.importUtil.addUUIDAnnotation(cr, UuidT3Generator.fromSNOMED(sctCode), this.ptRelationshipMetadata.getProperty("Inverse Snomed Code").getUUID()); }); } if (this.ptRelationships.getProperties().size() > 0) { this.importUtil.loadMetaDataItems(this.ptRelationships, this.metaDataRoot.getPrimordialUuid()); } if (this.ptAssociations.getProperties().size() > 0) { this.importUtil.loadMetaDataItems(this.ptAssociations, this.metaDataRoot.getPrimordialUuid()); } }