List of usage examples for java.util Stack Stack
public Stack()
From source file:eu.annocultor.utils.HierarchyTracingFilter.java
private Set<String> traceBroaderDepthFirst(RepositoryConnection connection, ValueFactory factory, List<StringInStack> topConcepts) throws Exception { // trace skos:broader tree top-down Stack<StringInStack> urlsToCheck = new Stack<StringInStack>(); urlsToCheck.addAll(topConcepts);/*from w w w . java2 s . c om*/ Set<String> passedUrls = new HashSet<String>(); while (!urlsToCheck.isEmpty()) { StringInStack url = urlsToCheck.pop(); if (!StringUtils.isEmpty(url.getString()) && passedUrls.add(url.getString())) { List<StringInStack> children = fetchNarrower(connection, factory, url, urlsToCheck.isEmpty() ? null : urlsToCheck.peek()); Collections.sort(children); urlsToCheck.addAll(children); } } return passedUrls; }
From source file:net.sf.firemox.xml.tbs.Tbs.java
/** * Converts the given tbs XML node to its binary form writing in the given * OutputStream.//from ww w . j ava 2s .c o m * * @see net.sf.firemox.token.IdTokens#PLAYER_REGISTER_SIZE * @see net.sf.firemox.stack.phasetype.PhaseType * @see net.sf.firemox.clickable.ability.SystemAbility * @see net.sf.firemox.tools.StatePicture * @param node * the XML card structure * @param out * output stream where the card structure will be saved * @return the amount of written action in the output. * @throws IOException * error during the writing. * @see net.sf.firemox.deckbuilder.MdbLoader#loadMDB(String, int) */ public final int buildMdb(Node node, OutputStream out) throws IOException { final FileOutputStream fileOut = (FileOutputStream) out; referencedTest = new HashMap<String, Node>(); referencedAbilities = new HashMap<String, Node>(); referencedActions = new HashMap<String, List<Node>>(); referencedAttachments = new HashMap<String, Node>(); referencedNonMacroActions = new HashSet<String>(); referencedNonMacroAttachments = new HashSet<String>(); macroActions = new Stack<List<Node>>(); resolveReferences = false; MToolKit.writeString(out, node.getAttribute("name")); System.out.println("Building " + node.getAttribute("name") + " rules..."); MToolKit.writeString(out, node.getAttribute("version")); MToolKit.writeString(out, node.getAttribute("author")); MToolKit.writeString(out, node.getAttribute("comment")); // Write database configuration final Node database = node.get("database-properties"); Map<String, IdPropertyType> properties = new HashMap<String, IdPropertyType>(); for (java.lang.Object obj : database) { if (obj instanceof Node) { Node nodePriv = (Node) obj; String propertyType = nodePriv.getAttribute("type"); IdPropertyType propertyId; if (propertyType == null || propertyType.equals(String.class.getName())) { if ("true".equalsIgnoreCase(nodePriv.getAttribute("translate"))) { propertyId = IdPropertyType.SIMPLE_TRANSLATABLE_PROPERTY; } else { propertyId = IdPropertyType.SIMPLE_PROPERTY; } } else if ("java.util.List".equals(propertyType)) { if ("true".equalsIgnoreCase(nodePriv.getAttribute("translate"))) { propertyId = IdPropertyType.COLLECTION_TRANSLATABLE_PROPERTY; } else { propertyId = IdPropertyType.COLLECTION_PROPERTY; } } else { throw new InternalError("Unknow property type '" + propertyType + "'"); } properties.put(nodePriv.getAttribute("name"), propertyId); } } out.write(properties.size()); for (Map.Entry<String, IdPropertyType> entry : properties.entrySet()) { entry.getValue().serialize(out); MToolKit.writeString(out, entry.getKey()); } MToolKit.writeString(out, node.getAttribute("art-url")); MToolKit.writeString(out, node.getAttribute("back-picture")); MToolKit.writeString(out, node.getAttribute("damage-picture")); MToolKit.writeString(out, (String) node.get("licence").get(0)); // Manas final Node manas = node.get("mana-symbols"); // Colored manas final Node colored = manas.get("colored"); MToolKit.writeString(out, colored.getAttribute("url")); MToolKit.writeString(out, colored.getAttribute("big-url")); for (java.lang.Object obj : colored) { if (obj instanceof Node) { Node nodePriv = (Node) obj; out.write(XmlTools.getValue(nodePriv.getAttribute("name"))); MToolKit.writeString(out, nodePriv.getAttribute("picture")); MToolKit.writeString(out, nodePriv.getAttribute("big-picture")); } } // Colorless manas final Node colorless = manas.get("colorless"); MToolKit.writeString(out, colorless.getAttribute("url")); MToolKit.writeString(out, colorless.getAttribute("big-url")); MToolKit.writeString(out, colorless.getAttribute("unknown")); out.write(colorless.getNbNodes()); for (java.lang.Object obj : colorless) { if (obj instanceof Node) { final Node nodePriv = (Node) obj; out.write(Integer.parseInt(nodePriv.getAttribute("amount"))); MToolKit.writeString(out, nodePriv.getAttribute("picture")); } } // Hybrid manas final Node hybrid = manas.get("hybrid"); MToolKit.writeString(out, hybrid.getAttribute("url")); for (Object obj : hybrid) { if (obj instanceof Node) { final Node nodePriv = (Node) obj; out.write(XmlTools.getValue(nodePriv.getAttribute("name"))); MToolKit.writeString(out, nodePriv.getAttribute("picture")); } } // phyrexian manas final Node phyrexian = manas.get("phyrexian"); MToolKit.writeString(out, phyrexian.getAttribute("url")); for (Object obj : phyrexian) { if (obj instanceof Node) { final Node nodePriv = (Node) obj; out.write(XmlTools.getValue(nodePriv.getAttribute("name"))); MToolKit.writeString(out, nodePriv.getAttribute("picture")); } } // Prepare the shortcut to card's bytes offset final long shortcutCardBytes = fileOut.getChannel().position(); MToolKit.writeInt24(out, 0); // Write the user defined deck constraints final Set<String> definedConstraints = new HashSet<String>(); final Node deckConstraintRoot = XmlTools.getExternalizableNode(node, "deck-constraints"); final List<Node> deckConstraints = deckConstraintRoot.getNodes("deck-constraint"); XmlTools.writeAttrOptions(deckConstraintRoot, "deckbuilder-min-property", out); XmlTools.writeAttrOptions(deckConstraintRoot, "deckbuilder-max-property", out); XmlTools.writeAttrOptions(deckConstraintRoot, "master", out); out.write(deckConstraints.size()); for (Node deckConstraint : deckConstraints) { // Write the constraint key name String deckName = deckConstraint.getAttribute("name"); MToolKit.writeString(out, deckName); // Write extend String extend = deckConstraint.getAttribute("extends"); MToolKit.writeString(out, extend); if (extend != null && extend.length() > 0 && !definedConstraints.contains(extend)) { throw new RuntimeException("'" + deckName + "' is supposed extending '" + extend + "' but has not been found. Note that declaration order is important."); } // Write the constraint XmlTools.defaultOnMeTag = false; XmlTest.getTest("test").buildMdb(deckConstraint, out); definedConstraints.add(deckName); } // END OF HEADER // additional zones final List<XmlParser.Node> additionalZones = node.get("layouts").get("zones").get("additional-zones") .getNodes("additional-zone"); out.write(additionalZones.size()); int zoneId = IdZones.FIRST_ADDITIONAL_ZONE; for (XmlParser.Node additionalZone : additionalZones) { final String zoneName = additionalZone.getAttribute("name"); if (zoneId > IdZones.LAST_ADDITIONAL_ZONE) { throw new RuntimeException( "Cannot add more additional-zone (" + zoneName + "), increase core limitation"); } XmlTools.zones.put(zoneName, zoneId++); MToolKit.writeString(out, zoneName); MToolKit.writeString(out, additionalZone.getAttribute("layout-class")); MToolKit.writeString(out, additionalZone.getAttribute("constraint-you")); MToolKit.writeString(out, additionalZone.getAttribute("constraint-opponent")); } // Initial zone id out.write(XmlTools.getZone(node.get("layouts").get("zones").getAttribute("default-zone"))); // the references final Node references = XmlTools.getExternalizableNode(node, "references"); // the tests references System.out.println("\tshared tests..."); XmlTools.defaultOnMeTag = true; final Node tests = references.get("tests"); if (tests == null) { out.write(0); } else { out.write(tests.getNbNodes()); for (java.lang.Object obj : tests) { if (obj instanceof Node) { String ref = ((Node) obj).getAttribute("reference-name").toString(); referencedTest.put(ref, (Node) obj); MToolKit.writeString(out, ref); for (java.lang.Object objTest : (Node) obj) { if (objTest instanceof Node) { final Node node1 = (Node) objTest; try { XmlTest.getTest(node1.getTag()).buildMdb(node1, out); } catch (Throwable ie) { XmlConfiguration.error("In referenced test '" + ref + "' : " + ie.getMessage() + ". Context=" + objTest); } break; } } } } } // the action references (not included into MDB) final Node actions = references.get("actions"); System.out.print("\tactions : references (inlined in MDB)"); if (actions != null) { for (java.lang.Object obj : actions) { if (obj instanceof Node) { final String ref = ((Node) obj).getAttribute("reference-name"); final String globalName = ((Node) obj).getAttribute("name"); // do not accept macro? if ("false".equals(((Node) obj).getAttribute("macro"))) { referencedNonMacroActions.add(ref); } final List<Node> actionList = new ArrayList<Node>(); boolean firstIsDone = false; for (java.lang.Object actionI : (Node) obj) { if (actionI instanceof Node) { final Node action = (Node) actionI; // add action to the action list and replace the name of // sub-actions if (action.getAttribute("name") == null) { if (globalName != null) { if (firstIsDone) { action.addAttribute(new XmlParser.Attribute("name", "%" + globalName)); } else { action.addAttribute(new XmlParser.Attribute("name", globalName)); firstIsDone = true; } } else if (firstIsDone) { action.addAttribute(new XmlParser.Attribute("name", "%" + ref)); } else { action.addAttribute(new XmlParser.Attribute("name", ref)); firstIsDone = true; } } else if (!firstIsDone) { firstIsDone = true; } actionList.add((Node) actionI); } } // add this reference referencedActions.put(ref, actionList); } } } // the attachment references (not included into MDB) final Node attachments = references.get("attachments"); System.out.print(", attachments"); if (attachments != null) { for (java.lang.Object obj : attachments) { if (obj instanceof Node) { final String ref = ((Node) obj).getAttribute("reference-name"); // do not accept macro? if ("false".equals(((Node) obj).getAttribute("macro"))) { referencedNonMacroAttachments.add(ref); } // add this reference referencedAttachments.put(ref, (Node) obj); } } } // action pictures final Node actionsPictures = node.get("action-pictures"); System.out.print(", pictures"); if (actionsPictures == null) { out.write(0); out.write('\0'); } else { MToolKit.writeString(out, actionsPictures.getAttribute("url")); out.write(actionsPictures.getNbNodes()); for (java.lang.Object obj : actionsPictures) { if (obj instanceof Node) { final Node actionPicture = (Node) obj; MToolKit.writeString(out, actionPicture.getAttribute("name")); MToolKit.writeString(out, actionPicture.getAttribute("picture")); } } } // constraints on abilities linked to action final Node constraints = node.get("action-constraints"); System.out.println(", constraints"); if (constraints == null) { out.write(0); } else { out.write(constraints.getNbNodes()); for (java.lang.Object obj : constraints) { if (obj instanceof Node) { final Node constraint = (Node) obj; for (java.lang.Object objA : constraint.get("actions")) { if (objA instanceof Node) { XmlAction.getAction(((Node) objA).getTag()).buildMdb((Node) objA, out); break; } } if ("or".equals(constraint.getAttribute("operation"))) { IdOperation.OR.serialize(out); } else { IdOperation.AND.serialize(out); } XmlTest.getTest("test").buildMdb(constraint.get("test"), out); } } } // objects defined in this TBS System.out.println("\tobjects..."); final List<Node> objects = node.get("objects").getNodes("object"); out.write(objects.size()); for (Node object : objects) { // write object final XmlParser.Attribute objectName = new XmlParser.Attribute("name", object.getAttribute("name")); boolean onePresent = false; for (java.lang.Object modifierTmp : object) { if (modifierTmp instanceof Node) { // write the 'has-next' flag if (onePresent) { out.write(1); } // write the object-modifier final Node modifier = (Node) modifierTmp; modifier.addAttribute(objectName); XmlModifier.getModifier(modifier.getTag()).buildMdb(modifier, out); // Write the 'paint' flag if (onePresent) { out.write(0); } else { out.write(1); } onePresent = true; } } if (!onePresent) { // no modifier associated to this object, we write a virtual ONE ModifierType.REGISTER_MODIFIER.serialize(out); XmlModifier.buildMdbModifier(object, out); // Write the modified register index && value XmlTools.writeConstant(out, 0); XmlTools.writeConstant(out, 0); IdOperation.ADD.serialize(out); // Write the 'paint' flag out.write(1); } // Write the 'has-next' flag out.write(0); } // the abilities references System.out.println("\tshared abilities..."); Node abilities = references.get("abilities"); out.write(abilities.getNbNodes()); macroActions.push(null); for (Node ability : abilities.getNodes("ability")) { String ref = ability.getAttribute("reference-name").toString(); referencedAbilities.put(ref, ability); MToolKit.writeString(out, ref); try { Node node1 = (Node) ability.get(1); XmlTbs.getTbsComponent(node1.getTag()).buildMdb(node1, out); } catch (Throwable ie) { XmlConfiguration.error("Error In referenced ability '" + ref + "' : " + ie.getMessage() + "," + ie + ". Context=" + ability); } } macroActions.pop(); // damage types name System.out.println("\tdamage types..."); Collections.sort(XmlConfiguration.EXPORTED_DAMAGE_TYPES); int count = XmlConfiguration.EXPORTED_DAMAGE_TYPES.size(); out.write(count); for (int i = 0; i < count; i++) { final PairStringInt pair = XmlConfiguration.EXPORTED_DAMAGE_TYPES.get(i); MToolKit.writeString(out, pair.text); MToolKit.writeInt16(out, pair.value); } /** * <ul> * CARD'S PART : * <li>state pictures * <li>tooltip filters * <li>exported types name * <li>exported sorted properties name * <li>implemented cards * </ul> */ // state pictures System.out.println("\tstates"); final Node states = node.get("state-pictures"); if (states == null) { out.write(0); } else { out.write(states.getNbNodes()); for (java.lang.Object obj : states) { if (obj instanceof Node) { final Node ns = (Node) obj; MToolKit.writeString(out, ns.getAttribute("picture")); MToolKit.writeString(out, ns.getAttribute("name")); MToolKit.writeInt16(out, XmlTools.getInt(ns.getAttribute("state"))); out.write(XmlTools.getInt(ns.getAttribute("index"))); final int x = XmlTools.getInt(ns.getAttribute("x")); final int y = XmlTools.getInt(ns.getAttribute("y")); if (MToolKit.getConstant(x) == -1 && MToolKit.getConstant(y) != -1 || MToolKit.getConstant(x) != -1 && MToolKit.getConstant(y) == -1) { XmlConfiguration.error( "In state-picture '-1' value is allowed if and only if x AND y have this value."); } MToolKit.writeInt16(out, XmlTools.getInt(ns.getAttribute("x"))); MToolKit.writeInt16(out, XmlTools.getInt(ns.getAttribute("y"))); MToolKit.writeInt16(out, XmlTools.getInt(ns.getAttribute("width"))); MToolKit.writeInt16(out, XmlTools.getInt(ns.getAttribute("height"))); XmlTest.getTest("test").buildMdb(node.get("display-test"), out); } } } // tooltip filters System.out.println("\ttooltip filters..."); final Node ttFilters = node.get("tooltip-filters"); XmlTools.defaultOnMeTag = false; if (ttFilters == null) { out.write(0); } else { out.write(ttFilters.getNbNodes()); for (java.lang.Object obj : ttFilters) { if (obj instanceof Node) { buildMdbTooltipFilter((Node) obj, out); } } } // exported types name System.out.println("\texported type..."); Collections.sort(XmlConfiguration.EXPORTED_TYPES); int nbTypes = XmlConfiguration.EXPORTED_TYPES.size(); out.write(nbTypes); for (int i = 0; i < nbTypes; i++) { final PairStringInt pair = XmlConfiguration.EXPORTED_TYPES.get(i); MToolKit.writeString(out, pair.text); MToolKit.writeInt16(out, pair.value); } // exported sorted properties name and associated pictures System.out.println("\tproperties..."); Collections.sort(XmlConfiguration.EXPORTED_PROPERTIES); final int nbProperties = XmlConfiguration.EXPORTED_PROPERTIES.size(); MToolKit.writeInt16(out, nbProperties); for (int i = 0; i < nbProperties; i++) { final PairStringInt pair = XmlConfiguration.EXPORTED_PROPERTIES.get(i); MToolKit.writeInt16(out, pair.value); MToolKit.writeString(out, pair.text); } MToolKit.writeInt16(out, XmlConfiguration.PROPERTY_PICTURES.size()); for (Map.Entry<Integer, String> entry : XmlConfiguration.PROPERTY_PICTURES.entrySet()) { MToolKit.writeInt16(out, entry.getKey()); MToolKit.writeString(out, entry.getValue()); } /** * <ul> * STACK MANAGER'S PART : * <li>first player registers * <li>second player registers * <li>abortion zone * </ul> */ // player registers System.out.println("\tinitial registers..."); Node registers = node.get("registers-first-player"); final byte[] registersBytes = new byte[IdTokens.PLAYER_REGISTER_SIZE]; if (registers != null) { final List<Node> list = registers.getNodes("register"); for (Node register : list) { registersBytes[XmlTools.getInt(register.getAttribute("index"))] = (byte) XmlTools .getInt(register.getAttribute("value")); } } out.write(registersBytes); registers = node.get("registers-second-player"); final byte[] registersBytes2 = new byte[IdTokens.PLAYER_REGISTER_SIZE]; if (registers != null) { final List<Node> list = registers.getNodes("register"); for (Node register : list) { registersBytes2[XmlTools.getInt(register.getAttribute("index"))] = (byte) XmlTools .getInt(register.getAttribute("value")); } } out.write(registersBytes2); /* * TODO abortion zone */ final Node refAbilities = node.get("abilities"); out.write(XmlTools.getZone(refAbilities.getAttribute("abortionzone"))); // additional costs System.out.println("\tadditional-costs..."); final List<Node> additionalCosts = node.get("additional-costs").getNodes("additional-cost"); out.write(additionalCosts.size()); for (Node additionalCost : additionalCosts) { XmlTest.getTest("test").buildMdb(additionalCost.get("test"), out); XmlTbs.writeActionList(additionalCost.get("cost"), out); } /** * <ul> * EVENT MANAGER'S PART : * <li>phases * <li>turn-structure * <li>first phase index * </ul> */ // phases System.out.println("\tphases..."); final Node phases = node.get("phases"); out.write(phases.getNbNodes()); for (java.lang.Object obj : phases) { if (obj instanceof Node) { buildMdbPhaseType((Node) obj, out); } } // turn structure final String list = phases.getAttribute("turn-structure"); System.out.println("\tturn structure..."); final String[] arrayid = list.split(" "); out.write(arrayid.length); for (String id : arrayid) { out.write(XmlTools.getAliasValue(id)); } // first phase index for first turn out.write(Integer.parseInt(phases.getAttribute("start"))); // state based abilities System.out.println("\trule abilities..."); out.write(refAbilities.getNbNodes()); for (java.lang.Object obj : refAbilities) { if (obj instanceof Node) { try { XmlTbs.getTbsComponent(((Node) obj).getTag()).buildMdb((Node) obj, out); } catch (Throwable ie) { XmlConfiguration.error("Error in system ability '" + ((Node) obj).getAttribute("name") + "' : " + ie.getMessage() + ". Context=" + obj); break; } } } // static-modifiers System.out.println("\tstatic-modifiers..."); final Node modifiers = node.get("static-modifiers"); if (modifiers == null) { out.write(0); } else { out.write(modifiers.getNbNodes()); for (java.lang.Object obj : modifiers) { if (obj instanceof Node) { XmlModifier.getModifier("static-modifier").buildMdb((Node) obj, out); } } } // layouts System.out.println("\tlayouts..."); final Node layouts = node.get("layouts"); // initialize task pane layout writeTaskPaneElement(layouts.get("common-panel").get("card-details").get("properties"), out); // Sector of play zone for layouts List<Node> sectors = layouts.get("zones").get("play").getNodes("sector"); out.write(sectors.size()); for (XmlParser.Node sector : sectors) { XmlTest.getTest("test").buildMdb(sector, out); MToolKit.writeString(out, sector.getAttribute("constraint")); } // Update the shortcut to the first bytes of cards final long cardBytesPosition = fileOut.getChannel().position(); fileOut.getChannel().position(shortcutCardBytes); MToolKit.writeInt24(out, (int) cardBytesPosition); fileOut.getChannel().position(cardBytesPosition); // cards bytes + names resolveReferences = true; System.out.println("Processing cards..."); String xmlFile = node.getAttribute("xmlFile"); try { final String baseName = FilenameUtils.getBaseName(xmlFile); XmlTbs.updateMdb(baseName, out); } catch (Throwable e2) { XmlConfiguration.error("Error found in cards parsing of rule '" + xmlFile + "' : " + e2.getMessage()); } System.out.println(node.getAttribute("name") + " rules finished"); return 0; }
From source file:io.fabric8.maven.enricher.fabric8.AbstractLiveEnricher.java
/** * Creates an Iterable to walk the exception from the bottom up * (the last caused by going upwards to the root exception). * * @param exception the exception/* w w w . ja v a 2 s. co m*/ * @return the Iterable * @see java.lang.Iterable */ protected Stack<Throwable> unfoldExceptions(Throwable exception) { Stack<Throwable> throwables = new Stack<>(); Throwable current = exception; // spool to the bottom of the caused by tree while (current != null) { throwables.push(current); current = current.getCause(); } return throwables; }
From source file:com.stratumsoft.xmlgen.SchemaTypeXmlGenerator.java
private void init() { factory = DocumentFactory.getInstance(); outputFormat = options.getOutputFormat(); outputFormat.setExpandEmptyElements(true); //expand elements into form <a></a> instead of <a/>; TBD: expose processedTypes = new ArrayList<>(); recursiveCount = new HashMap<>(); schemaStack = new Stack<>(); initNSMap();/* w w w. j a v a2s . c om*/ }
From source file:com.nextep.designer.sqlclient.ui.helpers.SQLHelper.java
private static DMLParseResult parseSQL(String sql, int start) { final ISQLParser parser = GeneratorFactory.getSQLParser(DBGMHelper.getCurrentVendor()); // Retrieving the corresponding statement start IDocument doc = new Document(); doc.set(sql + " "); //$NON-NLS-1$ FindReplaceDocumentAdapter finder = new FindReplaceDocumentAdapter(doc); try {/* w w w .j a v a 2s.co m*/ IRegion lastSemicolonRegion = finder.find(start - 1, ";", false, false, false, false); //$NON-NLS-1$ if (lastSemicolonRegion == null) { lastSemicolonRegion = new Region(0, 1); } IRegion selectRegion = finder.find(lastSemicolonRegion.getOffset(), "SELECT|INSERT|UPDATE|DELETE", true, //$NON-NLS-1$ false, false, true); IRegion endSemicolonRegion = finder.find(start == doc.getLength() ? start - 1 : start, ";", true, false, //$NON-NLS-1$ false, false); if (endSemicolonRegion == null) { endSemicolonRegion = new Region(doc.getLength() - 1, 0); } if (selectRegion == null || lastSemicolonRegion == null || endSemicolonRegion == null) { return null; } // The select must be found after the first semicolon, else it is not the // same SQL statement if (selectRegion.getOffset() >= lastSemicolonRegion.getOffset() && endSemicolonRegion.getOffset() >= selectRegion.getOffset()) { DMLScanner scanner = new DMLScanner(parser); scanner.setRange(doc, selectRegion.getOffset(), endSemicolonRegion.getOffset() - selectRegion.getOffset()); IToken token = scanner.nextToken(); DMLParseResult result = new DMLParseResult(); Stack<DMLParseResult> stack = new Stack<DMLParseResult>(); Map<Segment, DMLParseResult> results = new HashMap<Segment, DMLParseResult>(); while (!token.isEOF()) { // Counting parenthethis if (token == DMLScanner.LEFTPAR_TOKEN) { result.parCount++; } else if (token == DMLScanner.RIGHTPAR_TOKEN) { result.parCount--; } if (token == DMLScanner.SELECT_TOKEN) { // && (result.tableSegStart>0 || // result.whereSegStart>0)) { stack.push(result); result = new DMLParseResult(); result.stackStart = scanner.getTokenOffset(); } else if (token == DMLScanner.RIGHTPAR_TOKEN && result.parCount < 0) { // && // stack.size()>0) // { results.put(new Segment(result.stackStart, scanner.getTokenOffset() - result.stackStart), result); result = stack.pop(); } else if (token == DMLScanner.INSERT_TOKEN) { result.ignoreInto = false; } else if (token == DMLScanner.FROM_TOKEN || token == DMLScanner.UPDATE_TOKEN || (token == DMLScanner.INTO_TOKEN && !result.ignoreInto)) { result.ignoreInto = true; // We have a table segment start result.tableSegStart = scanner.getTokenOffset(); result.tableStartToken = token; } else if (token == DMLScanner.WORD_TOKEN && result.tableSegStart > 0) { // We are in a table segment so we instantiate appropriate table references // and aliases // in the parse result if (result.lastAlias == null) { // This is a new table definition, we add it result.lastAlias = new TableAlias( doc.get(scanner.getTokenOffset(), scanner.getTokenLength()).toUpperCase()); // result.lastAlias // .setTable(tablesMap.get(result.lastAlias.getTableName())); result.addFromTable(result.lastAlias); } else if (result.lastAlias.getTableAlias() == null) { // This is an alias of a defined table final String alias = doc.get(scanner.getTokenOffset(), scanner.getTokenLength()); final List<String> reservedWords = parser.getTypedTokens().get(ISQLParser.DML); if (!reservedWords.contains(alias.toUpperCase())) { result.lastAlias.setAlias(alias); } else { result.lastAlias = null; } } } else if (token == DMLScanner.COMMA_TOKEN) { // On a comma, we reset any table reference result.lastAlias = null; } else if (token == DMLScanner.DML_TOKEN) { result.lastAlias = null; if (result.tableSegStart != -1) { int tableSegEnd = scanner.getTokenOffset(); result.addTableSegment( new Segment(result.tableSegStart, tableSegEnd - result.tableSegStart)); result.tableSegStart = -1; } } else if (result.tableSegStart != -1 && ((result.tableStartToken == DMLScanner.FROM_TOKEN && token == DMLScanner.WHERE_TOKEN) || (result.tableStartToken == DMLScanner.UPDATE_TOKEN && token == DMLScanner.SET_TOKEN) || (result.tableStartToken == DMLScanner.INTO_TOKEN && token == DMLScanner.LEFTPAR_TOKEN))) { // We have matched a table segment end, so we close the segment // and we add it to the parse result's table segments int tableSegEnd = scanner.getTokenOffset(); result.addTableSegment( new Segment(result.tableSegStart, tableSegEnd - result.tableSegStart)); result.tableSegStart = -1; if (token == DMLScanner.WHERE_TOKEN) { result.whereSegStart = scanner.getTokenOffset() + scanner.getTokenLength(); } } token = scanner.nextToken(); } // If the table segment is still opened, we close it at the end of the SQL statement if (result.tableSegStart > -1) { int tableSegEnd = endSemicolonRegion.getOffset(); result.addTableSegment( new Segment(result.tableSegStart, tableSegEnd - result.tableSegStart + 1)); } // Locating the appropriate result for (Segment s : results.keySet()) { if (s.getOffset() <= start && s.getOffset() + s.getLength() > start) { return results.get(s); } } return result; } } catch (BadLocationException e) { LOGGER.debug("Problems while retrieving SQL statement"); } return null; }
From source file:net.iponweb.hadoop.streaming.parquet.TextRecordWriterWrapper.java
@Override public void write(Text key, Text value) throws IOException { Group grp = factory.newGroup(); String[] strK = key.toString().split(TAB, -1); String[] strV = value == null ? new String[0] : value.toString().split(TAB, -1); String kv_combined[] = (String[]) ArrayUtils.addAll(strK, strV); Iterator<PathAction> ai = recorder.iterator(); Stack<Group> groupStack = new Stack<>(); groupStack.push(grp);/*from w w w .j av a 2 s . c o m*/ int i = 0; try { while (ai.hasNext()) { PathAction a = ai.next(); switch (a.getAction()) { case GROUPEND: grp = groupStack.pop(); break; case GROUPSTART: groupStack.push(grp); grp = grp.addGroup(a.getName()); break; case FIELD: String s = null; PrimitiveType.PrimitiveTypeName primType = a.getType(); String colName = a.getName(); if (i < kv_combined.length) s = kv_combined[i++]; if (s == null) { if (a.getRepetition() == Type.Repetition.OPTIONAL) { i++; continue; } s = primType == PrimitiveType.PrimitiveTypeName.BINARY ? "" : "0"; } // If we have 'repeated' field, assume that we should expect JSON-encoded array // Convert array and append all values int repetition = 1; boolean repeated = false; ArrayList<String> s_vals = null; if (a.getRepetition() == Type.Repetition.REPEATED) { repeated = true; s_vals = new ArrayList<>(); ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(s); Iterator<JsonNode> itr = node.iterator(); repetition = 0; while (itr.hasNext()) { String o; switch (primType) { case BINARY: o = itr.next().getTextValue(); // No array-of-objects! break; case BOOLEAN: o = String.valueOf(itr.next().getBooleanValue()); break; default: o = String.valueOf(itr.next().getNumberValue()); } s_vals.add(o); repetition++; } } for (int j = 0; j < repetition; j++) { if (repeated) // extract new s s = s_vals.get(j); try { switch (primType) { case INT32: grp.append(colName, new Double(Double.parseDouble(s)).intValue()); break; case INT64: case INT96: grp.append(colName, new Double(Double.parseDouble(s)).longValue()); break; case DOUBLE: grp.append(colName, Double.parseDouble(s)); break; case FLOAT: grp.append(colName, Float.parseFloat(s)); break; case BOOLEAN: grp.append(colName, s.equalsIgnoreCase("true") || s.equals("1")); break; case BINARY: grp.append(colName, Binary.fromString(s)); break; default: throw new RuntimeException("Can't handle type " + primType); } } catch (NumberFormatException e) { grp.append(colName, 0); } } } } realWriter.write(null, (SimpleGroup) grp); } catch (InterruptedException e) { Thread.interrupted(); throw new IOException(e); } catch (Exception e) { ByteArrayOutputStream out = new ByteArrayOutputStream(); e.printStackTrace(new PrintStream(out)); throw new RuntimeException("Failed on record " + grp + ", schema=" + schema + ", path action=" + recorder + " exception = " + e.getClass() + ", msg=" + e.getMessage() + ", cause=" + e.getCause() + ", trace=" + out.toString()); } }
From source file:net.bulletin.pdi.xero.step.support.XMLChunkerTest.java
/** * <p>This test is checking to see that, without any container elements, the chunking will produce one * document and that single document should be the whole of the input.</p> */// w w w . j a v a 2s. co m @Test public void testPullNextXmlChunk_withoutContainerElements() throws Exception { byte[] sampleXml = readSampleXml(); XMLChunker chunker = new XMLChunkerImpl( XMLInputFactory.newInstance().createXMLStreamReader(new ByteArrayInputStream(sampleXml)), // all in-memory new Stack<String>()); // --------------------------------- String actuals[] = new String[] { chunker.pullNextXmlChunk(), chunker.pullNextXmlChunk() }; // --------------------------------- // This will work through the chunks and check specific information it knows in the sample. { DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); XPath xPath = XPathFactory.newInstance().newXPath(); org.w3c.dom.Document doc = documentBuilder .parse(new ByteArrayInputStream(actuals[0].getBytes(CharEncoding.UTF_8))); NodeList artistNodeList = (NodeList) xPath.evaluate("/Response/Artists/Artist", doc, XPathConstants.NODESET); Assert.assertEquals(3, artistNodeList.getLength()); } Assert.assertNull("expected the last chunk to be null", actuals[1]); }
From source file:eu.annocultor.converter.ConverterHandler.java
public void multiFileStartDocument() throws SAXException { super.startDocument(); tagPath = new Stack<Path>(); tagBeingIgnored = null;//from w ww . j a va 2 s. co m passedARecord = false; }
From source file:com.push.app.HomeActivity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); fragmentStack = new Stack<>(); sharedPreferences = getSharedPreferences("preferences", Activity.MODE_PRIVATE); aq = new AQuery(this); setSupportActionBar((Toolbar) findViewById(R.id.toolbar)); isNotification = getIntent().getBooleanExtra("is_notification", false); mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.activity_main_swipe_refresh_layout); mHomeLayout = (FrameLayout) findViewById(R.id.mHomeLayout); mSearchView = (FrameLayout) findViewById(R.id.mSearchView); mToolbarView = (Toolbar) findViewById(R.id.toolbar); getSupportActionBar().setDisplayShowHomeEnabled(true); getSupportActionBar().setDisplayUseLogoEnabled(true); getSupportActionBar().setLogo(R.mipmap.logo); getSupportActionBar().setTitle(""); imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); //Setup the drawer //setUpDrawer(); mListView = (ObservableListView) findViewById(R.id.mList); initViews();/*from w w w . jav a2s . c om*/ mListView.setBackgroundColor(Color.WHITE); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { checkForNewContent(); } }); if (isNotification) { String extra = getIntent().getExtras() .getString(Notification.DefaultNotificationHandler.INTENT_EXTRAS_KEY); Utils.log("Extras -> " + extra); try { JSONObject extrasObject = new JSONObject(extra); JSONObject extras = extrasObject.getJSONObject("payload").getJSONObject("extras"); JSONObject additionalInfo = extras.getJSONObject("additionalInfo"); Utils.log("Extras payload -> " + extras); if (additionalInfo.has("action") && additionalInfo.getString("action").equalsIgnoreCase("donation")) { Utils.log("Displaying donation page"); displayView(1); return; } else if (additionalInfo.has("article_id")) { mSwipeRefreshLayout.setRefreshing(true); if (restAPI == null) { setUpRestApi(); } restAPI.getArticle(additionalInfo.getString("article_id"), new Callback<ArticlePost>() { @Override public void success(ArticlePost articlePost, Response response) { mSwipeRefreshLayout.setRefreshing(false); Intent i = new Intent(HomeActivity.this, DetailPostActivity.class); PostFragmentAdapter.postItems.clear(); PostFragmentAdapter.postItems.add(articlePost.getResults().get(0)); i.putExtra("postPosition", 0); i.putExtra("postTitle", articlePost.getResults().get(0).getHeadline()); i.putExtra("description", articlePost.getResults().get(0).getDescription()); cachePosts("searchResults", articlePost);//cache these results startActivity(i); } @Override public void failure(RetrofitError error) { mSwipeRefreshLayout.setRefreshing(false); Log.e("ERROR", "Failed to parse JSON ", error); } }); } } catch (JSONException ex) { Utils.log("Error loading post -> " + ex.getMessage()); } } }
From source file:grails.converters.JSON.java
private void prepareRender(Writer out) { writer = prettyPrint ? new PrettyPrintJSONWriter(out) : new JSONWriter(out); if (circularReferenceBehaviour == CircularReferenceBehaviour.PATH) { if (log.isInfoEnabled()) { log.info(String.format("Using experimental CircularReferenceBehaviour.PATH for %s", getClass().getName())); }/*from w w w .j a v a 2 s .c o m*/ writer = new PathCapturingJSONWriterWrapper(writer); } referenceStack = new Stack<Object>(); }