List of usage examples for javax.xml.stream XMLOutputFactory newFactory
public static XMLOutputFactory newFactory() throws FactoryConfigurationError
From source file:fr.ritaly.dungeonmaster.item.ItemDef.java
public static void main(String[] args) throws Exception { final List<Item.Type> types = Arrays.asList(Item.Type.values()); Collections.sort(types, new Comparator<Item.Type>() { @Override/*from ww w. j a v a 2 s. co m*/ public int compare(Type o1, Type o2) { return o1.name().compareTo(o2.name()); } }); final StringWriter stringWriter = new StringWriter(32000); final XMLStreamWriter writer = new IndentingXMLStreamWriter( XMLOutputFactory.newFactory().createXMLStreamWriter(stringWriter)); writer.writeStartDocument(); writer.writeStartElement("items"); writer.writeDefaultNamespace("yadmjc:items:1.0"); for (Item.Type type : types) { writer.writeStartElement("item"); writer.writeAttribute("id", type.name()); writer.writeAttribute("weight", Float.toString(type.getWeight())); if (type.getDamage() != -1) { writer.writeAttribute("damage", Integer.toString(type.getDamage())); } if (type.getActivationBodyPart() != null) { writer.writeAttribute("activation", type.getActivationBodyPart().name()); } if (type.getShield() != 0) { writer.writeAttribute("shield", Integer.toString(type.getShield())); } if (type.getAntiMagic() != 0) { writer.writeAttribute("anti-magic", Integer.toString(type.getAntiMagic())); } if (type.getDecayRate() != -1) { writer.writeAttribute("decay-rate", Integer.toString(type.getDecayRate())); } if (type.getDistance() != -1) { writer.writeAttribute("distance", Integer.toString(type.getDistance())); } if (type.getShootDamage() != -1) { writer.writeAttribute("shoot-damage", Integer.toString(type.getShootDamage())); } if (!type.getCarryLocations().isEmpty()) { writer.writeStartElement("locations"); // Sort the locations to ensure they're always serialized in a consistent way for (CarryLocation location : new TreeSet<CarryLocation>(type.getCarryLocations())) { writer.writeEmptyElement("location"); writer.writeAttribute("id", location.name()); } writer.writeEndElement(); } if (!type.getActions().isEmpty()) { writer.writeStartElement("actions"); for (ActionDef actionDef : type.getActions()) { writer.writeEmptyElement("action"); writer.writeAttribute("id", actionDef.getAction().name()); if (actionDef.getMinLevel() != Champion.Level.NONE) { writer.writeAttribute("min-level", actionDef.getMinLevel().name()); } if (actionDef.isUseCharges()) { writer.writeAttribute("use-charges", Boolean.toString(actionDef.isUseCharges())); } } writer.writeEndElement(); // </actions> } if (!type.getEffects().isEmpty()) { writer.writeStartElement("effects"); for (Effect effect : type.getEffects()) { writer.writeEmptyElement("effect"); writer.writeAttribute("stat", effect.getStatistic().name()); writer.writeAttribute("strength", String.format("%+d", effect.getStrength())); } writer.writeEndElement(); // </effects> } writer.writeEndElement(); // </item> } writer.writeEndElement(); // </items> writer.writeEndDocument(); System.out.println(stringWriter); }
From source file:fr.ritaly.dungeonmaster.ai.CreatureDef.java
public static void main(String[] args) throws Exception { final List<Creature.Type> types = Arrays.asList(Creature.Type.values()); Collections.sort(types, new Comparator<Creature.Type>() { @Override//from w w w.ja va 2s .c o m public int compare(Creature.Type o1, Creature.Type o2) { return o1.name().compareTo(o2.name()); } }); final StringWriter stringWriter = new StringWriter(32000); final XMLStreamWriter writer = new IndentingXMLStreamWriter( XMLOutputFactory.newFactory().createXMLStreamWriter(stringWriter)); writer.writeStartDocument(); writer.writeStartElement("creatures"); writer.writeDefaultNamespace("yadmjc:creatures:1.0"); for (Creature.Type type : types) { writer.writeStartElement("creature"); writer.writeAttribute("id", type.name()); writer.writeAttribute("base-health", Integer.toString(type.getBaseHealth())); writer.writeAttribute("height", type.getHeight().name()); writer.writeAttribute("size", type.getSize().name()); writer.writeAttribute("awareness", Integer.toString(type.getAwareness())); writer.writeAttribute("bravery", Integer.toString(type.getBravery())); writer.writeAttribute("experience-multiplier", Integer.toString(type.getExperienceMultiplier())); writer.writeAttribute("move-duration", Integer.toString(type.getMoveDuration())); writer.writeAttribute("sight-range", Integer.toString(type.getSightRange())); writer.writeAttribute("absorbs-items", Boolean.toString(type.isAbsorbsItems())); writer.writeAttribute("levitates", Boolean.toString(type.levitates())); writer.writeAttribute("archenemy", Boolean.toString(type.isArchenemy())); writer.writeAttribute("night-vision", Boolean.toString(type.isNightVision())); writer.writeAttribute("sees-invisible", Boolean.toString(type.isSeesInvisible())); writer.writeEmptyElement("defense"); writer.writeAttribute("anti-magic", Integer.toString(type.getAntiMagic())); writer.writeAttribute("armor", Integer.toString(type.getArmor())); writer.writeAttribute("shield", Integer.toString(type.getShield())); writer.writeAttribute("poison", Integer.toString(type.getPoisonResistance())); writer.writeEmptyElement("attack"); writer.writeAttribute("skill", type.getAttackSkill().name()); writer.writeAttribute("animation-duration", Integer.toString(type.getAttackAnimationDuration())); writer.writeAttribute("duration", Integer.toString(type.getAttackDuration())); writer.writeAttribute("power", Integer.toString(type.getAttackPower())); writer.writeAttribute("type", type.getAttackType().name()); writer.writeAttribute("range", Integer.toString(type.getAttackRange())); writer.writeAttribute("probability", Integer.toString(type.getAttackProbability())); writer.writeAttribute("side-attack", Boolean.toString(type.isSideAttackAllowed())); writer.writeEmptyElement("poison"); if (type.getPoison() != 0) { writer.writeAttribute("strength", Integer.toString(type.getPoison())); } if (!type.getSpells().isEmpty()) { writer.writeStartElement("spells"); // Sort the spells to ensure they're always serialized in a // consistent way for (Spell.Type spell : new TreeSet<Spell.Type>(type.getSpells())) { writer.writeEmptyElement("spell"); writer.writeAttribute("id", spell.name()); } writer.writeEndElement(); // </spells> } if (!type.getWeaknesses().isEmpty()) { writer.writeStartElement("weaknesses"); // Sort the weaknesses to ensure they're always serialized in a // consistent way for (Weakness weakness : new TreeSet<Weakness>(type.getWeaknesses())) { writer.writeEmptyElement("weakness"); writer.writeAttribute("id", weakness.name()); } writer.writeEndElement(); // </weaknesses> } if (!type.getDefinition().getItemDefs().isEmpty()) { writer.writeStartElement("items"); for (ItemDef itemDef : type.getDefinition().getItemDefs()) { writer.writeEmptyElement("item"); writer.writeAttribute("type", itemDef.type.name()); writer.writeAttribute("min", Integer.toString(itemDef.min)); writer.writeAttribute("max", Integer.toString(itemDef.max)); if (itemDef.curse != null) { writer.writeAttribute("curse", itemDef.curse.name()); } } writer.writeEndElement(); // </items> } writer.writeEndElement(); // </creature> } writer.writeEndElement(); // </creatures> writer.writeEndDocument(); System.out.println(stringWriter); }
From source file:com.basistech.bbhmp.RosapiBundleCollectorMojo.java
private void writeMetadata(Map<Integer, List<BundleSpec>> bundlesByLevel) throws MojoExecutionException { OutputStream os = null;//from w ww . j av a 2 s .co m File md = new File(outputDirectory, "bundles.xml"); try { os = new FileOutputStream(md); XMLStreamWriter writer = XMLOutputFactory.newFactory().createXMLStreamWriter(os); writer = new IndentingXMLStreamWriter(writer); writer.writeStartDocument("utf-8", "1.0"); writer.writeStartElement("bundles"); for (Integer level : bundlesByLevel.keySet()) { writer.writeStartElement("level"); writer.writeAttribute("level", Integer.toString(level)); for (BundleSpec spec : bundlesByLevel.get(level)) { writer.writeStartElement("bundle"); writer.writeAttribute("start", Boolean.toString(spec.start)); writer.writeCharacters(spec.filename); writer.writeEndElement(); } writer.writeEndElement(); } writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); } catch (IOException | XMLStreamException e) { throw new MojoExecutionException("Failed to write metadata file " + md.toString(), e); } finally { IOUtils.closeQuietly(os); } }
From source file:com.amalto.core.storage.services.SystemModels.java
@POST @Path("{model}") @ApiOperation("Get impacts of the model update with the new XSD provided as request content. Changes will not be performed !") public String analyzeModelChange(@ApiParam("Model name") @PathParam("model") String modelName, @ApiParam("Optional language to get localized result") @QueryParam("lang") String locale, InputStream dataModel) {/*from w w w . j av a 2 s .co m*/ Map<ImpactAnalyzer.Impact, List<Change>> impacts; List<String> typeNamesToDrop = new ArrayList<String>(); if (!isSystemStorageAvailable()) { impacts = new EnumMap<>(ImpactAnalyzer.Impact.class); for (ImpactAnalyzer.Impact impact : impacts.keySet()) { impacts.put(impact, Collections.<Change>emptyList()); } } else { StorageAdmin storageAdmin = ServerContext.INSTANCE.get().getStorageAdmin(); Storage storage = storageAdmin.get(modelName, StorageType.MASTER); if (storage == null) { LOGGER.warn( "Container '" + modelName + "' does not exist. Skip impact analyzing for model change."); //$NON-NLS-1$//$NON-NLS-2$ return StringUtils.EMPTY; } if (storage.getType() == StorageType.SYSTEM) { LOGGER.debug("No model update for system storage"); //$NON-NLS-1$ return StringUtils.EMPTY; } // Compare new data model with existing data model MetadataRepository previousRepository = storage.getMetadataRepository(); MetadataRepository newRepository = new MetadataRepository(); newRepository.load(dataModel); Compare.DiffResults diffResults = Compare.compare(previousRepository, newRepository); // Analyzes impacts on the select storage impacts = storage.getImpactAnalyzer().analyzeImpacts(diffResults); List<ComplexTypeMetadata> typesToDrop = storage.findSortedTypesToDrop(diffResults, true); Set<String> tableNamesToDrop = storage.findTablesToDrop(typesToDrop); for (String tableName : tableNamesToDrop) { if (previousRepository.getInstantiableTypes() .contains(previousRepository.getComplexType(tableName))) { typeNamesToDrop.add(tableName); } } } // Serialize results to XML StringWriter resultAsXml = new StringWriter(); XMLStreamWriter writer = null; try { writer = XMLOutputFactory.newFactory().createXMLStreamWriter(resultAsXml); writer.writeStartElement("result"); //$NON-NLS-1$ { for (Map.Entry<ImpactAnalyzer.Impact, List<Change>> category : impacts.entrySet()) { writer.writeStartElement(category.getKey().name().toLowerCase()); List<Change> changes = category.getValue(); for (Change change : changes) { writer.writeStartElement("change"); //$NON-NLS-1$ { writer.writeStartElement("message"); //$NON-NLS-1$ { Locale messageLocale; if (StringUtils.isEmpty(locale)) { messageLocale = Locale.getDefault(); } else { messageLocale = new Locale(locale); } writer.writeCharacters(change.getMessage(messageLocale)); } writer.writeEndElement(); } writer.writeEndElement(); } writer.writeEndElement(); } writer.writeStartElement("entitiesToDrop"); //$NON-NLS-1$ for (String typeName : typeNamesToDrop) { writer.writeStartElement("entity"); //$NON-NLS-1$ writer.writeCharacters(typeName); writer.writeEndElement(); } writer.writeEndElement(); } writer.writeEndElement(); } catch (XMLStreamException e) { throw new RuntimeException(e); } finally { if (writer != null) { try { writer.flush(); } catch (XMLStreamException e) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("Could not flush XML content.", e); //$NON-NLS-1$ } } } } return resultAsXml.toString(); }
From source file:edu.stanford.cfuller.imageanalysistools.fitting.ImageObject.java
public String writeToXMLString() { StringWriter sw = new StringWriter(); try {//from ww w .j a v a 2 s. c o m XMLStreamWriter xsw = XMLOutputFactory.newFactory().createXMLStreamWriter(sw); this.writeToXML(xsw); } catch (XMLStreamException e) { LoggingUtilities.getLogger() .severe("Exception encountered while writing XML correction output: " + e.getMessage()); } return sw.toString(); }
From source file:WpRDFFunctionLibrary.java
public static void mergeGpmltoSingleFile(String gpmlLocation) throws IOException, XMLStreamException, ParserConfigurationException, SAXException, TransformerException { // Based on: http://stackoverflow.com/questions/10759775/how-to-merge-1000-xml-files-into-one-in-java //for (int i = 1; i < 8 ; i++) { Writer outputWriter = new FileWriter("/tmp/WpGPML.xml"); XMLOutputFactory xmlOutFactory = XMLOutputFactory.newFactory(); XMLEventWriter xmlEventWriter = xmlOutFactory.createXMLEventWriter(outputWriter); XMLEventFactory xmlEventFactory = XMLEventFactory.newFactory(); xmlEventWriter.add(xmlEventFactory.createStartDocument("ISO-8859-1", "1.0")); xmlEventWriter.add(xmlEventFactory.createStartElement("", null, "PathwaySet")); xmlEventWriter.add(xmlEventFactory.createAttribute("creationData", basicCalls.now())); XMLInputFactory xmlInFactory = XMLInputFactory.newFactory(); File dir = new File(gpmlLocation); File[] rootFiles = dir.listFiles(); //the section below is only in case of analysis sets for (File rootFile : rootFiles) { String fileName = FilenameUtils.removeExtension(rootFile.getName()); System.out.println(fileName); String[] identifiers = fileName.split("_"); System.out.println(fileName); String wpIdentifier = identifiers[identifiers.length - 2]; String wpRevision = identifiers[identifiers.length - 1]; //Pattern pattern = Pattern.compile("_(WP[0-9]+)_([0-9]+).gpml"); //Matcher matcher = pattern.matcher(fileName); //System.out.println(matcher.find()); //String wpIdentifier = matcher.group(1); File tempFile = new File(constants.localAllGPMLCacheDir() + wpIdentifier + "_" + wpRevision + ".gpml"); //System.out.println(matcher.group(1)); //String wpRevision = matcher.group(2); //System.out.println(matcher.group(2)); if (!(tempFile.exists())) { System.out.println(tempFile.getName()); Document currentGPML = basicCalls.openXmlFile(rootFile.getPath()); basicCalls.saveDOMasXML(WpRDFFunctionLibrary.addWpProvenance(currentGPML, wpIdentifier, wpRevision), constants.localCurrentGPMLCache() + tempFile.getName()); }/* w w w . j ava 2 s .c o m*/ } dir = new File("/tmp/GPML"); rootFiles = dir.listFiles(); for (File rootFile : rootFiles) { System.out.println(rootFile); XMLEventReader xmlEventReader = xmlInFactory.createXMLEventReader(new StreamSource(rootFile)); XMLEvent event = xmlEventReader.nextEvent(); // Skip ahead in the input to the opening document element try { while (event.getEventType() != XMLEvent.START_ELEMENT) { event = xmlEventReader.nextEvent(); } do { xmlEventWriter.add(event); event = xmlEventReader.nextEvent(); } while (event.getEventType() != XMLEvent.END_DOCUMENT); xmlEventReader.close(); } catch (Exception e) { System.out.println("Malformed gpml file"); } } xmlEventWriter.add(xmlEventFactory.createEndElement("", null, "PathwaySet")); xmlEventWriter.add(xmlEventFactory.createEndDocument()); xmlEventWriter.close(); outputWriter.close(); }
From source file:com.net2plan.internal.sim.SimStats.java
/** * Returns a HTML {@code String} with statistics. * /*from w ww.j av a 2 s . c o m*/ * @param simTime Current simulation time * @return Statistics in HTML format * @since 0.2.3 */ public String getResults(double simTime) { if (lastEventTime == 0) return "<p>No event was processed</p>"; double totalSimulationTime = simTime - transitoryTime; if (totalSimulationTime == 0) return "<p>Simulation time equal to zero. No results</p>"; // computeNextState(simTime+0.0000000000001); try (ByteArrayOutputStream os = new ByteArrayOutputStream()) { XMLOutputFactory2 output = (XMLOutputFactory2) XMLOutputFactory.newFactory(); XMLStreamWriter2 writer = (XMLStreamWriter2) output.createXMLStreamWriter(os); writer.writeStartDocument("UTF-8", "1.0"); /* Write network information */ writer.writeStartElement("network"); writer.writeAttribute("avgNumLayers", String.format("%.3f", totalSimulationTime > 0 ? accum_avgNumLayers / totalSimulationTime : 0)); int minNumLayers_thisNetwork = minNumLayers; if (minNumLayers_thisNetwork == Integer.MAX_VALUE) minNumLayers_thisNetwork = 0; writer.writeAttribute("minNumLayers", Integer.toString(minNumLayers_thisNetwork)); writer.writeAttribute("maxNumLayers", Integer.toString(maxNumLayers)); writer.writeAttribute("avgNumNodes", String.format("%.3f", totalSimulationTime > 0 ? accum_avgNumNodes / totalSimulationTime : 0)); int minNumNodes_thisNetwork = minNumNodes; if (minNumNodes_thisNetwork == Integer.MAX_VALUE) minNumNodes_thisNetwork = 0; writer.writeAttribute("minNumNodes", Integer.toString(minNumNodes_thisNetwork)); writer.writeAttribute("maxNumNodes", Integer.toString(maxNumNodes)); /* Write node information */ Collection<Long> nodeIds = netState.getNodeIds(); for (long nodeId : nodeIds) { checkAndCreateNode(nodeId); double upTime_thisNode = accum_nodeUpTime.get(nodeId).doubleValue(); double totalTime_thisNode = accum_nodeTotalTime.get(nodeId).doubleValue(); double upTimePercentage_thisNode = totalTime_thisNode > 0 ? 100 * upTime_thisNode / totalTime_thisNode : 0; writer.writeStartElement("node"); writer.writeAttribute("id", Long.toString(nodeId)); writer.writeAttribute("name", netState.getNodeFromId(nodeId).getName()); writer.writeAttribute("upTime", StringUtils.secondsToYearsDaysHoursMinutesSeconds(upTime_thisNode)); writer.writeAttribute("upTimePercentage", String.format("%.3f", upTimePercentage_thisNode)); writer.writeAttribute("totalTime", StringUtils.secondsToYearsDaysHoursMinutesSeconds(totalTime_thisNode)); writer.writeEndElement(); } /* Write layer information */ for (long layerId : netState.getNetworkLayerIds()) { checkAndCreateLayer(layerId); double totalTime_thisLayer = accum_layerTotalTime.get(layerId).doubleValue(); NetworkLayer netStateLayer = netState.getNetworkLayerFromId(layerId); String trafficUnitsName = netState.getDemandTrafficUnitsName(netStateLayer); if (trafficUnitsName.isEmpty()) trafficUnitsName = "none"; String capacityUnitsName = netState.getLinkCapacityUnitsName(netStateLayer); if (capacityUnitsName.isEmpty()) capacityUnitsName = "none"; writer.writeStartElement("layer"); writer.writeAttribute("id", Long.toString(layerId)); writer.writeAttribute("name", netStateLayer.getName()); writer.writeAttribute("avgNumLinks", String.format("%.3f", totalTime_thisLayer > 0 ? accum_avgNumLinks.get(layerId).doubleValue() / totalTime_thisLayer : 0)); int minNumLinks_thisLayer = minNumLinks.get(layerId); if (minNumLinks_thisLayer == Integer.MAX_VALUE) minNumLinks_thisLayer = 0; writer.writeAttribute("minNumLinks", Integer.toString(minNumLinks_thisLayer)); writer.writeAttribute("maxNumLinks", Integer.toString(maxNumLinks.get(layerId))); writer.writeAttribute("avgNumDemands", String.format("%.3f", totalTime_thisLayer > 0 ? accum_avgNumDemands.get(layerId).doubleValue() / totalTime_thisLayer : 0)); int minNumDemands_thisLayer = minNumDemands.get(layerId); if (minNumDemands_thisLayer == Integer.MAX_VALUE) minNumDemands_thisLayer = 0; writer.writeAttribute("minNumDemands", Integer.toString(minNumDemands_thisLayer)); writer.writeAttribute("maxNumDemands", Integer.toString(maxNumDemands.get(layerId))); writer.writeAttribute("totalTime", StringUtils.secondsToYearsDaysHoursMinutesSeconds(totalTime_thisLayer)); writer.writeAttribute("trafficUnitsName", trafficUnitsName); writer.writeAttribute("avgOfferedTraffic", String.format("%.3f", totalTime_thisLayer > 0 ? accum_avgTotalOfferedTraffic.get(layerId).doubleValue() / totalTime_thisLayer : 0)); double minTotalOfferedTraffic_thisLayer = minTotalOfferedTraffic.get(layerId).doubleValue(); if (minTotalOfferedTraffic_thisLayer == Double.MAX_VALUE) minTotalOfferedTraffic_thisLayer = 0; writer.writeAttribute("minOfferedTraffic", String.format("%.3f", minTotalOfferedTraffic_thisLayer)); writer.writeAttribute("maxOfferedTraffic", String.format("%.3f", maxTotalOfferedTraffic.get(layerId).doubleValue())); writer.writeAttribute("avgCarriedTraffic", String.format("%.3f", totalTime_thisLayer > 0 ? accum_avgTotalCarriedTraffic.get(layerId).doubleValue() / totalTime_thisLayer : 0)); double minTotalCarriedTraffic_thisLayer = minTotalCarriedTraffic.get(layerId).doubleValue(); if (minTotalCarriedTraffic_thisLayer == Double.MAX_VALUE) minTotalCarriedTraffic_thisLayer = 0; writer.writeAttribute("minCarriedTraffic", String.format("%.3f", minTotalCarriedTraffic_thisLayer)); writer.writeAttribute("maxCarriedTraffic", String.format("%.3f", maxTotalCarriedTraffic.get(layerId).doubleValue())); writer.writeAttribute("capacityUnitsName", capacityUnitsName); writer.writeAttribute("avgTotalCapacity", String.format("%.3f", totalTime_thisLayer > 0 ? accum_avgTotalCapacity.get(layerId).doubleValue() / totalTime_thisLayer : 0)); double minTotalCapacity_thisLayer = minTotalCapacity.get(layerId).doubleValue(); if (minTotalCapacity_thisLayer == Double.MAX_VALUE) minTotalCapacity_thisLayer = 0; writer.writeAttribute("minTotalCapacity", String.format("%.3f", minTotalCapacity_thisLayer)); writer.writeAttribute("maxTotalCapacity", String.format("%.3f", maxTotalCapacity.get(layerId).doubleValue())); writer.writeAttribute("avgCongestion", String.format("%.3f", totalTime_thisLayer > 0 ? accum_avgCongestion.get(layerId).doubleValue() / totalTime_thisLayer : 0)); double minCongestion_thisLayer = minCongestion.get(layerId).doubleValue(); if (minCongestion_thisLayer == Double.MAX_VALUE) minCongestion_thisLayer = 0; writer.writeAttribute("minCongestion", String.format("%.3f", minCongestion_thisLayer)); writer.writeAttribute("maxCongestion", String.format("%.3f", maxCongestion.get(layerId).doubleValue())); writer.writeAttribute("availabilityClassic", String.format("%.6f", totalTime_thisLayer > 0 ? accum_availabilityClassic.get(layerId).doubleValue() / totalTime_thisLayer : 0)); writer.writeAttribute("availabilityWeighted", String.format("%.6f", totalTime_thisLayer > 0 ? accum_availabilityWeighted.get(layerId).doubleValue() / totalTime_thisLayer : 0)); double worstDemandAvailabilityClassic_thisLayer = worstDemandAvailabilityClassic.get(layerId) .doubleValue(); double worstDemandAvailabilityWeighted_thisLayer = worstDemandAvailabilityWeighted.get(layerId) .doubleValue(); /* Write demand information */ Collection<Long> demandIds_thisLayer = netState.getDemandIds(netStateLayer); for (long demandId : netState.getDemandIds(netStateLayer)) { checkAndCreateDemand(layerId, demandId); double totalTime_thisDemand = demandTotalTime.get(layerId).get(demandId).doubleValue(); worstDemandAvailabilityClassic_thisLayer = Math.min(worstDemandAvailabilityClassic_thisLayer, totalTime_thisDemand > 0 ? accum_demandAvailabilityClassic.get(layerId).get(demandId).doubleValue() / totalTime_thisDemand : 0); worstDemandAvailabilityWeighted_thisLayer = Math.min(worstDemandAvailabilityWeighted_thisLayer, totalTime_thisDemand > 0 ? accum_demandAvailabilityWeighted.get(layerId).get(demandId).doubleValue() / totalTime_thisDemand : 0); } writer.writeAttribute("worstDemandAvailabilityClassic", String.format("%.6f", worstDemandAvailabilityClassic_thisLayer)); writer.writeAttribute("worstDemandAvailabilityWeighted", String.format("%.6f", worstDemandAvailabilityWeighted_thisLayer)); /* Write node information */ for (long nodeId : nodeIds) { checkAndCreateNode(layerId, nodeId); double totalTime_thisNode_thisLayer = Math.min(accum_nodeTotalTime.get(nodeId).doubleValue(), totalTime_thisLayer); writer.writeStartElement("node"); writer.writeAttribute("id", Long.toString(nodeId)); writer.writeAttribute("name", netState.getNodeFromId(nodeId).getName()); writer.writeAttribute("avgInDegree", String.format("%.3f", totalTime_thisNode_thisLayer > 0 ? accum_avgNodeInDegree.get(layerId).get(nodeId).doubleValue() / totalTime_thisNode_thisLayer : 0)); int minNodeInDegree_thisNode_thisLayer = minNodeInDegree.get(layerId).get(nodeId); if (minNodeInDegree_thisNode_thisLayer == Integer.MAX_VALUE) minNodeInDegree_thisNode_thisLayer = 0; writer.writeAttribute("minInDegree", Integer.toString(minNodeInDegree_thisNode_thisLayer)); writer.writeAttribute("maxInDegree", Integer.toString(maxNodeInDegree.get(layerId).get(nodeId))); writer.writeAttribute("avgOutDegree", String.format("%.3f", totalTime_thisNode_thisLayer > 0 ? accum_avgNodeOutDegree.get(layerId).get(nodeId).doubleValue() / totalTime_thisNode_thisLayer : 0)); int minNodeOutDegree_thisNode_thisLayer = minNodeOutDegree.get(layerId).get(nodeId); if (minNodeOutDegree_thisNode_thisLayer == Integer.MAX_VALUE) minNodeOutDegree_thisNode_thisLayer = 0; writer.writeAttribute("minOutDegree", Integer.toString(minNodeOutDegree_thisNode_thisLayer)); writer.writeAttribute("maxOutDegree", Integer.toString(maxNodeOutDegree.get(layerId).get(nodeId))); writer.writeAttribute("avgIngressTraffic", String.format("%.3f", totalTime_thisNode_thisLayer > 0 ? accum_avgNodeIngressTraffic.get(layerId).get(nodeId).doubleValue() / totalTime_thisNode_thisLayer : 0)); double minNodeIngressTraffic_thisNode_thisLayer = minNodeIngressTraffic.get(layerId) .get(nodeId); if (minNodeIngressTraffic_thisNode_thisLayer == Double.MAX_VALUE) minNodeIngressTraffic_thisNode_thisLayer = 0; writer.writeAttribute("minIngressTraffic", String.format("%.3f", minNodeIngressTraffic.get(layerId).get(nodeId))); writer.writeAttribute("maxIngressTraffic", String.format("%.3f", maxNodeIngressTraffic.get(layerId).get(nodeId))); writer.writeAttribute("avgEgressTraffic", String.format("%.3f", totalTime_thisNode_thisLayer > 0 ? accum_avgNodeEgressTraffic.get(layerId).get(nodeId).doubleValue() / totalTime_thisNode_thisLayer : 0)); double minNodeEgressTraffic_thisNode_thisLayer = minNodeEgressTraffic.get(layerId).get(nodeId); if (minNodeEgressTraffic_thisNode_thisLayer == Double.MAX_VALUE) minNodeEgressTraffic_thisNode_thisLayer = 0; writer.writeAttribute("minEgressTraffic", String.format("%.3f", minNodeEgressTraffic_thisNode_thisLayer)); writer.writeAttribute("maxEgressTraffic", String.format("%.3f", maxNodeEgressTraffic.get(layerId).get(nodeId))); writer.writeEndElement(); } /* Write link information */ Collection<Long> linkIds_thisLayer = netState.getLinkIds(netState.getNetworkLayerFromId(layerId)); for (long linkId : linkIds_thisLayer) { checkAndCreateLink(layerId, linkId); Link netStateLink = netState.getLinkFromId(linkId); long originNodeId_thisLink = netStateLink.getOriginNode().getId(); long destinationNodeId_thisLink = netStateLink.getDestinationNode().getId(); String originNodeName = netStateLink.getOriginNode().getName(); String destinationNodeName = netStateLink.getDestinationNode().getName(); double upTime_thisLink = accum_linkUpTime.get(layerId).get(linkId).doubleValue(); double totalTime_thisLink = accum_linkTotalTime.get(layerId).get(linkId).doubleValue(); double upTimePercentage_thisLink = totalTime_thisLink > 0 ? 100 * upTime_thisLink / totalTime_thisLink : 0; double oversubscribedTime_thisLink = accum_linkOversubscribedTime.get(layerId).get(linkId) .doubleValue(); double oversubscribedTimePercentage_thisLink = totalTime_thisLink > 0 ? 100 * oversubscribedTime_thisLink / totalTime_thisLink : 0; writer.writeStartElement("link"); writer.writeAttribute("id", Long.toString(linkId)); writer.writeAttribute("originNode", originNodeName.isEmpty() ? Long.toString(originNodeId_thisLink) : String.format("%d (%s)", originNodeId_thisLink, originNodeName)); writer.writeAttribute("destinationNode", destinationNodeName.isEmpty() ? Long.toString(destinationNodeId_thisLink) : String.format("%d (%s)", destinationNodeId_thisLink, destinationNodeName)); writer.writeAttribute("avgLengthInKm", String.format("%.3f", totalTime_thisLink > 0 ? accum_avgLinkLengthInKm.get(layerId).get(linkId).doubleValue() / totalTime_thisLink : 0)); double minLinkLengthInKm_thisLink = minLinkLengthInKm.get(layerId).get(linkId).doubleValue(); if (minLinkLengthInKm_thisLink == Double.MAX_VALUE) minLinkLengthInKm_thisLink = 0; writer.writeAttribute("minLengthInKm", String.format("%.3f", minLinkLengthInKm_thisLink)); writer.writeAttribute("maxLengthInKm", String.format("%.3f", maxLinkLengthInKm.get(layerId).get(linkId).doubleValue())); writer.writeAttribute("avgCapacity", String.format("%.3f", totalTime_thisLink > 0 ? accum_avgCapacity.get(layerId).get(linkId).doubleValue() / totalTime_thisLink : 0)); double minCapacity_thisLayer = minCapacity.get(layerId).get(linkId).doubleValue(); if (minCapacity_thisLayer == Double.MAX_VALUE) minCapacity_thisLayer = 0; writer.writeAttribute("minCapacity", String.format("%.3f", minCapacity_thisLayer)); writer.writeAttribute("maxCapacity", String.format("%.3f", maxCapacity.get(layerId).get(linkId).doubleValue())); writer.writeAttribute("avgOccupiedCapacity", String.format("%.3f", totalTime_thisLink > 0 ? accum_avgLinkOccupiedCapacity.get(layerId).get(linkId).doubleValue() / totalTime_thisLink : 0)); double minCarriedTraffic_thisLink = minLinkOccupiedCapacity.get(layerId).get(linkId) .doubleValue(); if (minCarriedTraffic_thisLink == Double.MAX_VALUE) minCarriedTraffic_thisLink = 0; writer.writeAttribute("minOccupiedCapacity", String.format("%.3f", minCarriedTraffic_thisLink)); writer.writeAttribute("maxOccupiedCapacity", String.format("%.3f", maxLinkOccupiedCapacity.get(layerId).get(linkId).doubleValue())); writer.writeAttribute("avgUtilization", String.format("%.3f", totalTime_thisLink > 0 ? accum_avgUtilization.get(layerId).get(linkId).doubleValue() / totalTime_thisLink : 0)); double minUtilization_thisLink = minUtilization.get(layerId).get(linkId).doubleValue(); if (minUtilization_thisLink == Double.MAX_VALUE) minUtilization_thisLink = 0; writer.writeAttribute("minUtilization", String.format("%.3f", minUtilization_thisLink)); writer.writeAttribute("maxUtilization", String.format("%.3f", maxUtilization.get(layerId).get(linkId).doubleValue())); writer.writeAttribute("avgOversubscribedCapacity", String.format("%.3f", totalTime_thisLink > 0 ? accum_avgOversubscribedCapacity.get(layerId).get(linkId).doubleValue() / totalTime_thisLink : 0)); double minOversubscribedCapacity_thisLink = minOversubscribedCapacity.get(layerId).get(linkId) .doubleValue(); if (minOversubscribedCapacity_thisLink == Double.MAX_VALUE) minOversubscribedCapacity_thisLink = 0; writer.writeAttribute("minOversubscribedCapacity", String.format("%.3f", minOversubscribedCapacity_thisLink)); writer.writeAttribute("maxOversubscribedCapacity", String.format("%.3f", maxOversubscribedCapacity.get(layerId).get(linkId).doubleValue())); writer.writeAttribute("oversubscribedTime", StringUtils.secondsToYearsDaysHoursMinutesSeconds(oversubscribedTime_thisLink)); writer.writeAttribute("oversubscribedTimePercentage", String.format("%.3f", oversubscribedTimePercentage_thisLink)); writer.writeAttribute("upTime", StringUtils.secondsToYearsDaysHoursMinutesSeconds(upTime_thisLink)); writer.writeAttribute("upTimePercentage", String.format("%.3f", upTimePercentage_thisLink)); writer.writeAttribute("totalTime", StringUtils.secondsToYearsDaysHoursMinutesSeconds(totalTime_thisLink)); writer.writeEndElement(); } /* Write demand information */ for (long demandId : demandIds_thisLayer) { Demand netStateDemand = netState.getDemandFromId(demandId); long ingressNodeId_thisDemand = netStateDemand.getIngressNode().getId(); long egressNodeId_thisDemand = netStateDemand.getEgressNode().getId(); String ingressNodeName = netStateDemand.getIngressNode().getName(); String egressNodeName = netStateDemand.getEgressNode().getName(); double totalTime_thisDemand = demandTotalTime.get(layerId).get(demandId).doubleValue(); double excessCarriedTrafficTime_thisDemand = excessDemandCarriedTrafficTime.get(layerId) .get(demandId).doubleValue(); double excessCarriedTrafficTimePercentage_thisDemand = totalTime_thisDemand > 0 ? 100 * excessCarriedTrafficTime_thisDemand / totalTime_thisDemand : 0; writer.writeStartElement("demand"); writer.writeAttribute("id", Long.toString(demandId)); writer.writeAttribute("ingressNode", ingressNodeName.isEmpty() ? Long.toString(ingressNodeId_thisDemand) : String.format("%d (%s)", ingressNodeId_thisDemand, ingressNodeName)); writer.writeAttribute("egressNode", egressNodeName.isEmpty() ? Long.toString(egressNodeId_thisDemand) : String.format("%d (%s)", egressNodeId_thisDemand, egressNodeName)); writer.writeAttribute("avgOfferedTraffic", String.format("%.3f", totalTime_thisDemand > 0 ? accum_avgDemandOfferedTraffic.get(layerId).get(demandId).doubleValue() / totalTime_thisDemand : 0)); double minOfferedTraffic_thisDemand = minDemandOfferedTraffic.get(layerId).get(demandId) .doubleValue(); if (minOfferedTraffic_thisDemand == Double.MAX_VALUE) minOfferedTraffic_thisDemand = 0; writer.writeAttribute("minOfferedTraffic", String.format("%.3f", minOfferedTraffic_thisDemand)); writer.writeAttribute("maxOfferedTraffic", String.format("%.3f", maxDemandOfferedTraffic.get(layerId).get(demandId).doubleValue())); writer.writeAttribute("avgCarriedTraffic", String.format("%.3f", totalTime_thisDemand > 0 ? accum_avgDemandCarriedTraffic.get(layerId).get(demandId).doubleValue() / totalTime_thisDemand : 0)); double minCarriedTraffic_thisDemand = minDemandCarriedTraffic.get(layerId).get(demandId) .doubleValue(); if (minCarriedTraffic_thisDemand == Double.MAX_VALUE) minCarriedTraffic_thisDemand = 0; writer.writeAttribute("minCarriedTraffic", String.format("%.3f", minCarriedTraffic_thisDemand)); writer.writeAttribute("maxCarriedTraffic", String.format("%.3f", maxDemandCarriedTraffic.get(layerId).get(demandId).doubleValue())); writer.writeAttribute("avgBlockedTraffic", String.format("%.3f", totalTime_thisDemand > 0 ? accum_avgDemandBlockedTraffic.get(layerId).get(demandId).doubleValue() / totalTime_thisDemand : 0)); double minBlockedTraffic_thisDemand = minDemandBlockedTraffic.get(layerId).get(demandId) .doubleValue(); if (minBlockedTraffic_thisDemand == Double.MAX_VALUE) minBlockedTraffic_thisDemand = 0; writer.writeAttribute("minBlockedTraffic", String.format("%.3f", minBlockedTraffic_thisDemand)); writer.writeAttribute("maxBlockedTraffic", String.format("%.3f", maxDemandBlockedTraffic.get(layerId).get(demandId).doubleValue())); writer.writeAttribute("availabilityClassic", String.format("%.6f", totalTime_thisDemand > 0 ? accum_demandAvailabilityClassic.get(layerId).get(demandId).doubleValue() / totalTime_thisDemand : 0)); writer.writeAttribute("availabilityWeighted", String.format("%.6f", totalTime_thisDemand > 0 ? accum_demandAvailabilityWeighted.get(layerId).get(demandId).doubleValue() / totalTime_thisDemand : 0)); writer.writeAttribute("avgExcessCarriedTraffic", String.format("%.3f", totalTime_thisDemand > 0 ? accum_avgExcessCarriedTraffic.get(layerId).get(demandId).doubleValue() / totalTime_thisDemand : 0)); double minExcessCarriedTraffic_thisDemand = minDemandExcessCarriedTraffic.get(layerId) .get(demandId).doubleValue(); if (minExcessCarriedTraffic_thisDemand == Double.MAX_VALUE) minExcessCarriedTraffic_thisDemand = 0; writer.writeAttribute("minExcessCarriedTraffic", String.format("%.3f", minExcessCarriedTraffic_thisDemand)); writer.writeAttribute("maxExcessCarriedTraffic", String.format("%.3f", maxDemandExcessCarriedTraffic.get(layerId).get(demandId).doubleValue())); writer.writeAttribute("excessCarriedTrafficTime", StringUtils.secondsToYearsDaysHoursMinutesSeconds(excessCarriedTrafficTime_thisDemand)); writer.writeAttribute("excessCarriedTrafficTimePercentage", String.format("%.3f", excessCarriedTrafficTimePercentage_thisDemand)); writer.writeAttribute("totalTime", StringUtils.secondsToYearsDaysHoursMinutesSeconds(totalTime_thisDemand)); writer.writeEndElement(); } writer.writeEndElement(); } writer.writeEndElement(); writer.writeEndDocument(); writer.flush(); writer.close(); String xml = os.toString(StandardCharsets.UTF_8.name()); return HTMLUtils.getHTMLFromXML(xml, SimStats.class.getResource("/com/net2plan/internal/sim/SimStats.xsl").toURI().toURL()); } catch (Throwable e) { throw new RuntimeException(e); } }
From source file:org.netbeans.jbatch.modeler.spec.core.Definitions.java
public static void unload(ModelerFile file, List<String> definitionIdList) { File savedFile = file.getFile(); if (definitionIdList.isEmpty()) { return;//from ww w . j a va 2 s . c o m } try { File cloneSavedFile = File.createTempFile("TMP", "job"); FileUtils.copyFile(savedFile, cloneSavedFile); BufferedReader br = new BufferedReader(new FileReader(savedFile)); String line = null; while ((line = br.readLine()) != null) { System.out.println("pre savedFile : " + line); } XMLOutputFactory xof = XMLOutputFactory.newFactory(); XMLStreamWriter xsw = xof.createXMLStreamWriter(new FileWriter(savedFile)); xsw.setDefaultNamespace("http://jbatchsuite.java.net"); xsw.writeStartDocument(); xsw.writeStartElement("jbatchnb", "root", "http://jbatchsuite.java.net"); xsw.writeNamespace("jbatch", "http://xmlns.jcp.org/xml/ns/javaee"); xsw.writeNamespace("jbatchnb", "http://jbatchsuite.java.net"); xsw.writeNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); xsw.writeNamespace("java", "http://jcp.org/en/jsr/detail?id=270"); xsw.writeNamespace("nbm", "http://nbmodeler.java.net"); if (cloneSavedFile.length() != 0) { try { XMLInputFactory xif = XMLInputFactory.newFactory(); StreamSource xml = new StreamSource(cloneSavedFile); XMLStreamReader xsr = xif.createXMLStreamReader(xml); xsr.nextTag(); while (xsr.getEventType() == XMLStreamConstants.START_ELEMENT) { // Def Y N // Tag N(D) Y(D) // ________________ // T T // ---------------- // // Def Y N // Tag Y(S) N(S) // ________________ // S S // ---------------- // // Def Y N // Tag Y(D) N(S) // ________________ // T S // ---------------- // // (D) => Different // (S) => Same // Y => Id Exist // N => Def Id is null // T => Transform // S => Skip if (xsr.getLocalName().equals("definitions")) { // if (definitionId == null) { // if (xsr.getAttributeValue(null, "id") != null) { // transformXMLStream(xsr, xsw); // } // } else { if (xsr.getAttributeValue(null, "id") == null) { System.out.println("transformXMLStream " + null); transformXMLStream(xsr, xsw); } else { if (!definitionIdList.contains(xsr.getAttributeValue(null, "id"))) { System.out.println("transformXMLStream " + xsr.getAttributeValue(null, "id")); transformXMLStream(xsr, xsw); } else { System.out.println("skipXMLStream " + xsr.getAttributeValue(null, "id")); skipXMLStream(xsr); } } // } } System.out.println( "pre xsr.getEventType() : " + xsr.getEventType() + " " + xsr.getLocalName()); xsr.nextTag(); System.out.println( "post xsr.getEventType() : " + xsr.getEventType() + " " + xsr.getLocalName()); } } catch (XMLStreamException ex) { Exceptions.printStackTrace(ex); } } xsw.writeEndDocument(); xsw.close(); br = new BufferedReader(new FileReader(savedFile)); line = null; while ((line = br.readLine()) != null) { System.out.println("post savedFile : " + line); } } catch (IOException ex) { Exceptions.printStackTrace(ex); } catch (XMLStreamException ex) { Exceptions.printStackTrace(ex); } }
From source file:org.netbeans.jbatch.modeler.specification.model.job.util.JobUtil.java
public void saveModelerFile(ModelerFile modelerFile) { Definitions definitions = (Definitions) modelerFile.getDefinitionElement(); try {//from w w w .j ava 2 s . co m updateBatchDiagram(modelerFile); List<String> closeDefinitionIdList = closeDiagram(modelerFile, definitions.getGarbageDefinitions()); List<String> definitionIdList = new ArrayList<String>(closeDefinitionIdList); // definitionIdList.addAll(definitions.getGarbageDefinitions()); definitionIdList.add(definitions.getId()); File savedFile = modelerFile.getFile(); BufferedReader br = new BufferedReader(new FileReader(savedFile)); String line = null; while ((line = br.readLine()) != null) { System.out.println("savedFile : " + line); } File cloneSavedFile = File.createTempFile("TMP", "job"); FileUtils.copyFile(savedFile, cloneSavedFile); // br = new BufferedReader(new FileReader(cloneSavedFile)); // line = null; // while ((line = br.readLine()) != null) { // System.out.println("line2 : " + line); // } XMLOutputFactory xof = XMLOutputFactory.newFactory(); XMLStreamWriter xsw = xof.createXMLStreamWriter(new FileWriter(savedFile)); xsw.setDefaultNamespace("http://jbatchsuite.java.net"); xsw.writeStartDocument(); xsw.writeStartElement("jbatchnb", "root", "http://jbatchsuite.java.net"); xsw.writeNamespace("jbatch", "http://xmlns.jcp.org/xml/ns/javaee"); xsw.writeNamespace("jbatchnb", "http://jbatchsuite.java.net"); xsw.writeNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance"); xsw.writeNamespace("java", "http://jcp.org/en/jsr/detail?id=270"); xsw.writeNamespace("nbm", "http://nbmodeler.java.net"); // br = new BufferedReader(new FileReader(savedFile)); // line = null; // while ((line = br.readLine()) != null) { // System.out.println("line3 : " + line); // } if (cloneSavedFile.length() != 0) { try { XMLInputFactory xif = XMLInputFactory.newFactory(); StreamSource xml = new StreamSource(cloneSavedFile); XMLStreamReader xsr = xif.createXMLStreamReader(xml); xsr.nextTag(); while (xsr.getEventType() == XMLStreamConstants.START_ELEMENT) { // Def Y N // Tag N(D) Y(D) // ________________ // T T // ---------------- // // Def Y N // Tag Y(S) N(S) // ________________ // S S // ---------------- // // Def Y N // Tag Y(D) N(S) // ________________ // T S // ---------------- // // (D) => Different // (S) => Same // Y => Id Exist // N => Id is null // T => Transform // S => Skip if (xsr.getLocalName().equals("definitions")) { // if (definitions.getId() == null) { // if (xsr.getAttributeValue(null, "id") != null) { // transformXMLStream(xsr, xsw); // } else { // skipXMLStream(xsr); // } // } else { if (xsr.getAttributeValue(null, "id") == null) { if (definitions.getId() == null) { skipXMLStream(xsr); } else { transformXMLStream(xsr, xsw); } } else { if (!definitionIdList.contains(xsr.getAttributeValue(null, "id"))) { transformXMLStream(xsr, xsw); } else { skipXMLStream(xsr); } } // } } xsr.nextTag(); } } catch (XMLStreamException ex) { Exceptions.printStackTrace(ex); } } JAXBElement<Definitions> je = new JAXBElement<Definitions>( new QName("http://jbatchsuite.java.net", "definitions", "jbatchnb"), Definitions.class, definitions); if (jobContext == null) { jobContext = JAXBContext.newInstance(new Class<?>[] { ShapeDesign.class, Definitions.class }); } if (jobMarshaller == null) { jobMarshaller = jobContext.createMarshaller(); } // output pretty printed jobMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); jobMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE); // jobMarshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "http://www.omg.org/spec/Batch/20100524/MODEL http://www.omg.org/spec/Batch/2.0/20100501/Batch20.xsd"); jobMarshaller.setEventHandler(new ValidateJAXB()); jobMarshaller.marshal(je, System.out); jobMarshaller.marshal(je, xsw); // xsw.writeEndElement(); xsw.writeEndDocument(); xsw.close(); // StringWriter sw = new StringWriter(); // jobMarshaller.marshal(file.getDefinitionElement(), sw); // FileUtils.writeStringToFile(savedFile, sw.toString().replaceFirst("xmlns:ns[A-Za-z\\d]{0,3}=\"http://www.omg.org/spec/Batch/20100524/MODEL\"", // "xmlns=\"http://www.omg.org/spec/Batch/20100524/MODEL\"")); } catch (JAXBException ex) { Exceptions.printStackTrace(ex); } catch (IOException ex) { Exceptions.printStackTrace(ex); } catch (XMLStreamException ex) { Exceptions.printStackTrace(ex); } }