List of usage examples for java.util HashSet toArray
<T> T[] toArray(T[] a);
From source file:uk.bl.wa.parsers.StanfordAnnotatorParser.java
/** * /*www . j a va 2s. com*/ * @param text * @param metadata */ public void parse(String text, Metadata metadata) { // create an empty Annotation just with the given text Annotation document = new Annotation(text); // run all Annotators on this text pipeline.annotate(document); // these are all the sentences in this document // a CoreMap is essentially a Map that uses class objects as keys and has values with custom types List<CoreMap> sentences = document.get(SentencesAnnotation.class); // Loop over and extract: boolean inEntity = false; String currentEntity = ""; String currentEntityType = ""; HashSet<String> persons = new HashSet<String>(); HashSet<String> orgs = new HashSet<String>(); HashSet<String> locations = new HashSet<String>(); HashSet<String> dates = new HashSet<String>(); HashSet<String> miscs = new HashSet<String>(); double totalSentiment = 0; double totalSentences = 0; int[] sentiments = new int[5]; for (CoreMap sentence : sentences) { Tree tree = sentence.get(SentimentCoreAnnotations.AnnotatedTree.class); int sentiment = RNNCoreAnnotations.getPredictedClass(tree); totalSentiment += sentiment; totalSentences++; // Also store as a histogram: sentiments[sentiment]++; // traversing the words in the current sentence // a CoreLabel is a CoreMap with additional token-specific methods for (CoreLabel token : sentence.get(TokensAnnotation.class)) { // this is the text of the token //String word = token.get(TextAnnotation.class); // this is the POS tag of the token //String pos = token.get(PartOfSpeechAnnotation.class); // this is the NER label of the token String ne = token.get(NamedEntityTagAnnotation.class); if (!inEntity) { if (!"O".equals(ne)) { inEntity = true; currentEntity = ""; currentEntityType = ne; } } if (inEntity) { if ("O".equals(ne)) { inEntity = false; if ("PERSON".equals(currentEntityType)) { persons.add(currentEntity.trim()); } else if ("ORGANIZATION".equals(currentEntityType)) { orgs.add(currentEntity.trim()); } else if ("LOCATION".equals(currentEntityType)) { locations.add(currentEntity.trim()); } else if ("DATE".equals(currentEntityType)) { dates.add(currentEntity.trim()); } else if ("MISC".equals(currentEntityType)) { miscs.add(currentEntity.trim()); } else if ("NUMBER".equals(currentEntityType)) { // Ignore numbers. } else { System.err.println("Entity type " + currentEntityType + " for token " + token + " cannot be handled by this parser!"); } } else { currentEntity += " " + token; } } } } // Now store them: metadata.set(NER_PERSONS, persons.toArray(new String[0])); metadata.set(NER_ORGANISATIONS, orgs.toArray(new String[0])); metadata.set(NER_LOCATIONS, locations.toArray(new String[0])); metadata.set(NER_DATES, dates.toArray(new String[0])); metadata.set(NER_MISC, miscs.toArray(new String[0])); // And calculate and store the rounded average sentiment: metadata.set(AVG_SENTIMENT, (int) Math.round(totalSentiment / totalSentences)); // Convert sentiment distribution: String[] sentiment_dist = new String[5]; for (int i = 0; i < 5; i++) sentiment_dist[i] = "" + sentiments[i]; metadata.set(SENTIMENT_DIST, sentiment_dist); }
From source file:uk.bl.wa.nlp.parsers.StanfordAnnotatorParser.java
/** * /*from w w w . j a v a 2s . c o m*/ * @param text * @param metadata */ public void parse(String text, Metadata metadata) { // create an empty Annotation just with the given text Annotation document = new Annotation(text); // run all Annotators on this text pipeline.annotate(document); // these are all the sentences in this document // a CoreMap is essentially a Map that uses class objects as keys and has values with custom types List<CoreMap> sentences = document.get(SentencesAnnotation.class); // Loop over and extract: boolean inEntity = false; String currentEntity = ""; String currentEntityType = ""; HashSet<String> persons = new HashSet<String>(); HashSet<String> orgs = new HashSet<String>(); HashSet<String> locations = new HashSet<String>(); HashSet<String> dates = new HashSet<String>(); HashSet<String> miscs = new HashSet<String>(); double totalSentiment = 0; double totalSentences = 0; int[] sentiments = new int[5]; for (CoreMap sentence : sentences) { // REQUIRES LATER VERSION OF PARSER (Java 8) // Tree tree = sentence.get(SentimentAnnotatedTree.class); // int sentiment = RNNCoreAnnotations.getPredictedClass(tree); // totalSentiment += sentiment; // totalSentences++; // // Also store as a histogram: // sentiments[sentiment]++; // traversing the words in the current sentence // a CoreLabel is a CoreMap with additional token-specific methods for (CoreLabel token : sentence.get(TokensAnnotation.class)) { // this is the text of the token //String word = token.get(TextAnnotation.class); // this is the POS tag of the token //String pos = token.get(PartOfSpeechAnnotation.class); // this is the NER label of the token String ne = token.get(NamedEntityTagAnnotation.class); if (!inEntity) { if (!"O".equals(ne)) { inEntity = true; currentEntity = ""; currentEntityType = ne; } } if (inEntity) { if ("O".equals(ne)) { inEntity = false; if ("PERSON".equals(currentEntityType)) { persons.add(currentEntity.trim()); } else if ("ORGANIZATION".equals(currentEntityType)) { orgs.add(currentEntity.trim()); } else if ("LOCATION".equals(currentEntityType)) { locations.add(currentEntity.trim()); } else if ("DATE".equals(currentEntityType)) { dates.add(currentEntity.trim()); } else if ("MISC".equals(currentEntityType)) { miscs.add(currentEntity.trim()); } else if ("NUMBER".equals(currentEntityType)) { // Ignore numbers. } else { System.err.println("Entity type " + currentEntityType + " for token " + token + " cannot be handled by this parser!"); } } else { currentEntity += " " + token.toString(OutputFormat.VALUE); } } } } // Now store them: metadata.set(NER_PERSONS, persons.toArray(new String[0])); metadata.set(NER_ORGANISATIONS, orgs.toArray(new String[0])); metadata.set(NER_LOCATIONS, locations.toArray(new String[0])); metadata.set(NER_DATES, dates.toArray(new String[0])); metadata.set(NER_MISC, miscs.toArray(new String[0])); // And calculate and store the rounded average sentiment: metadata.set(AVG_SENTIMENT, (int) Math.round(totalSentiment / totalSentences)); // Convert sentiment distribution: // String[] sentiment_dist = new String[5]; // for( int i = 0; i < 5; i++ ) sentiment_dist[i] = ""+sentiments[i]; // metadata.set( SENTIMENT_DIST, sentiment_dist); }
From source file:org.rhq.enterprise.server.resource.ResourceManagerBean.java
public Map<Integer, String> getResourcesAncestry(Subject subject, Integer[] resourceIds, ResourceAncestryFormat format) { Map<Integer, String> result = new HashMap<Integer, String>(resourceIds.length); if (resourceIds.length == 0) { return result; }/* w w w.j ava2 s. co m*/ ResourceCriteria resourceCriteria = new ResourceCriteria(); resourceCriteria.addFilterIds(resourceIds); resourceCriteria.fetchResourceType(true); List<Resource> resources = findResourcesByCriteria(subject, resourceCriteria); if (ResourceAncestryFormat.RAW == format) { for (Resource resource : resources) { result.put(resource.getId(), resource.getAncestry()); } return result; } HashSet<Integer> typesSet = new HashSet<Integer>(); HashSet<String> ancestries = new HashSet<String>(); for (Resource resource : resources) { ResourceType type = resource.getResourceType(); if (type != null) { typesSet.add(type.getId()); } ancestries.add(resource.getAncestry()); } // In addition to the types of the result resources, get the types of their ancestry typesSet.addAll(getAncestryTypeIds(ancestries)); ResourceTypeCriteria resourceTypeCriteria = new ResourceTypeCriteria(); resourceTypeCriteria.addFilterIds(typesSet.toArray(new Integer[typesSet.size()])); List<ResourceType> types = typeManager.findResourceTypesByCriteria(subject, resourceTypeCriteria); for (Resource resource : resources) { String decodedAncestry = getDecodedAncestry(resource, types, format); result.put(resource.getId(), decodedAncestry); } return result; }
From source file:de.interactive_instruments.ShapeChange.Options.java
/** This returns the names of all parms whose names match a regex pattern */ public String[] parameterNamesByRegex(String t, String regex) { HashSet<String> pnames = new HashSet<String>(); int lt2 = t.length() + 2; for (Entry<String, String> e : fParameters.entrySet()) { String key = e.getKey();/*from www . j a v a2 s . c o m*/ if (key.startsWith(t + "::")) { if (Pattern.matches(regex, key.substring(lt2))) pnames.add(key.substring(lt2)); } } return pnames.toArray(new String[0]); }
From source file:sh.isaac.convert.rxnorm.standard.RxNormMojo.java
/** * Process CUI rows.//from w ww . j a v a2 s. c o m * * @param conceptData the concept data * @throws IOException Signals that an I/O exception has occurred. * @throws SQLException the SQL exception * @throws PropertyVetoException the property veto exception */ private void processCUIRows(ArrayList<RXNCONSO> conceptData) throws IOException, SQLException, PropertyVetoException { final String rxCui = conceptData.get(0).rxcui; final HashSet<String> uniqueTTYs = new HashSet<>(); final HashSet<String> uniqueSABs = new HashSet<>(); // ensure all the same CUI, gather the TTYs involved conceptData.stream().map((row) -> { uniqueTTYs.add(row.tty); return row; }).map((row) -> { uniqueSABs.add(row.sab); return row; }).filter((row) -> (!row.rxcui.equals(rxCui))).forEachOrdered((_item) -> { throw new RuntimeException("Oops"); }); ComponentReference cuiConcept; if ((uniqueSABs.size() == 1) && uniqueSABs.iterator().next().equals(this.sctSab)) { // This is a SCT only concept - we don't want to create it. But we might need to put some relationships or associations here. final String sctId = conceptData.get(0).code; if (sctId == null) { throw new RuntimeException("Unexpected"); } cuiConcept = ComponentReference.fromConcept(this.sctIdToUUID.get(sctId)); // Add the RxCUI UUID this.importUtil.addUUID(cuiConcept.getPrimordialUuid(), createCUIConceptUUID(rxCui)); // TODO need to look at what else I should be grabbing - the RXCUI for example should be attached. What else? } else { // just creating the reference here, with the UUID - because we don't know if it should be active or inactive yet. // create the real concept later. cuiConcept = ComponentReference.fromConcept(createCUIConceptUUID(rxCui)); long conceptTime = Integer.MAX_VALUE; // Activate the concept if any description is active Status conceptState = Status.INACTIVE; this.importUtil.addStringAnnotation(cuiConcept, rxCui, this.ptUMLSAttributes.getProperty("RXCUI").getUUID(), Status.ACTIVE); final ArrayList<ValuePropertyPairWithSAB> cuiDescriptions = new ArrayList<>(); final HashSet<String> sabs = new HashSet<>(); for (final RXNCONSO atom : conceptData) { if (atom.sab.equals(this.sctSab)) { continue; } // Add attributes from SAT table this.descSat.clearParameters(); this.descSat.setString(1, rxCui); this.descSat.setString(2, atom.rxaui); final ArrayList<RXNSAT> satData; boolean disableDescription; Long descriptionTime; try (ResultSet rs = this.descSat.executeQuery()) { satData = new ArrayList<>(); disableDescription = false; descriptionTime = null; while (rs.next()) { final RXNSAT current = new RXNSAT(rs); satData.add(current); if ("RXN_OBSOLETED".equals(current.atn)) { disableDescription = true; } if ("RXN_ACTIVATED".equals(current.atn)) { try { final long time = this.dateParse.parse(current.atv).getTime(); descriptionTime = time; if (time < conceptTime) { conceptTime = time; } } catch (final ParseException e) { throw new RuntimeException("Can't parse date?"); } } } } final ValuePropertyPairWithSAB desc = new ValuePropertyPairWithSAB(atom.str, this.ptDescriptions.getProperty(atom.tty), atom.sab, satData); if (disableDescription) { desc.setDisabled(true); } else { // if any description is active, concept is still active conceptState = Status.ACTIVE; } if (descriptionTime != null) { desc.setTime(descriptionTime); } desc.setUUID(ConverterUUID.createNamespaceUUIDFromStrings(cuiConcept.getPrimordialUuid().toString(), atom.rxaui)); // used for sorting description to figure out what to use for FULLY_QUALIFIED_NAME cuiDescriptions.add(desc); desc.addStringAttribute(this.ptUMLSAttributes.getProperty("RXAUI").getUUID(), atom.rxaui); desc.addUUIDAttribute(this.ptUMLSAttributes.getProperty("SAB").getUUID(), this.ptSABs.getProperty(atom.sab).getUUID()); if (StringUtils.isNotBlank(atom.code) && !atom.code.equals("NOCODE")) { desc.addStringAttribute(this.ptUMLSAttributes.getProperty("CODE").getUUID(), atom.code); } if (StringUtils.isNotBlank(atom.saui)) { desc.addStringAttribute(this.ptUMLSAttributes.getProperty("SAUI").getUUID(), atom.saui); } if (StringUtils.isNotBlank(atom.scui)) { desc.addStringAttribute(this.ptUMLSAttributes.getProperty("SCUI").getUUID(), atom.scui); } if (StringUtils.isNotBlank(atom.suppress)) { desc.addUUIDAttribute(this.ptUMLSAttributes.getProperty("SUPPRESS").getUUID(), this.suppress.get(atom.suppress)); } if (StringUtils.isNotBlank(atom.cvf)) { if (atom.cvf.equals("4096")) { desc.addRefsetMembership(this.cpcRefsetConcept.getPrimordialUuid()); } else { throw new RuntimeException("Unexpected value in RXNCONSO cvf column '" + atom.cvf + "'"); } } if (!atom.lat.equals("ENG")) { ConsoleUtil.printErrorln("Non-english lang settings not handled yet!"); } // TODO - at this point, sometime in the future, we make make attributes out of the relationships that occur between the AUIs // and store them on the descriptions, since OTF doesn't allow relationships between descriptions // TODO am I supposed to be using sabs? sabs.add(atom.sab); } // sanity check on descriptions - make sure we only have one that is of type synonym with the preferred flag final ArrayList<String> items = new ArrayList<>(); cuiDescriptions.stream() .filter((vpp) -> ((vpp.getProperty().getPropertySubType() >= BPT_Descriptions.SYNONYM) && (vpp.getProperty().getPropertySubType() <= (BPT_Descriptions.SYNONYM + 20)))) .forEachOrdered((vpp) -> { items.add(vpp.getProperty().getSourcePropertyNameFQN() + " " + vpp.getProperty().getPropertySubType()); }); // Numbers come from the rankings down below in makeDescriptionType(...) final HashSet<String> ranksLookedAt = new HashSet<>(); ranksLookedAt.add("204"); ranksLookedAt.add("206"); ranksLookedAt.add("210"); ranksLookedAt.add("208"); ranksLookedAt.add("212"); boolean oneNotInList = false; if (items.size() > 1) { for (final String s : items) { if (!ranksLookedAt.contains(s.substring(s.length() - 3, s.length()))) { oneNotInList = true; break; } } } if (oneNotInList) { ConsoleUtil.printErrorln( "Need to rank multiple synonym types that are each marked preferred, determine if ranking is appropriate!"); items.forEach((s) -> { ConsoleUtil.printErrorln(s); }); } final List<SemanticChronology> addedDescriptions = this.importUtil.addDescriptions(cuiConcept, cuiDescriptions); if (addedDescriptions.size() != cuiDescriptions.size()) { throw new RuntimeException("oops"); } final HashSet<String> uniqueUMLSCUI = new HashSet<>(); for (int i = 0; i < cuiDescriptions.size(); i++) { final SemanticChronology desc = addedDescriptions.get(i); final ValuePropertyPairWithSAB descPP = cuiDescriptions.get(i); final BiFunction<String, String, Boolean> functions = (atn, atv) -> { // Pull these up to the concept. if ("UMLSCUI".equals(atn)) { uniqueUMLSCUI.add(atv); return true; } return false; }; // TODO should I be passing in item code here? processSAT(ComponentReference.fromChronology(desc), descPP.getSatData(), null, descPP.getSab(), functions); } // pulling up the UMLS CUIs. // uniqueUMLSCUI is populated during processSAT uniqueUMLSCUI.forEach((umlsCui) -> { final UUID itemUUID = ConverterUUID.createNamespaceUUIDFromString("UMLSCUI" + umlsCui); this.importUtil.addStringAnnotation(cuiConcept, itemUUID, umlsCui, this.ptTermAttributes.getProperty("UMLSCUI").getUUID(), Status.ACTIVE); }); ValuePropertyPairWithAttributes.processAttributes(this.importUtil, cuiDescriptions, addedDescriptions); // there are no attributes in rxnorm without an AUI. // try // { this.importUtil.addRefsetMembership(cuiConcept, this.allCUIRefsetConcept.getPrimordialUuid(), Status.ACTIVE, null); // } // catch (RuntimeException e) // { // if (e.toString().contains("duplicate UUID")) // { // //ok - this can happen due to multiple merges onto an existing SCT concept // } // else // { // throw e; // } // } // add semantic types this.semanticTypeStatement.clearParameters(); this.semanticTypeStatement.setString(1, rxCui); final ResultSet rs = this.semanticTypeStatement.executeQuery(); processSemanticTypes(cuiConcept, rs); if (conceptTime < 0) { throw new RuntimeException("oops"); } this.importUtil.createConcept(cuiConcept.getPrimordialUuid(), conceptTime, conceptState, null); } final HashSet<UUID> parents = new HashSet<>(); this.cuiRelStatementForward.clearParameters(); this.cuiRelStatementForward.setString(1, rxCui); parents.addAll(addRelationships(cuiConcept, REL.read(null, this.cuiRelStatementForward.executeQuery(), true, this.allowedCUIsForSABs, this.skippedRelForNotMatchingCUIFilter, true, (string -> reverseRel(string))))); this.cuiRelStatementBackward.clearParameters(); this.cuiRelStatementBackward.setString(1, rxCui); parents.addAll(addRelationships(cuiConcept, REL.read(null, this.cuiRelStatementBackward.executeQuery(), false, this.allowedCUIsForSABs, this.skippedRelForNotMatchingCUIFilter, true, (string -> reverseRel(string))))); // Have to add multiple parents at once, no place to keep all the other details. Load those as associations for now. if (parents.size() > 0) { ComponentReference.fromChronology(this.importUtil.addParent(cuiConcept, null, parents.toArray(new UUID[parents.size()]), null, null)); } }
From source file:net.countercraft.movecraft.async.translation.TranslationTask.java
@Override public void excecute() { MovecraftLocation[] blocksList = data.getBlockList(); final int[] fallThroughBlocks = new int[] { 0, 8, 9, 10, 11, 31, 37, 38, 39, 40, 50, 51, 55, 59, 63, 65, 68, 69, 70, 72, 75, 76, 77, 78, 83, 85, 93, 94, 111, 141, 142, 143, 171 }; // blockedByWater=false means an ocean-going vessel boolean waterCraft = !getCraft().getType().blockedByWater(); boolean hoverCraft = getCraft().getType().getCanHover(); boolean airCraft = getCraft().getType().blockedByWater(); int hoverLimit = getCraft().getType().getHoverLimit(); Player craftPilot = CraftManager.getInstance().getPlayerFromCraft(getCraft()); int[][][] hb = getCraft().getHitBox(); if (hb == null) return;//from ww w . j av a 2 s . c om // start by finding the crafts borders int minY = 65535; int maxY = -65535; for (int[][] i1 : hb) { for (int[] i2 : i1) { if (i2 != null) { if (i2[0] < minY) { minY = i2[0]; } if (i2[1] > maxY) { maxY = i2[1]; } } } } int maxX = getCraft().getMinX() + hb.length; int maxZ = getCraft().getMinZ() + hb[0].length; // safe because if the first x array doesn't have a z array, then it wouldn't be the first x array int minX = getCraft().getMinX(); int minZ = getCraft().getMinZ(); // treat sinking crafts specially if (getCraft().getSinking()) { waterCraft = true; hoverCraft = false; } if (getCraft().getDisabled() && (!getCraft().getSinking())) { fail(String.format(I18nSupport.getInternationalisedString("Craft is disabled!"))); } // check the maxheightaboveground limitation, move 1 down if that limit is exceeded if (getCraft().getType().getMaxHeightAboveGround() > 0 && data.getDy() >= 0) { int x = getCraft().getMaxX() + getCraft().getMinX(); x = x >> 1; int y = getCraft().getMaxY(); int z = getCraft().getMaxZ() + getCraft().getMinZ(); z = z >> 1; int cy = getCraft().getMinY(); boolean done = false; while (!done) { cy = cy - 1; if (getCraft().getW().getBlockTypeIdAt(x, cy, z) != 0) done = true; if (cy <= 1) done = true; } if (y - cy > getCraft().getType().getMaxHeightAboveGround()) { data.setDy(-1); } } // Find the waterline from the surrounding terrain or from the static level in the craft type int waterLine = 0; if (waterCraft) { if (getCraft().getType().getStaticWaterLevel() != 0) { if (waterLine <= maxY + 1) { waterLine = getCraft().getType().getStaticWaterLevel(); } } else { // figure out the water level by examining blocks next to the outer boundaries of the craft for (int posY = maxY + 1; (posY >= minY - 1) && (waterLine == 0); posY--) { int numWater = 0; int numAir = 0; int posX; int posZ; posZ = minZ - 1; for (posX = minX - 1; (posX <= maxX + 1) && (waterLine == 0); posX++) { int typeID = getCraft().getW().getBlockAt(posX, posY, posZ).getTypeId(); if (typeID == 9) numWater++; if (typeID == 0) numAir++; } posZ = maxZ + 1; for (posX = minX - 1; (posX <= maxX + 1) && (waterLine == 0); posX++) { int typeID = getCraft().getW().getBlockAt(posX, posY, posZ).getTypeId(); if (typeID == 9) numWater++; if (typeID == 0) numAir++; } posX = minX - 1; for (posZ = minZ; (posZ <= maxZ) && (waterLine == 0); posZ++) { int typeID = getCraft().getW().getBlockAt(posX, posY, posZ).getTypeId(); if (typeID == 9) numWater++; if (typeID == 0) numAir++; } posX = maxX + 1; for (posZ = minZ; (posZ <= maxZ) && (waterLine == 0); posZ++) { int typeID = getCraft().getW().getBlockAt(posX, posY, posZ).getTypeId(); if (typeID == 9) numWater++; if (typeID == 0) numAir++; } if (numWater > numAir) { waterLine = posY; } } } // now add all the air blocks found within the craft's hitbox immediately above the waterline and below to the craft blocks so they will be translated HashSet<MovecraftLocation> newHSBlockList = new HashSet<MovecraftLocation>(Arrays.asList(blocksList)); int posY = waterLine + 1; for (int posX = minX; posX < maxX; posX++) { for (int posZ = minZ; posZ < maxZ; posZ++) { if (hb[posX - minX] != null) { if (hb[posX - minX][posZ - minZ] != null) { if (getCraft().getW().getBlockAt(posX, posY, posZ).getTypeId() == 0 && posY > hb[posX - minX][posZ - minZ][0] && posY < hb[posX - minX][posZ - minZ][1]) { MovecraftLocation l = new MovecraftLocation(posX, posY, posZ); newHSBlockList.add(l); } } } } } // dont check the hitbox for the underwater portion. Otherwise open-hulled ships would flood. for (posY = waterLine; posY >= minY; posY--) { for (int posX = minX; posX < maxX; posX++) { for (int posZ = minZ; posZ < maxZ; posZ++) { if (getCraft().getW().getBlockAt(posX, posY, posZ).getTypeId() == 0) { MovecraftLocation l = new MovecraftLocation(posX, posY, posZ); newHSBlockList.add(l); } } } } blocksList = newHSBlockList.toArray(new MovecraftLocation[newHSBlockList.size()]); } // check for fuel, burn some from a furnace if needed. Blocks of coal are supported, in addition to coal and charcoal double fuelBurnRate = getCraft().getType().getFuelBurnRate(); // going down doesn't require fuel if (data.getDy() == -1 && data.getDx() == 0 && data.getDz() == 0) fuelBurnRate = 0.0; if (fuelBurnRate != 0.0 && getCraft().getSinking() == false) { if (getCraft().getBurningFuel() < fuelBurnRate) { Block fuelHolder = null; for (MovecraftLocation bTest : blocksList) { Block b = getCraft().getW().getBlockAt(bTest.getX(), bTest.getY(), bTest.getZ()); if (b.getTypeId() == 61) { InventoryHolder inventoryHolder = (InventoryHolder) b.getState(); if (inventoryHolder.getInventory().contains(263) || inventoryHolder.getInventory().contains(173)) { fuelHolder = b; } } } if (fuelHolder == null) { fail(String.format( I18nSupport.getInternationalisedString("Translation - Failed Craft out of fuel"))); } else { InventoryHolder inventoryHolder = (InventoryHolder) fuelHolder.getState(); if (inventoryHolder.getInventory().contains(263)) { ItemStack iStack = inventoryHolder.getInventory() .getItem(inventoryHolder.getInventory().first(263)); int amount = iStack.getAmount(); if (amount == 1) { inventoryHolder.getInventory().remove(iStack); } else { iStack.setAmount(amount - 1); } getCraft().setBurningFuel(getCraft().getBurningFuel() + 7.0); } else { ItemStack iStack = inventoryHolder.getInventory() .getItem(inventoryHolder.getInventory().first(173)); int amount = iStack.getAmount(); if (amount == 1) { inventoryHolder.getInventory().remove(iStack); } else { iStack.setAmount(amount - 1); } getCraft().setBurningFuel(getCraft().getBurningFuel() + 79.0); } } } else { getCraft().setBurningFuel(getCraft().getBurningFuel() - fuelBurnRate); } } List<MovecraftLocation> tempBlockList = new ArrayList<MovecraftLocation>(); HashSet<MovecraftLocation> existingBlockSet = new HashSet<MovecraftLocation>(Arrays.asList(blocksList)); HashSet<EntityUpdateCommand> entityUpdateSet = new HashSet<EntityUpdateCommand>(); Set<MapUpdateCommand> updateSet = new HashSet<MapUpdateCommand>(); data.setCollisionExplosion(false); Set<MapUpdateCommand> explosionSet = new HashSet<MapUpdateCommand>(); List<Material> harvestBlocks = getCraft().getType().getHarvestBlocks(); List<MovecraftLocation> harvestedBlocks = new ArrayList<MovecraftLocation>(); List<MovecraftLocation> destroyedBlocks = new ArrayList<MovecraftLocation>(); List<Material> harvesterBladeBlocks = getCraft().getType().getHarvesterBladeBlocks(); int hoverOver = data.getDy(); int craftMinY = 0; int craftMaxY = 0; boolean clearNewData = false; boolean hoverUseGravity = getCraft().getType().getUseGravity(); boolean checkHover = (data.getDx() != 0 || data.getDz() != 0);// we want to check only horizontal moves boolean canHoverOverWater = getCraft().getType().getCanHoverOverWater(); boolean townyEnabled = Movecraft.getInstance().getTownyPlugin() != null; boolean explosionBlockedByTowny = false; boolean moveBlockedByTowny = false; boolean validateTownyExplosion = false; String townName = ""; Set<TownBlock> townBlockSet = new HashSet<TownBlock>(); TownyWorld townyWorld = null; TownyWorldHeightLimits townyWorldHeightLimits = null; if (townyEnabled && Settings.TownyBlockMoveOnSwitchPerm) { townyWorld = TownyUtils.getTownyWorld(getCraft().getW()); if (townyWorld != null) { townyEnabled = townyWorld.isUsingTowny(); if (townyEnabled) { townyWorldHeightLimits = TownyUtils.getWorldLimits(getCraft().getW()); if (getCraft().getType().getCollisionExplosion() != 0.0F) { validateTownyExplosion = true; } } } } else { townyEnabled = false; } for (int i = 0; i < blocksList.length; i++) { MovecraftLocation oldLoc = blocksList[i]; MovecraftLocation newLoc = oldLoc.translate(data.getDx(), data.getDy(), data.getDz()); if (newLoc.getY() > data.getMaxHeight() && newLoc.getY() > oldLoc.getY()) { fail(String.format( I18nSupport.getInternationalisedString("Translation - Failed Craft hit height limit"))); break; } else if (newLoc.getY() < data.getMinHeight() && newLoc.getY() < oldLoc.getY() && getCraft().getSinking() == false) { fail(String.format(I18nSupport .getInternationalisedString("Translation - Failed Craft hit minimum height limit"))); break; } boolean blockObstructed = false; boolean harvestBlock = false; boolean bladeOK = true; Material testMaterial; Location plugLoc = new Location(getCraft().getW(), newLoc.getX(), newLoc.getY(), newLoc.getZ()); if (craftPilot != null) { // See if they are permitted to build in the area, if WorldGuard integration is turned on if (Movecraft.getInstance().getWorldGuardPlugin() != null && Settings.WorldGuardBlockMoveOnBuildPerm) { if (Movecraft.getInstance().getWorldGuardPlugin().canBuild(craftPilot, plugLoc) == false) { fail(String.format(I18nSupport.getInternationalisedString( "Translation - Failed Player is not permitted to build in this WorldGuard region") + " @ %d,%d,%d", oldLoc.getX(), oldLoc.getY(), oldLoc.getZ())); break; } } } Player p; if (craftPilot == null) { p = getCraft().getNotificationPlayer(); } else { p = craftPilot; } if (p != null) { if (Movecraft.getInstance().getWorldGuardPlugin() != null && Movecraft.getInstance().getWGCustomFlagsPlugin() != null && Settings.WGCustomFlagsUsePilotFlag) { LocalPlayer lp = Movecraft.getInstance().getWorldGuardPlugin().wrapPlayer(p); WGCustomFlagsUtils WGCFU = new WGCustomFlagsUtils(); if (!WGCFU.validateFlag(plugLoc, Movecraft.FLAG_MOVE, lp)) { fail(String .format(I18nSupport.getInternationalisedString("WGCustomFlags - Translation Failed") + " @ %d,%d,%d", oldLoc.getX(), oldLoc.getY(), oldLoc.getZ())); break; } } if (townyEnabled) { TownBlock townBlock = TownyUtils.getTownBlock(plugLoc); if (townBlock != null && !townBlockSet.contains(townBlock)) { if (validateTownyExplosion) { if (!explosionBlockedByTowny) { if (!TownyUtils.validateExplosion(townBlock)) { explosionBlockedByTowny = true; } } } if (TownyUtils.validateCraftMoveEvent(p, plugLoc, townyWorld)) { townBlockSet.add(townBlock); } else { int y = plugLoc.getBlockY(); boolean oChange = false; if (craftMinY > y) { craftMinY = y; oChange = true; } if (craftMaxY < y) { craftMaxY = y; oChange = true; } if (oChange) { boolean failed = false; Town town = TownyUtils.getTown(townBlock); if (town != null) { Location locSpawn = TownyUtils.getTownSpawn(townBlock); if (locSpawn != null) { if (!townyWorldHeightLimits.validate(y, locSpawn.getBlockY())) { failed = true; } } else { failed = true; } if (failed) { if (Movecraft.getInstance().getWorldGuardPlugin() != null && Movecraft.getInstance().getWGCustomFlagsPlugin() != null && Settings.WGCustomFlagsUsePilotFlag) { LocalPlayer lp = Movecraft.getInstance().getWorldGuardPlugin() .wrapPlayer(p); ApplicableRegionSet regions = Movecraft.getInstance() .getWorldGuardPlugin().getRegionManager(plugLoc.getWorld()) .getApplicableRegions(plugLoc); if (regions.size() != 0) { WGCustomFlagsUtils WGCFU = new WGCustomFlagsUtils(); if (WGCFU.validateFlag(plugLoc, Movecraft.FLAG_MOVE, lp)) { failed = false; } } } } if (failed) { townName = town.getName(); moveBlockedByTowny = true; } } } } } } } //check for chests around testMaterial = getCraft().getW().getBlockAt(oldLoc.getX(), oldLoc.getY(), oldLoc.getZ()).getType(); if (testMaterial.equals(Material.CHEST) || testMaterial.equals(Material.TRAPPED_CHEST)) { if (!checkChests(testMaterial, newLoc, existingBlockSet)) { //prevent chests collision fail(String.format( I18nSupport.getInternationalisedString("Translation - Failed Craft is obstructed") + " @ %d,%d,%d,%s", newLoc.getX(), newLoc.getY(), newLoc.getZ(), getCraft().getW() .getBlockAt(newLoc.getX(), newLoc.getY(), newLoc.getZ()).getType().toString())); break; } } if (getCraft().getSinking()) { int testID = getCraft().getW().getBlockAt(newLoc.getX(), newLoc.getY(), newLoc.getZ()).getTypeId(); blockObstructed = !(Arrays.binarySearch(fallThroughBlocks, testID) >= 0) && !existingBlockSet.contains(newLoc); } else if (!waterCraft) { // New block is not air or a piston head and is not part of the existing ship testMaterial = getCraft().getW().getBlockAt(newLoc.getX(), newLoc.getY(), newLoc.getZ()).getType(); blockObstructed = (!testMaterial.equals(Material.AIR)) && !existingBlockSet.contains(newLoc); } else { // New block is not air or water or a piston head and is not part of the existing ship testMaterial = getCraft().getW().getBlockAt(newLoc.getX(), newLoc.getY(), newLoc.getZ()).getType(); blockObstructed = (!testMaterial.equals(Material.AIR) && !testMaterial.equals(Material.STATIONARY_WATER) && !testMaterial.equals(Material.WATER)) && !existingBlockSet.contains(newLoc); } boolean ignoreBlock = false; // air never obstructs anything (changed 4/18/2017 to prevent drilling machines) if (getCraft().getW().getBlockAt(oldLoc.getX(), oldLoc.getY(), oldLoc.getZ()).getType() .equals(Material.AIR) && blockObstructed) { ignoreBlock = true; // blockObstructed=false; } testMaterial = getCraft().getW().getBlockAt(newLoc.getX(), newLoc.getY(), newLoc.getZ()).getType(); if (blockObstructed) { if (hoverCraft || harvestBlocks.size() > 0) { // New block is not harvested block if (harvestBlocks.contains(testMaterial) && !existingBlockSet.contains(newLoc)) { Material tmpType = getCraft().getW().getBlockAt(oldLoc.getX(), oldLoc.getY(), oldLoc.getZ()) .getType(); if (harvesterBladeBlocks.size() > 0) { if (!harvesterBladeBlocks.contains(tmpType)) { bladeOK = false; } } if (bladeOK) { blockObstructed = false; harvestBlock = true; tryPutToDestroyBox(testMaterial, newLoc, harvestedBlocks, destroyedBlocks); harvestedBlocks.add(newLoc); } } } } if (blockObstructed || moveBlockedByTowny) { if (hoverCraft && checkHover) { //we check one up ever, if it is hovercraft and one down if it's using gravity if (hoverOver == 0 && newLoc.getY() + 1 <= data.getMaxHeight()) { //first was checked actual level, now check if we can go up hoverOver = 1; data.setDy(1); clearNewData = true; } else if (hoverOver >= 1) { //check other options to go up if (hoverOver < hoverLimit + 1 && newLoc.getY() + 1 <= data.getMaxHeight()) { data.setDy(hoverOver + 1); hoverOver += 1; clearNewData = true; } else { if (hoverUseGravity && newLoc.getY() - hoverOver - 1 >= data.getMinHeight()) { //we are on the maximum of top //if we can't go up so we test bottom side data.setDy(-1); hoverOver = -1; } else { // no way - back to original dY, turn off hovercraft for this move // and get original data again for all explosions data.setDy(0); hoverOver = 0; hoverCraft = false; hoverUseGravity = false; } clearNewData = true; } } else if (hoverOver <= -1) { //we cant go down for 1 block, check more to hoverLimit if (hoverOver > -hoverLimit - 1 && newLoc.getY() - 1 >= data.getMinHeight()) { data.setDy(hoverOver - 1); hoverOver -= 1; clearNewData = true; } else { // no way - back to original dY, turn off hovercraft for this move // and get original data again for all explosions data.setDy(0); hoverOver = 0; hoverUseGravity = false; clearNewData = true; hoverCraft = false; } } else { // no way - reached MaxHeight during looking new way upstairss if (hoverUseGravity && newLoc.getY() - 1 >= data.getMinHeight()) { //we are on the maximum of top //if we can't go up so we test bottom side data.setDy(-1); hoverOver = -1; } else { // - back to original dY, turn off hovercraft for this move // and get original data again for all explosions data.setDy(0); hoverOver = 0; hoverUseGravity = false; hoverCraft = false; } clearNewData = true; } // End hovercraft stuff } else { // handle sinking ship collisions if (getCraft().getSinking()) { if (getCraft().getType().getExplodeOnCrash() != 0.0F && !explosionBlockedByTowny) { int explosionKey = (int) (0 - (getCraft().getType().getExplodeOnCrash() * 100)); if (System.currentTimeMillis() - getCraft().getOrigPilotTime() > 1000) if (!getCraft().getW().getBlockAt(oldLoc.getX(), oldLoc.getY(), oldLoc.getZ()) .getType().equals(Material.AIR)) { explosionSet .add(new MapUpdateCommand(oldLoc, explosionKey, (byte) 0, getCraft())); data.setCollisionExplosion(true); } } else { // use the explosion code to clean up the craft, but not with enough force to do anything int explosionKey = 0 - 1; if (!getCraft().getW().getBlockAt(oldLoc.getX(), oldLoc.getY(), oldLoc.getZ()).getType() .equals(Material.AIR)) { explosionSet.add(new MapUpdateCommand(oldLoc, explosionKey, (byte) 0, getCraft())); data.setCollisionExplosion(true); } } } else { // Explode if the craft is set to have a CollisionExplosion. Also keep moving for spectacular ramming collisions if (getCraft().getType().getCollisionExplosion() == 0.0F) { if (moveBlockedByTowny) { fail(String.format( I18nSupport.getInternationalisedString("Towny - Translation Failed") + " %s @ %d,%d,%d", townName, oldLoc.getX(), oldLoc.getY(), oldLoc.getZ())); } else { fail(String.format( I18nSupport.getInternationalisedString( "Translation - Failed Craft is obstructed") + " @ %d,%d,%d,%s", oldLoc.getX(), oldLoc.getY(), oldLoc.getZ(), getCraft().getW().getBlockAt(newLoc.getX(), newLoc.getY(), newLoc.getZ()) .getType().toString())); if (getCraft().getNotificationPlayer() != null) { Location location = getCraft().getNotificationPlayer().getLocation(); } } break; } else if (explosionBlockedByTowny) { int explosionKey = 0 - 1; if (!getCraft().getW().getBlockAt(oldLoc.getX(), oldLoc.getY(), oldLoc.getZ()).getType() .equals(Material.AIR)) { explosionSet.add(new MapUpdateCommand(oldLoc, explosionKey, (byte) 0, getCraft())); data.setCollisionExplosion(true); } } else if (System.currentTimeMillis() - getCraft().getOrigPilotTime() > 1000) { int explosionKey; float explosionForce = getCraft().getType().getCollisionExplosion(); if (getCraft().getType().getFocusedExplosion() == true) { explosionForce = explosionForce * getCraft().getBlockList().length; } if (oldLoc.getY() < waterLine) { // underwater explosions require more force to do anything explosionForce += 25; } explosionKey = (int) (0 - (explosionForce * 100)); if (!getCraft().getW().getBlockAt(oldLoc.getX(), oldLoc.getY(), oldLoc.getZ()).getType() .equals(Material.AIR)) { explosionSet.add(new MapUpdateCommand(oldLoc, explosionKey, (byte) 0, getCraft())); data.setCollisionExplosion(true); } if (getCraft().getType().getFocusedExplosion() == true) { // don't handle any further collisions if it is set to focusedexplosion break; } } } } } else { //block not obstructed int oldID = getCraft().getW().getBlockTypeIdAt(oldLoc.getX(), oldLoc.getY(), oldLoc.getZ()); byte oldData = getCraft().getW().getBlockAt(oldLoc.getX(), oldLoc.getY(), oldLoc.getZ()).getData(); int currentID = getCraft().getW().getBlockTypeIdAt(newLoc.getX(), newLoc.getY(), newLoc.getZ()); byte currentData = getCraft().getW().getBlockAt(newLoc.getX(), newLoc.getY(), newLoc.getZ()) .getData(); // remove water from sinking crafts if (getCraft().getSinking()) { if ((oldID == 8 || oldID == 9) && oldLoc.getY() > waterLine) oldID = 0; } if (!ignoreBlock) { updateSet.add(new MapUpdateCommand(oldLoc, currentID, currentData, newLoc, oldID, oldData, getCraft())); tempBlockList.add(newLoc); } if (i == blocksList.length - 1) { if ((hoverCraft && hoverUseGravity) || (hoverUseGravity && newLoc.getY() > data.getMaxHeight() && hoverOver == 0)) { //hovecraft using gravity or something else using gravity and flying over its limit int iFreeSpace = 0; //canHoverOverWater adds 1 to dY for better check water under craft // best way should be expand selected region to each first blocks under craft if (hoverOver == 0) { //we go directly forward so we check if we can go down for (int ii = -1; ii > -hoverLimit - 2 - (canHoverOverWater ? 0 : 1); ii--) { if (!isFreeSpace(data.getDx(), hoverOver + ii, data.getDz(), blocksList, existingBlockSet, waterCraft, hoverCraft, harvestBlocks, canHoverOverWater, checkHover)) { break; } iFreeSpace++; } if (data.failed()) { break; } if (iFreeSpace > hoverLimit - (canHoverOverWater ? 0 : 1)) { data.setDy(-1); hoverOver = -1; clearNewData = true; } } else if (hoverOver == 1 && !airCraft) { //prevent fly heigher than hoverLimit for (int ii = -1; ii > -hoverLimit - 2; ii--) { if (!isFreeSpace(data.getDx(), hoverOver + ii, data.getDz(), blocksList, existingBlockSet, waterCraft, hoverCraft, harvestBlocks, canHoverOverWater, checkHover)) { break; } iFreeSpace++; } if (data.failed()) { break; } if (iFreeSpace > hoverLimit) { if (bladeOK) { fail(String.format(I18nSupport.getInternationalisedString( "Translation - Failed Craft hit height limit"))); } else { fail(String.format( I18nSupport.getInternationalisedString( "Translation - Failed Craft is obstructed") + " @ %d,%d,%d,%s", oldLoc.getX(), oldLoc.getY(), oldLoc.getZ(), getCraft().getW() .getBlockAt(newLoc.getX(), newLoc.getY(), newLoc.getZ()) .getType().toString())); } break; } } else if (hoverOver > 1) { //prevent jump thru block for (int ii = 1; ii < hoverOver - 1; ii++) { if (!isFreeSpace(0, ii, 0, blocksList, existingBlockSet, waterCraft, hoverCraft, harvestBlocks, canHoverOverWater, checkHover)) { break; } iFreeSpace++; } if (data.failed()) { break; } if (iFreeSpace + 2 < hoverOver) { data.setDy(-1); hoverOver = -1; clearNewData = true; } } else if (hoverOver < -1) { //prevent jump thru block for (int ii = -1; ii > hoverOver + 1; ii--) { if (!isFreeSpace(0, ii, 0, blocksList, existingBlockSet, waterCraft, hoverCraft, harvestBlocks, canHoverOverWater, checkHover)) { break; } iFreeSpace++; } if (data.failed()) { break; } if (iFreeSpace + 2 < -hoverOver) { data.setDy(0); hoverOver = 0; hoverCraft = false; clearNewData = true; } } if (!canHoverOverWater) { if (hoverOver >= 1) { //others hoverOver values we have checked jet for (int ii = hoverOver - 1; ii > hoverOver - hoverLimit - 2; ii--) { if (!isFreeSpace(0, ii, 0, blocksList, existingBlockSet, waterCraft, hoverCraft, harvestBlocks, canHoverOverWater, checkHover)) { break; } iFreeSpace++; } if (data.failed()) { break; } } } } } } //END OF: if (blockObstructed) if (clearNewData) { i = -1; tempBlockList.clear(); updateSet.clear(); harvestedBlocks.clear(); data.setCollisionExplosion(false); explosionSet.clear(); clearNewData = false; townBlockSet.clear(); craftMinY = 0; craftMaxY = 0; } } //END OF: for ( int i = 0; i < blocksList.length; i++ ) { // now move the scheduled block changes along with the ship HashMap<MapUpdateCommand, Long> newScheduledBlockChanges = new HashMap<MapUpdateCommand, Long>(); HashMap<MapUpdateCommand, Long> oldScheduledBlockChanges = getCraft().getScheduledBlockChanges(); if (oldScheduledBlockChanges != null) { for (MapUpdateCommand muc : oldScheduledBlockChanges.keySet()) { MovecraftLocation newLoc = muc.getNewBlockLocation().translate(data.getDx(), data.getDy(), data.getDz()); // Long newTime=oldScheduledBlockChanges.get(muc); Long newTime = System.currentTimeMillis() + 5000; MapUpdateCommand newMuc = new MapUpdateCommand(newLoc, muc.getTypeID(), muc.getDataID(), getCraft()); newScheduledBlockChanges.put(newMuc, newTime); } data.setScheduledBlockChanges(newScheduledBlockChanges); } if (data.collisionExplosion()) { // mark the craft to check for sinking, remove the exploding blocks from the blocklist, and submit the explosions for map update for (MapUpdateCommand m : explosionSet) { if (existingBlockSet.contains(m.getNewBlockLocation())) { existingBlockSet.remove(m.getNewBlockLocation()); if (Settings.FadeWrecksAfter > 0) { int typeID = getCraft().getW().getBlockAt(m.getNewBlockLocation().getX(), m.getNewBlockLocation().getY(), m.getNewBlockLocation().getZ()).getTypeId(); if (typeID != 0 && typeID != 9) { Movecraft.getInstance().blockFadeTimeMap.put(m.getNewBlockLocation(), System.currentTimeMillis()); Movecraft.getInstance().blockFadeTypeMap.put(m.getNewBlockLocation(), typeID); if (m.getNewBlockLocation().getY() <= waterLine) { Movecraft.getInstance().blockFadeWaterMap.put(m.getNewBlockLocation(), true); } else { Movecraft.getInstance().blockFadeWaterMap.put(m.getNewBlockLocation(), false); } Movecraft.getInstance().blockFadeWorldMap.put(m.getNewBlockLocation(), getCraft().getW()); } } } // if the craft is sinking, remove all solid blocks above the one that hit the ground from the craft for smoothing sinking if (getCraft().getSinking() == true && (getCraft().getType().getExplodeOnCrash() == 0.0 || explosionBlockedByTowny)) { int posy = m.getNewBlockLocation().getY() + 1; int testID = getCraft().getW() .getBlockAt(m.getNewBlockLocation().getX(), posy, m.getNewBlockLocation().getZ()) .getTypeId(); while (posy <= maxY && !(Arrays.binarySearch(fallThroughBlocks, testID) >= 0)) { MovecraftLocation testLoc = new MovecraftLocation(m.getNewBlockLocation().getX(), posy, m.getNewBlockLocation().getZ()); if (existingBlockSet.contains(testLoc)) { existingBlockSet.remove(testLoc); if (Settings.FadeWrecksAfter > 0) { int typeID = getCraft().getW() .getBlockAt(testLoc.getX(), testLoc.getY(), testLoc.getZ()).getTypeId(); if (typeID != 0 && typeID != 9) { Movecraft.getInstance().blockFadeTimeMap.put(testLoc, System.currentTimeMillis()); Movecraft.getInstance().blockFadeTypeMap.put(testLoc, typeID); if (testLoc.getY() <= waterLine) { Movecraft.getInstance().blockFadeWaterMap.put(testLoc, true); } else { Movecraft.getInstance().blockFadeWaterMap.put(testLoc, false); } Movecraft.getInstance().blockFadeWorldMap.put(testLoc, getCraft().getW()); } } } posy = posy + 1; testID = getCraft().getW() .getBlockAt(m.getNewBlockLocation().getX(), posy, m.getNewBlockLocation().getZ()) .getTypeId(); } } } MovecraftLocation[] newBlockList = (MovecraftLocation[]) existingBlockSet .toArray(new MovecraftLocation[0]); data.setBlockList(newBlockList); data.setUpdates(explosionSet.toArray(new MapUpdateCommand[1])); fail(String.format(I18nSupport.getInternationalisedString("Translation - Failed Craft is obstructed"))); if (getCraft().getSinking() == false) { // FROG changed from ==true, think that was a typo if (getCraft().getType().getSinkPercent() != 0.0) { getCraft().setLastBlockCheck(0); } getCraft().setLastCruisUpdate(System.currentTimeMillis() - 30000); } } if (!data.failed()) { MovecraftLocation[] newBlockList = (MovecraftLocation[]) tempBlockList .toArray(new MovecraftLocation[0]); data.setBlockList(newBlockList); //prevents torpedo and rocket pilots :) if (getCraft().getType().getMoveEntities() && getCraft().getSinking() == false) { // Move entities within the craft List<Entity> eList = null; int numTries = 0; while ((eList == null) && (numTries < 100)) { try { eList = getCraft().getW().getEntities(); } catch (java.util.ConcurrentModificationException e) { numTries++; } } Iterator<Entity> i = eList.iterator(); while (i.hasNext()) { Entity pTest = i.next(); // if ( MathUtils.playerIsWithinBoundingPolygon( getCraft().getHitBox(), getCraft().getMinX(), getCraft().getMinZ(), MathUtils.bukkit2MovecraftLoc( pTest.getLocation() ) ) ) { if (MathUtils.locIsNearCraftFast(getCraft(), MathUtils.bukkit2MovecraftLoc(pTest.getLocation()))) { if (pTest.getType() == org.bukkit.entity.EntityType.PLAYER) { Player player = (Player) pTest; getCraft().getMovedPlayers().put(player, System.currentTimeMillis()); Location tempLoc = pTest.getLocation(); // Direct control no longer locks the player in place // if(getCraft().getPilotLocked()==true && pTest==CraftManager.getInstance().getPlayerFromCraft(getCraft())) { // tempLoc.setX(getCraft().getPilotLockedX()); // tempLoc.setY(getCraft().getPilotLockedY()); // tempLoc.setZ(getCraft().getPilotLockedZ()); // } tempLoc = tempLoc.add(data.getDx(), data.getDy(), data.getDz()); Location newPLoc = new Location(getCraft().getW(), tempLoc.getX(), tempLoc.getY(), tempLoc.getZ()); newPLoc.setPitch(pTest.getLocation().getPitch()); newPLoc.setYaw(pTest.getLocation().getYaw()); EntityUpdateCommand eUp = new EntityUpdateCommand(pTest.getLocation().clone(), newPLoc, pTest); entityUpdateSet.add(eUp); // if(getCraft().getPilotLocked()==true && pTest==CraftManager.getInstance().getPlayerFromCraft(getCraft())) { // getCraft().setPilotLockedX(tempLoc.getX()); // getCraft().setPilotLockedY(tempLoc.getY()); // getCraft().setPilotLockedZ(tempLoc.getZ()); // } } if (pTest.getType() == org.bukkit.entity.EntityType.PRIMED_TNT) { Entity ent = (Entity) pTest; Location tempLoc = pTest.getLocation(); tempLoc = tempLoc.add(data.getDx(), data.getDy(), data.getDz()); EntityUpdateCommand eUp = new EntityUpdateCommand(pTest.getLocation().clone(), tempLoc, pTest); entityUpdateSet.add(eUp); } } } } else { //add releaseTask without playermove to manager if (getCraft().getType().getCruiseOnPilot() == false && getCraft().getSinking() == false) // not necessary to release cruiseonpilot crafts, because they will already be released CraftManager.getInstance().addReleaseTask(getCraft()); } // remove water near sinking crafts if (getCraft().getSinking()) { int posX; int posY = maxY; int posZ; if (posY > waterLine) { for (posX = minX - 1; posX <= maxX + 1; posX++) { for (posZ = minZ - 1; posZ <= maxZ + 1; posZ++) { if (getCraft().getW().getBlockAt(posX, posY, posZ).getTypeId() == 9 || getCraft().getW().getBlockAt(posX, posY, posZ).getTypeId() == 8) { MovecraftLocation loc = new MovecraftLocation(posX, posY, posZ); updateSet.add(new MapUpdateCommand(loc, 0, (byte) 0, getCraft())); } } } } for (posY = maxY + 1; (posY >= minY - 1) && (posY > waterLine); posY--) { posZ = minZ - 1; for (posX = minX - 1; posX <= maxX + 1; posX++) { if (getCraft().getW().getBlockAt(posX, posY, posZ).getTypeId() == 9 || getCraft().getW().getBlockAt(posX, posY, posZ).getTypeId() == 8) { MovecraftLocation loc = new MovecraftLocation(posX, posY, posZ); updateSet.add(new MapUpdateCommand(loc, 0, (byte) 0, getCraft())); } } posZ = maxZ + 1; for (posX = minX - 1; posX <= maxX + 1; posX++) { if (getCraft().getW().getBlockAt(posX, posY, posZ).getTypeId() == 9 || getCraft().getW().getBlockAt(posX, posY, posZ).getTypeId() == 8) { MovecraftLocation loc = new MovecraftLocation(posX, posY, posZ); updateSet.add(new MapUpdateCommand(loc, 0, (byte) 0, getCraft())); } } posX = minX - 1; for (posZ = minZ - 1; posZ <= maxZ + 1; posZ++) { if (getCraft().getW().getBlockAt(posX, posY, posZ).getTypeId() == 9 || getCraft().getW().getBlockAt(posX, posY, posZ).getTypeId() == 8) { MovecraftLocation loc = new MovecraftLocation(posX, posY, posZ); updateSet.add(new MapUpdateCommand(loc, 0, (byte) 0, getCraft())); } } posX = maxX + 1; for (posZ = minZ - 1; posZ <= maxZ + 1; posZ++) { if (getCraft().getW().getBlockAt(posX, posY, posZ).getTypeId() == 9 || getCraft().getW().getBlockAt(posX, posY, posZ).getTypeId() == 8) { MovecraftLocation loc = new MovecraftLocation(posX, posY, posZ); updateSet.add(new MapUpdateCommand(loc, 0, (byte) 0, getCraft())); } } } } //Set blocks that are no longer craft to air // /********************************************************************************************************** // * I had problems with ListUtils (I tryied commons-collections 3.2.1. and 4.0 without success) // * so I replaced Lists with Sets // * // * Caused by: java.lang.NoClassDefFoundError: org/apache/commons/collections/ListUtils // * at net.countercraft.movecraft.async.translation.TranslationTask.excecute(TranslationTask.java:716) // * mwkaicz 24-02-2015 // ***********************************************************************************************************/ // Set<MovecraftLocation> setA = new HashSet(Arrays.asList(blocksList)); // Set<MovecraftLocation> setB = new HashSet(Arrays.asList(newBlockList)); // setA.removeAll(setB); // MovecraftLocation[] arrA = new MovecraftLocation[0]; // arrA = setA.toArray(arrA); // List<MovecraftLocation> airLocation = Arrays.asList(arrA); List<MovecraftLocation> airLocation = ListUtils.subtract(Arrays.asList(blocksList), Arrays.asList(newBlockList)); for (MovecraftLocation l1 : airLocation) { // for watercraft, fill blocks below the waterline with water if (!waterCraft) { if (getCraft().getSinking()) { updateSet.add(new MapUpdateCommand(l1, 0, (byte) 0, getCraft(), getCraft().getType().getSmokeOnSink())); } else { updateSet.add(new MapUpdateCommand(l1, 0, (byte) 0, getCraft())); } } else { if (l1.getY() <= waterLine) { // if there is air below the ship at the current position, don't fill in with water MovecraftLocation testAir = new MovecraftLocation(l1.getX(), l1.getY() - 1, l1.getZ()); while (existingBlockSet.contains(testAir)) { testAir.setY(testAir.getY() - 1); } if (getCraft().getW().getBlockAt(testAir.getX(), testAir.getY(), testAir.getZ()) .getTypeId() == 0) { if (getCraft().getSinking()) { updateSet.add(new MapUpdateCommand(l1, 0, (byte) 0, getCraft(), getCraft().getType().getSmokeOnSink())); } else { updateSet.add(new MapUpdateCommand(l1, 0, (byte) 0, getCraft())); } } else { updateSet.add(new MapUpdateCommand(l1, 9, (byte) 0, getCraft())); } } else { if (getCraft().getSinking()) { updateSet.add(new MapUpdateCommand(l1, 0, (byte) 0, getCraft(), getCraft().getType().getSmokeOnSink())); } else { updateSet.add(new MapUpdateCommand(l1, 0, (byte) 0, getCraft())); } } } } //add destroyed parts of growed for (MovecraftLocation destroyedLocation : destroyedBlocks) { updateSet.add(new MapUpdateCommand(destroyedLocation, 0, (byte) 0, getCraft())); } MapUpdateCommand[] updateArray = updateSet.toArray(new MapUpdateCommand[1]); // MapUpdateManager.getInstance().sortUpdates(updateArray); data.setUpdates(updateArray); data.setEntityUpdates(entityUpdateSet.toArray(new EntityUpdateCommand[1])); if (data.getDy() != 0) { data.setHitbox(BoundingBoxUtils.translateBoundingBoxVertically(data.getHitbox(), data.getDy())); } data.setMinX(data.getMinX() + data.getDx()); data.setMinZ(data.getMinZ() + data.getDz()); } captureYield(blocksList, harvestedBlocks); }
From source file:org.nuxeo.ecm.platform.usermanager.UserManagerImpl.java
@Override public String[] getUsersForPermission(String perm, ACP acp, DocumentModel context) { PermissionProvider permissionProvider = Framework.getService(PermissionProvider.class); // using a hashset to avoid duplicates HashSet<String> usernames = new HashSet<String>(); ACL merged = acp.getMergedACLs("merged"); // The list of permission that is has "perm" as its (compound) // permission ArrayList<ACE> filteredACEbyPerm = new ArrayList<ACE>(); List<String> currentPermissions = getLeafPermissions(perm); for (ACE ace : merged.getACEs()) { // Checking if the permission contains the permission we want to // check (we use the security service method for coumpound // permissions) List<String> acePermissions = getLeafPermissions(ace.getPermission()); // Everything is a special permission (not compound) if (SecurityConstants.EVERYTHING.equals(ace.getPermission())) { acePermissions = Arrays.asList(permissionProvider.getPermissions()); }// w ww.j av a 2 s . c o m if (acePermissions.containsAll(currentPermissions)) { // special case: everybody perm grant false, don't take in // account the previous ace if (SecurityConstants.EVERYONE.equals(ace.getUsername()) && !ace.isGranted()) { break; } filteredACEbyPerm.add(ace); } } for (ACE ace : filteredACEbyPerm) { String aceUsername = ace.getUsername(); List<String> users = null; // If everyone, add/remove all the users if (SecurityConstants.EVERYONE.equals(aceUsername)) { users = getUserIds(); } // if a group, add/remove all the user from the group (and // subgroups) if (users == null) { NuxeoGroup group; group = getGroup(aceUsername, context); if (group != null) { users = getUsersInGroupAndSubGroups(aceUsername, context); } } // otherwise, add the user if (users == null) { users = new ArrayList<String>(); users.add(aceUsername); } if (ace.isGranted()) { usernames.addAll(users); } else { usernames.removeAll(users); } } return usernames.toArray(new String[usernames.size()]); }
From source file:tvbrowser.ui.mainframe.MainFrame.java
/** * extract the drag and drop targets from the event * @param transferable/*from www . j av a 2s . c o m*/ * @param dataFlavors * @return */ private File[] getDragDropPlugins(final DataFlavor[] dataFlavors, final Transferable transferable) { HashSet<File> files = new HashSet<File>(); for (DataFlavor flavor : dataFlavors) { try { Object data = transferable.getTransferData(flavor); if (data instanceof List) { for (Object o : ((List) data)) { if (o instanceof File) { addPluginFile((File) o, files); } } if (!files.isEmpty()) { break; } } else if (data instanceof String) { String name = ((String) data).trim(); if (name.toLowerCase().endsWith("jar")) { File pluginFile = new File(name); if (pluginFile.canRead()) { addPluginFile(pluginFile, files); if (!files.isEmpty()) { break; } } else { try { URI uri = new URI(name); addPluginFile(new File(uri), files); } catch (URISyntaxException e) { // ignore } if (!files.isEmpty()) { break; } } } } } catch (UnsupportedFlavorException e) { //ignore } catch (IOException e) { //ignore } } return files.toArray(new File[files.size()]); }
From source file:org.LexGrid.LexBIG.Impl.dataAccess.SQLImplementedMethods.java
public static Entity buildCodedEntry(String internalCodingSchemeName, String internalVersionString, String code, String namespace, LocalNameList restrictToProperties, PropertyType[] restrictToPropertyTypes) throws UnexpectedInternalError, MissingResourceException { try {// w w w.jav a 2s.c o m Entity concept = new Entity(); concept.setEntityCode(code); SQLInterface si = ResourceManager.instance().getSQLInterface(internalCodingSchemeName, internalVersionString); //if the namespace is null (and its 2009 model), set it to the default (which is //equal to the codingSchemeName. //This shouldn't ever happen -- all classes that call this method should provide //a namespace. if (si.supports2009Model() && StringUtils.isBlank(namespace)) { namespace = internalCodingSchemeName; } ArrayList<Definition> definitions = new ArrayList<Definition>(); ArrayList<Presentation> presentations = new ArrayList<Presentation>(); ArrayList<Property> properties = new ArrayList<Property>(); ArrayList<Comment> comments = new ArrayList<Comment>(); ArrayList<PropertyLink> links = new ArrayList<PropertyLink>(); PreparedStatement getEntityCode = null; PreparedStatement getEntityType = null; PreparedStatement getEntityProperties = null; PreparedStatement getPropertyLinks = null; try { StringBuffer buildEntity = new StringBuffer(); buildEntity .append("Select * " + " from " + si.getTableName(SQLTableConstants.ENTITY) + " {AS} t1 "); if (si.supports2009Model()) { buildEntity.append("left join " + si.getTableName(SQLTableConstants.ENTRY_STATE) + " {AS} t2 " + "on t1." + SQLTableConstants.TBLCOL_ENTRYSTATEID + " = t2." + SQLTableConstants.TBLCOL_ENTRYSTATEID); } buildEntity.append(" where " + si.getSQLTableConstants().codingSchemeNameOrId + " = ? AND " + si.getSQLTableConstants().entityCodeOrId + " = ?"); if (si.supports2009Model()) { buildEntity.append(" AND " + SQLTableConstants.TBLCOL_ENTITYCODENAMESPACE + " = ?"); } getEntityCode = si.modifyAndCheckOutPreparedStatement(buildEntity.toString()); getEntityCode.setString(1, internalCodingSchemeName); getEntityCode.setString(2, code); if (si.supports2009Model()) { getEntityCode.setString(3, namespace); } ResultSet results = getEntityCode.executeQuery(); // one and only one result if (results.next()) { concept.setIsDefined( DBUtility.getBooleanFromResultSet(results, SQLTableConstants.TBLCOL_ISDEFINED)); concept.setIsAnonymous( DBUtility.getBooleanFromResultSet(results, SQLTableConstants.TBLCOL_ISANONYMOUS)); concept.setIsActive( DBUtility.getBooleanFromResultSet(results, SQLTableConstants.TBLCOL_ISACTIVE)); if (!si.supports2009Model()) { concept.setStatus(results.getString(SQLTableConstants.TBLCOL_CONCEPTSTATUS)); } else { concept.setEntityCodeNamespace(namespace); } EntityDescription ed = new EntityDescription(); ed.setContent(results.getString(SQLTableConstants.TBLCOL_ENTITYDESCRIPTION)); concept.setEntityDescription(ed); if (si.supports2009Model()) { String owner = results.getString(SQLTableConstants.TBLCOL_OWNER); String status = results.getString(SQLTableConstants.TBLCOL_STATUS); Timestamp effectiveDate = results.getTimestamp(SQLTableConstants.TBLCOL_EFFECTIVEDATE); Timestamp expirationDate = results.getTimestamp(SQLTableConstants.TBLCOL_EXPIRATIONDATE); String revisionId = results.getString(SQLTableConstants.TBLCOL_REVISIONID); String prevRevisionId = results.getString(SQLTableConstants.TBLCOL_PREVREVISIONID); String changeType = results.getString(SQLTableConstants.TBLCOL_CHANGETYPE); String relativeOrder = results.getString(SQLTableConstants.TBLCOL_RELATIVEORDER); EntryState es = new EntryState(); if (!StringUtils.isBlank(changeType)) { es.setChangeType(org.LexGrid.versions.types.ChangeType.valueOf(changeType)); } es.setContainingRevision(revisionId); es.setPrevRevision(prevRevisionId); es.setRelativeOrder(computeRelativeOrder(relativeOrder)); concept.setEntryState(es); if (owner != null) { concept.setOwner(owner); } concept.setStatus(status); concept.setEffectiveDate(effectiveDate); concept.setExpirationDate(expirationDate); } } results.close(); si.checkInPreparedStatement(getEntityCode); if (si.supports2009Model()) { getEntityType = si.checkOutPreparedStatement( "Select * " + " from " + si.getTableName(SQLTableConstants.ENTITY_TYPE) + " where " + si.getSQLTableConstants().codingSchemeNameOrId + " = ? AND " + si.getSQLTableConstants().entityCodeOrId + " = ? AND " + SQLTableConstants.TBLCOL_ENTITYCODENAMESPACE + " = ?"); getEntityType.setString(1, internalCodingSchemeName); getEntityType.setString(2, code); getEntityType.setString(3, namespace); results = getEntityType.executeQuery(); while (results.next()) { concept.addEntityType(results.getString(SQLTableConstants.TBLCOL_ENTITYTYPE)); } results.close(); si.checkInPreparedStatement(getEntityType); } else { concept.addEntityType(SQLTableConstants.ENTITYTYPE_CONCEPT); } // populate the property links String addWhereSegment = (!si.supports2009Model() ? (si.getSQLTableConstants().entityType + " = '" + SQLTableConstants.ENTITYTYPE_CONCEPT + "' and ") : ""); getPropertyLinks = si .checkOutPreparedStatement("Select " + SQLTableConstants.TBLCOL_SOURCEPROPERTYID + ", " + SQLTableConstants.TBLCOL_LINK + ", " + SQLTableConstants.TBLCOL_TARGETPROPERTYID + " from " + si.getTableName(SQLTableConstants.ENTITY_PROPERTY_LINKS) + " where " + addWhereSegment + si.getSQLTableConstants().entityCodeOrEntityId + " = ? and " + si.getSQLTableConstants().codingSchemeNameOrId + " = ?"); getPropertyLinks.setString(1, code); getPropertyLinks.setString(2, internalCodingSchemeName); results = getPropertyLinks.executeQuery(); while (results.next()) { String sourcePropertyId = results.getString(SQLTableConstants.TBLCOL_SOURCEPROPERTYID); String link = results.getString(SQLTableConstants.TBLCOL_LINK); String targetPropertyId = results.getString(SQLTableConstants.TBLCOL_TARGETPROPERTYID); PropertyLink pl = new PropertyLink(); pl.setPropertyLink(link); pl.setSourceProperty(sourcePropertyId); pl.setTargetProperty(targetPropertyId); links.add(pl); } results.close(); si.checkInPreparedStatement(getPropertyLinks); // codedEntry.setModVersion(null); StringBuffer propertyQuery = new StringBuffer(); // I'm constructing a left join query to get the property // results I need from 3 (or 2 in 1.5 table version) different // tables at once, rather than doing a query on each. propertyQuery.append("SELECT a." + SQLTableConstants.TBLCOL_PROPERTYID + ", a." + SQLTableConstants.TBLCOL_PROPERTYNAME + ", a." + SQLTableConstants.TBLCOL_LANGUAGE + ", a." + SQLTableConstants.TBLCOL_FORMAT + ", a." + SQLTableConstants.TBLCOL_ISPREFERRED + ", a." + SQLTableConstants.TBLCOL_DEGREEOFFIDELITY + ", a." + SQLTableConstants.TBLCOL_MATCHIFNOCONTEXT + ", a." + SQLTableConstants.TBLCOL_REPRESENTATIONALFORM + ", a." + SQLTableConstants.TBLCOL_PROPERTYVALUE + ", a." + SQLTableConstants.TBLCOL_PROPERTYTYPE + (si.supports2009Model() ? (", a." + SQLTableConstants.TBLCOL_ENTRYSTATEID) : "") + (si.supports2009Model() ? ", es.*" : "") + ", b." + SQLTableConstants.TBLCOL_TYPENAME + ", b." + SQLTableConstants.TBLCOL_ATTRIBUTEVALUE + ", b." + SQLTableConstants.TBLCOL_VAL1 + ", b." + SQLTableConstants.TBLCOL_VAL2); propertyQuery.append(" FROM "); String codingSchemeName = si.getSQLTableConstants().codingSchemeNameOrId; String concptCode = si.getSQLTableConstants().entityCodeOrEntityId; propertyQuery.append(si.getTableName(SQLTableConstants.ENTITY_PROPERTY) + " {AS} a "); propertyQuery.append( " left join " + si.getTableName(SQLTableConstants.ENTITY_PROPERTY_MULTI_ATTRIBUTES)); propertyQuery.append(" {AS} b on a." + codingSchemeName + " = b." + codingSchemeName + " and a." + concptCode + " = b." + concptCode + " and a." + SQLTableConstants.TBLCOL_PROPERTYID + " = b." + SQLTableConstants.TBLCOL_PROPERTYID); if (si.supports2009Model()) { propertyQuery .append(" left join " + si.getTableName(SQLTableConstants.ENTRY_STATE) + " {AS} es "); propertyQuery.append("on a." + SQLTableConstants.TBLCOL_ENTRYSTATEID); propertyQuery.append(" = es." + SQLTableConstants.TBLCOL_ENTRYSTATEID); } propertyQuery.append(" where a." + concptCode + " = ? " + "and a." + codingSchemeName + " = ?"); if (si.supports2009Model()) { propertyQuery.append(" and a." + SQLTableConstants.TBLCOL_ENTITYCODENAMESPACE + " = ?"); } if (restrictToProperties != null && restrictToProperties.getEntryCount() > 0) { propertyQuery.append(" AND ("); for (int i = 0; i < restrictToProperties.getEntryCount(); i++) { propertyQuery.append(" " + si.getSQLTableConstants().propertyOrPropertyName + " = ? "); if (i + 1 < restrictToProperties.getEntryCount()) { propertyQuery.append(" OR "); } } propertyQuery.append(")"); } if (restrictToPropertyTypes != null && restrictToPropertyTypes.length > 0) { propertyQuery.append(" AND ("); for (int i = 0; i < restrictToPropertyTypes.length; i++) { propertyQuery.append(" " + SQLTableConstants.TBLCOL_PROPERTYTYPE + " = ? "); if (i + 1 < restrictToPropertyTypes.length) { propertyQuery.append(" OR "); } } propertyQuery.append(")"); } getEntityProperties = si.modifyAndCheckOutPreparedStatement(propertyQuery.toString()); int i = 1; getEntityProperties.setString(i++, code); getEntityProperties.setString(i++, internalCodingSchemeName); if (si.supports2009Model()) { getEntityProperties.setString(i++, namespace); } if (restrictToProperties != null && restrictToProperties.getEntryCount() > 0) { for (int j = 0; j < restrictToProperties.getEntryCount(); j++) { getEntityProperties.setString(i++, restrictToProperties.getEntry(j)); } } if (restrictToPropertyTypes != null && restrictToPropertyTypes.length > 0) { for (int j = 0; j < restrictToPropertyTypes.length; j++) { String pts = RestrictionImplementations.mapPropertyType(restrictToPropertyTypes[j]); getEntityProperties.setString(i++, pts); } } results = getEntityProperties.executeQuery(); // store the property from the last row org.LexGrid.commonTypes.Property newProperty = null; // all of the fields that come from the Property table String propertyType, property, propertyValue, language, presentationFormat, degreeOfFidelity, propertyId, representationalForm; Boolean matchIfNoContext, isPreferred; // holders for attributes, qualifiers Hashtable<String, Source> sources = null; HashSet<String> usageContexts = null; Hashtable<String, PropertyQualifier> propertyQualifiers = null; // As I process the result rows, I will get back duplicates of // the property information // if the property has more than one qualifer and/or source , // etc. while (results.next()) { propertyId = results.getString(SQLTableConstants.TBLCOL_PROPERTYID); if (newProperty == null || !propertyId.equals(newProperty.getPropertyId())) { // not equal means we have started a new property property = results.getString(si.getSQLTableConstants().propertyOrPropertyName); propertyType = results.getString(SQLTableConstants.TBLCOL_PROPERTYTYPE); propertyValue = results.getString(SQLTableConstants.TBLCOL_PROPERTYVALUE); language = results.getString(SQLTableConstants.TBLCOL_LANGUAGE); presentationFormat = results .getString(si.getSQLTableConstants().formatOrPresentationFormat); degreeOfFidelity = results.getString(SQLTableConstants.TBLCOL_DEGREEOFFIDELITY); representationalForm = results.getString(SQLTableConstants.TBLCOL_REPRESENTATIONALFORM); matchIfNoContext = DBUtility.getBooleanFromResultSet(results, SQLTableConstants.TBLCOL_MATCHIFNOCONTEXT); isPreferred = DBUtility.getBooleanFromResultSet(results, SQLTableConstants.TBLCOL_ISPREFERRED); // add all of the collected sources, usage contexts, and // qualifiers to // the previous property if (newProperty != null) { newProperty.setSource(sources.values().toArray(new Source[sources.size()])); newProperty.setUsageContext(usageContexts.toArray(new String[usageContexts.size()])); if (!propertyQualifiers.isEmpty()) newProperty.setPropertyQualifier(propertyQualifiers.values() .toArray(new PropertyQualifier[propertyQualifiers.size()])); } // we are starting a new property, so clear out the old // holders. sources = new Hashtable<String, Source>(); usageContexts = new HashSet<String>(); propertyQualifiers = new Hashtable<String, PropertyQualifier>(); // process the property portion of the result if (propertyType.equals(SQLTableConstants.TBLCOLVAL_DEFINITION)) { Definition def = new Definition(); def.setIsPreferred(isPreferred); def.setLanguage(language); def.setPropertyName(property); def.setPropertyId(propertyId); Text text = new Text(); text.setContent(propertyValue); text.setDataType(presentationFormat); def.setValue(text); definitions.add(def); newProperty = def; } else if (propertyType.equals(SQLTableConstants.TBLCOLVAL_PRESENTATION)) { Presentation presentation = new Presentation(); presentation.setIsPreferred(isPreferred); presentation.setLanguage(language); presentation.setPropertyName(property); presentation.setPropertyId(propertyId); Text text = new Text(); text.setContent(propertyValue); text.setDataType(presentationFormat); presentation.setValue(text); presentation.setDegreeOfFidelity(degreeOfFidelity); presentation.setMatchIfNoContext(matchIfNoContext); presentation.setRepresentationalForm(representationalForm); presentations.add(presentation); newProperty = presentation; } else if (propertyType.equals(SQLTableConstants.TBLCOLVAL_COMMENT)) { Comment comment = new Comment(); comment.setLanguage(language); comment.setPropertyName(property); comment.setPropertyId(propertyId); Text text = new Text(); text.setContent(propertyValue); text.setDataType(presentationFormat); comment.setValue(text); comments.add(comment); newProperty = comment; } else { Property theProperty = new Property(); theProperty.setLanguage(language); theProperty.setPropertyName(property); theProperty.setPropertyId(propertyId); Text text = new Text(); text.setContent(propertyValue); text.setDataType(presentationFormat); theProperty.setValue(text); properties.add(theProperty); newProperty = theProperty; } newProperty.setPropertyType(propertyType); if (si.supports2009Model()) { String owner = results.getString(SQLTableConstants.TBLCOL_OWNER); String status = results.getString(SQLTableConstants.TBLCOL_STATUS); Timestamp effectiveDate = results.getTimestamp(SQLTableConstants.TBLCOL_EFFECTIVEDATE); Timestamp expirationDate = results .getTimestamp(SQLTableConstants.TBLCOL_EXPIRATIONDATE); String revisionId = results.getString(SQLTableConstants.TBLCOL_REVISIONID); String prevRevisionId = results.getString(SQLTableConstants.TBLCOL_PREVREVISIONID); String changeType = results.getString(SQLTableConstants.TBLCOL_CHANGETYPE); String relativeOrder = results.getString(SQLTableConstants.TBLCOL_RELATIVEORDER); if (revisionId != null) { EntryState es = new EntryState(); if (!StringUtils.isBlank(changeType)) { es.setChangeType(org.LexGrid.versions.types.ChangeType.valueOf(changeType)); } es.setContainingRevision(revisionId); es.setPrevRevision(prevRevisionId); es.setRelativeOrder(computeRelativeOrder(relativeOrder)); newProperty.setEntryState(es); } if (owner != null) { newProperty.setOwner(owner); } if (status != null) newProperty.setStatus(status); if (effectiveDate != null) newProperty.setEffectiveDate(effectiveDate); if (expirationDate != null) newProperty.setExpirationDate(expirationDate); } } String type = null; String value = null; String val1 = null; String val2 = null; // collect values from the multiAttributes table type = results.getString(SQLTableConstants.TBLCOL_TYPENAME); value = results.getString(SQLTableConstants.TBLCOL_ATTRIBUTEVALUE); val1 = results.getString(SQLTableConstants.TBLCOL_VAL1); if (StringUtils.isBlank(val1)) val1 = null; val2 = results.getString(SQLTableConstants.TBLCOL_VAL2); if (StringUtils.isBlank(val2)) val2 = null; // hashsets to remove dupes (table doesn't allow dupes, but // left join will create some) if (type != null) { if (type.equalsIgnoreCase(SQLTableConstants.TBLCOLVAL_SOURCE)) { if (!sources.containsKey(createUniqueKeyForSource(value, val1))) { Source s = new Source(); s.setContent(value); s.setRole(val2); s.setSubRef(val1); sources.put(createUniqueKeyForSource(value, val1), s); } } else if (type.equalsIgnoreCase(SQLTableConstants.TBLCOLVAL_USAGECONTEXT)) { usageContexts.add(value); } else if (type.equalsIgnoreCase(SQLTableConstants.TBLCOLVAL_QUALIFIER)) { // nulls are a side affect of left join if (!propertyQualifiers.containsKey(val1 + ":" + value)) { PropertyQualifier pq = new PropertyQualifier(); Text txt = new Text(); txt.setContent(val1); pq.setValue(txt); pq.setPropertyQualifierName(value); propertyQualifiers.put(val1 + ":" + value, pq); } } else { getLogger().warn("There is invalid data in the 'typeName' column in the table " + si.getTableName(SQLTableConstants.ENTITY_PROPERTY_MULTI_ATTRIBUTES) + " for the concept code: " + code + " propertyId: " + propertyId + " codingSchemeName: " + internalCodingSchemeName); } } } // add all of the collected sources, usage contexts, and // qualifiers to // the previous property before exiting ... if (newProperty != null) { newProperty.setSource(sources.values().toArray(new Source[sources.size()])); newProperty.setUsageContext(usageContexts.toArray(new String[usageContexts.size()])); if (!propertyQualifiers.isEmpty()) newProperty.setPropertyQualifier(propertyQualifiers.values() .toArray(new PropertyQualifier[propertyQualifiers.size()])); } results.close(); } finally { si.checkInPreparedStatement(getEntityCode); si.checkInPreparedStatement(getEntityProperties); si.checkInPreparedStatement(getPropertyLinks); } concept.setComment(comments.toArray(new Comment[comments.size()])); concept.setDefinition(definitions.toArray(new Definition[definitions.size()])); concept.setPropertyLink(links.toArray(new PropertyLink[links.size()])); concept.setPresentation(presentations.toArray(new Presentation[presentations.size()])); concept.setProperty(properties.toArray(new Property[properties.size()])); return concept; } catch (MissingResourceException e) { throw e; } catch (Exception e) { throw new UnexpectedInternalError("There was an unexpected internal error.", e); } }
From source file:com.vmware.identity.idm.server.config.directory.DirectoryConfigStore.java
@Override public void setAuthnTypesForProvider(String tenantName, String providerName, boolean password, boolean windows, boolean certificate, boolean rsaSecureID) throws Exception { HashSet<Integer> authnTypes = new HashSet<Integer>(); if (password) { authnTypes.add(DirectoryConfigStore.FLAG_AUTHN_TYPE_ALLOW_PASSWORD); }/*from www .j a v a2s . c o m*/ if (windows) { authnTypes.add(DirectoryConfigStore.FLAG_AUTHN_TYPE_ALLOW_WINDOWS); } if (certificate) { authnTypes.add(DirectoryConfigStore.FLAG_AUTHN_TYPE_ALLOW_TLS_CERTIFICATE); } if (rsaSecureID) { authnTypes.add(DirectoryConfigStore.FLAG_AUTHN_TYPE_ALLOW_RSA_SECUREID); } if (authnTypes.size() == 0) { authnTypes.add(DirectoryConfigStore.FLAG_AUTHN_TYPE_ALLOW_NONE); } int[] authTypesArray = ArrayUtils.toPrimitive(authnTypes.toArray(new Integer[authnTypes.size()])); this.setProviderProperty(tenantName, providerName, IdentityProviderLdapObject.PROPERTY_AUTHN_TYPES, ServerUtils.getLdapValue(authTypesArray)); }