下面列出了javax.xml.transform.sax.TransformerHandler#startDocument ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void test() throws Exception {
TransformerHandler th = ((SAXTransformerFactory) TransformerFactory.newInstance()).newTransformerHandler();
DOMResult result = new DOMResult();
th.setResult(result);
th.startDocument();
th.startElement("", "root", "root", new AttributesImpl());
th.characters(new char[0], 0, 0);
th.endElement("", "root", "root");
th.endDocument();
// there's no point in having empty text --- we should remove it
Assert.assertEquals(0, ((Document) result.getNode()).getDocumentElement().getChildNodes().getLength());
}
public void test() throws Exception {
ClassReader cr = new ClassReader(is);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
SAXTransformerFactory saxtf = (SAXTransformerFactory) TransformerFactory.newInstance();
TransformerHandler handler = saxtf.newTransformerHandler();
handler.setResult(new SAXResult(new ASMContentHandler(bos, false)));
handler.startDocument();
cr.accept(new SAXClassAdapter(handler, false), false);
handler.endDocument();
assertEquals(cr, new ClassReader(bos.toByteArray()));
}
void save(File file, List<GanttPreviousStateTask> tasks) throws TransformerConfigurationException, SAXException {
StreamResult result = new StreamResult(file);
TransformerHandler handler = createHandler(result);
HistorySaver saver = new HistorySaver();
handler.startDocument();
saver.saveBaseline(myName, tasks, handler);
handler.endDocument();
}
@Override
protected void marshalToOutputStream(Marshaller ms, Object obj, OutputStream os,
Annotation[] anns, MediaType mt)
throws Exception {
Templates t = createTemplates(getOutTemplates(anns, mt), outParamsMap, outProperties);
if (t == null && supportJaxbOnly) {
super.marshalToOutputStream(ms, obj, os, anns, mt);
return;
}
org.apache.cxf.common.jaxb.JAXBUtils.setMinimumEscapeHandler(ms);
TransformerHandler th = null;
try {
th = factory.newTransformerHandler(t);
} catch (TransformerConfigurationException ex) {
TemplatesImpl ti = (TemplatesImpl)t;
th = factory.newTransformerHandler(ti.getTemplates());
this.trySettingProperties(th, ti);
}
Result result = getStreamResult(os, anns, mt);
if (systemId != null) {
result.setSystemId(systemId);
}
th.setResult(result);
if (getContext() == null) {
th.startDocument();
}
ms.marshal(obj, th);
if (getContext() == null) {
th.endDocument();
}
}
/**
* Copy the data points file of the raw data file from the temporary folder to the zip file.
* Create an XML file which contains the description of the same raw data file an copy it into the
* same zip file.
*
* @param rawDataFile raw data file to be copied
* @param rawDataSavedName name of the raw data inside the zip file
* @throws java.io.IOException
* @throws TransformerConfigurationException
* @throws SAXException
*/
void writeRawDataFile(RawDataFileImpl rawDataFile, int number)
throws IOException, TransformerConfigurationException, SAXException {
numOfScans = rawDataFile.getNumOfScans();
// Get the structure of the data points file
dataPointsOffsets = rawDataFile.getDataPointsOffsets();
dataPointsLengths = rawDataFile.getDataPointsLengths();
consolidatedDataPointsOffsets = new TreeMap<Integer, Long>();
// step 1 - save data file
logger.info("Saving data points of: " + rawDataFile.getName());
String rawDataSavedName = "Raw data file #" + number + " " + rawDataFile.getName();
zipOutputStream.putNextEntry(new ZipEntry(rawDataSavedName + ".scans"));
// We save only those data points that still have a reference in the
// dataPointsOffset table. Some deleted mass lists may still be present
// in the data points file, we don't want to copy those.
long newOffset = 0;
byte buffer[] = new byte[1 << 20];
RandomAccessFile dataPointsFile = rawDataFile.getDataPointsFile();
for (Integer storageID : dataPointsOffsets.keySet()) {
if (canceled)
return;
final long offset = dataPointsOffsets.get(storageID);
dataPointsFile.seek(offset);
final int bytes = dataPointsLengths.get(storageID) * 4 * 2;
consolidatedDataPointsOffsets.put(storageID, newOffset);
if (buffer.length < bytes) {
buffer = new byte[bytes * 2];
}
dataPointsFile.read(buffer, 0, bytes);
zipOutputStream.write(buffer, 0, bytes);
newOffset += bytes;
progress = 0.9 * ((double) offset / dataPointsFile.length());
}
if (canceled)
return;
// step 2 - save raw data description
logger.info("Saving raw data description of: " + rawDataFile.getName());
zipOutputStream.putNextEntry(new ZipEntry(rawDataSavedName + ".xml"));
OutputStream finalStream = zipOutputStream;
StreamResult streamResult = new StreamResult(finalStream);
SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
TransformerHandler hd = tf.newTransformerHandler();
Transformer serializer = hd.getTransformer();
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
hd.setResult(streamResult);
hd.startDocument();
saveRawDataInformation(rawDataFile, hd);
hd.endDocument();
}
public static void iccHeaderXml(LinkedHashMap<String, Object> header, File file) {
if (header == null || file == null) {
return;
}
try {
SAXTransformerFactory sf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
TransformerHandler handler = sf.newTransformerHandler();
Transformer transformer = handler.getTransformer();
transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
Result result = new StreamResult(new BufferedOutputStream(new FileOutputStream(file)));
handler.setResult(result);
handler.startDocument();
AttributesImpl attr = new AttributesImpl();
handler.startElement("", "", "IccProfile", attr);
handler.startElement("", "", "Header", attr);
handler.startElement("", "", "PreferredCMMType", attr);
String stringV = (String) header.get("CMMType");
handler.characters(stringV.toCharArray(), 0, stringV.length());
handler.endElement("", "", "PreferredCMMType");
handler.startElement("", "", "PCSIlluminant", attr);
attr.clear();
attr.addAttribute("", "", "X", "", header.get("x") + "");
attr.addAttribute("", "", "Y", "", header.get("y") + "");
attr.addAttribute("", "", "Z", "", header.get("z") + "");
handler.startElement("", "", "XYZNumber", attr);
handler.endElement("", "", "XYZNumber");
handler.endElement("", "", "PCSIlluminant");
handler.endElement("", "", "Header");
handler.endElement("", "", "IccProfile");
handler.endDocument();
} catch (Exception e) {
}
}
public void generate(Values values) throws IOException {
File dimenFile = values.dimenFile;
FileOutputStream fos = new FileOutputStream(dimenFile);
StreamResult result = new StreamResult(fos);
SAXTransformerFactory sff = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
TransformerHandler th = null;
try {
th = sff.newTransformerHandler();
Transformer transformer = th.getTransformer();
transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
th.setResult(result);
th.startDocument();
AttributesImpl attr = new AttributesImpl();
char[] space = "\n".toCharArray();
th.characters(space, 0, space.length);
th.startElement("", "", "resources", attr);
List<Dimen> dimens = values.dimens;
char[] spaceChar = "\n ".toCharArray();
for (Dimen dimen : dimens) {
//white space
th.characters(spaceChar, 0, spaceChar.length);
//name attr
attr.addAttribute("", "", "name", String.class.getName(), dimen.name);
th.startElement("", "", "dimen", attr);
char[] valueChars = String.format("%spx", dimen.value).toCharArray();
th.characters(valueChars, 0, valueChars.length);
th.endElement("", "", "dimen");
}
th.endElement("", "", "resources");
th.endDocument();
} catch (TransformerConfigurationException | SAXException e) {
e.printStackTrace();
} finally {
fos.close();
}
}
/**
* Copy the data points file of the raw data file from the temporary folder to the zip file.
* Create an XML file which contains the description of the same raw data file an copy it into the
* same zip file.
*
* @param rawDataFile raw data file to be copied
* @param rawDataSavedName name of the raw data inside the zip file
* @throws java.io.IOException
* @throws TransformerConfigurationException
* @throws SAXException
*/
void writeRawDataFile(RawDataFileImpl rawDataFile, int number)
throws IOException, TransformerConfigurationException, SAXException {
numOfScans = rawDataFile.getNumOfScans();
// Get the structure of the data points file
dataPointsOffsets = rawDataFile.getDataPointsOffsets();
dataPointsLengths = rawDataFile.getDataPointsLengths();
consolidatedDataPointsOffsets = new TreeMap<Integer, Long>();
// step 1 - save data file
logger.info("Saving data points of: " + rawDataFile.getName());
String rawDataSavedName = "Raw data file #" + number + " " + rawDataFile.getName();
zipOutputStream.putNextEntry(new ZipEntry(rawDataSavedName + ".scans"));
// We save only those data points that still have a reference in the
// dataPointsOffset table. Some deleted mass lists may still be present
// in the data points file, we don't want to copy those.
long newOffset = 0;
byte buffer[] = new byte[1 << 20];
RandomAccessFile dataPointsFile = rawDataFile.getDataPointsFile();
for (Integer storageID : dataPointsOffsets.keySet()) {
if (canceled)
return;
final long offset = dataPointsOffsets.get(storageID);
dataPointsFile.seek(offset);
final int bytes = dataPointsLengths.get(storageID) * 4 * 2;
consolidatedDataPointsOffsets.put(storageID, newOffset);
if (buffer.length < bytes) {
buffer = new byte[bytes * 2];
}
dataPointsFile.read(buffer, 0, bytes);
zipOutputStream.write(buffer, 0, bytes);
newOffset += bytes;
progress = 0.9 * ((double) offset / dataPointsFile.length());
}
if (canceled)
return;
// step 2 - save raw data description
logger.info("Saving raw data description of: " + rawDataFile.getName());
zipOutputStream.putNextEntry(new ZipEntry(rawDataSavedName + ".xml"));
OutputStream finalStream = zipOutputStream;
StreamResult streamResult = new StreamResult(finalStream);
SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
TransformerHandler hd = tf.newTransformerHandler();
Transformer serializer = hd.getTransformer();
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
hd.setResult(streamResult);
hd.startDocument();
saveRawDataInformation(rawDataFile, hd);
hd.endDocument();
}
@Override
public void save(OutputStream stream) throws IOException {
try {
AttributesImpl attrs = new AttributesImpl();
StreamResult result = new StreamResult(stream);
TransformerHandler handler = createHandler(result);
handler.startDocument();
addAttribute("name", getProject().getProjectName(), attrs);
addAttribute("company", getProject().getOrganization(), attrs);
addAttribute("webLink", getProject().getWebLink(), attrs);
if (area != null) {
addAttribute("view-date", CalendarFactory.createGanttCalendar(area.getStartDate()).toXMLString(), attrs);
}
if (myUIFacade != null) {
addAttribute("view-index", "" + myUIFacade.getViewIndex(), attrs);
// TODO for GP 2.0: move view configurations into <view> tag (see
// ViewSaver)
addAttribute("gantt-divider-location", "" + myUIFacade.getGanttDividerLocation(), attrs);
addAttribute("resource-divider-location", "" + myUIFacade.getResourceDividerLocation(), attrs);
}
addAttribute("version", VERSION, attrs);
addAttribute("locale", GanttLanguage.getInstance().getLocale().toString(), attrs);
startElement("project", attrs, handler);
//
// See https://bugs.openjdk.java.net/browse/JDK-8133452
if (getProject().getDescription() != null) {
String projectDescription = getProject().getDescription().replace("\\r\\n", "\\n");
cdataElement("description", projectDescription, attrs, handler);
}
saveViews(handler);
emptyComment(handler);
saveCalendar(handler);
saveTasks(handler);
saveResources(handler);
saveAssignments(handler);
saveVacations(handler);
saveHistory(handler);
saveRoles(handler);
endElement("project", handler);
handler.endDocument();
stream.close();
} catch (Throwable e) {
if (!GPLogger.log(e)) {
e.printStackTrace(System.err);
}
IOException propagatedException = new IOException("Failed to save the project file");
propagatedException.initCause(e);
throw propagatedException;
}
}
void serialize(TransformerHandler handler, File outputFile) throws SAXException, IOException, ExportException {
String filenameWithoutExtension = getFilenameWithoutExtension(outputFile);
handler.startDocument();
AttributesImpl attrs = new AttributesImpl();
writeViews(getUIFacade(), handler);
startElement("ganttproject", attrs, handler);
textElement("title", attrs, "GanttProject - " + filenameWithoutExtension, handler);
addAttribute("prefix", filenameWithoutExtension, attrs);
startElement("links", attrs, handler);
textElement("home", attrs, i18n("home"), handler);
textElement("chart", attrs, i18n("gantt"), handler);
textElement("tasks", attrs, i18n("task"), handler);
textElement("resources", attrs, i18n("human"), handler);
endElement("links", handler);
startElement("project", attrs, handler);
addAttribute("title", i18n("project"), attrs);
textElement("name", attrs, getProject().getProjectName(), handler);
addAttribute("title", i18n("organization"), attrs);
textElement("organization", attrs, getProject().getOrganization(), handler);
addAttribute("title", i18n("webLink"), attrs);
textElement("webLink", attrs, getProject().getWebLink(), handler);
addAttribute("title", i18n("shortDescription"), attrs);
textElement("description", attrs, getProject().getDescription(), handler);
endElement("project", handler);
// TODO: [dbarashev, 10.09.2005] introduce output files grouping structure
String ganttChartFileName = ExporterToHTML.replaceExtension(outputFile, ExporterToHTML.GANTT_CHART_FILE_EXTENSION).getName();
textElement("chart", attrs, ganttChartFileName, handler);
addAttribute("name", i18n("colName"), attrs);
addAttribute("role", i18n("colRole"), attrs);
addAttribute("mail", i18n("colMail"), attrs);
addAttribute("phone", i18n("colPhone"), attrs);
startElement("resources", attrs, handler);
writeResources(getProject().getHumanResourceManager(), handler);
String resourceChartFileName = ExporterToHTML.replaceExtension(outputFile,
ExporterToHTML.RESOURCE_CHART_FILE_EXTENSION).getName();
addAttribute("path", resourceChartFileName, attrs);
emptyElement("chart", attrs, handler);
endElement("resources", handler);
// addAttribute("name", i18n("name"), attrs);
// addAttribute("begin", i18n("start"), attrs);
// addAttribute("end", i18n("end"), attrs);
// addAttribute("milestone", i18n("meetingPoint"), attrs);
// addAttribute("progress", i18n("advancement"), attrs);
// addAttribute("assigned-to", i18n("assignTo"), attrs);
// addAttribute("notes", i18n("notesTask"), attrs);
try {
writeTasks(getProject().getTaskManager(), handler);
} catch (Exception e) {
throw new ExportException("Failed to write tasks", e);
}
addAttribute("version", "Ganttproject (" + GPVersion.CURRENT + ")", attrs);
Calendar c = CalendarFactory.newCalendar();
String dateAndTime = GanttLanguage.getInstance().formatShortDate(c) + " - " + GanttLanguage.getInstance().formatTime(c);
addAttribute("date", dateAndTime, attrs);
emptyElement("footer", attrs, handler);
endElement("ganttproject", handler);
handler.endDocument();
}
private void generateXml(IvyNode[] dependencies,
Map<ModuleRevisionId, Set<ArtifactDownloadReport>> moduleRevToArtifactsMap,
Map<ArtifactDownloadReport, Set<String>> artifactsToCopy) {
try {
try (FileOutputStream fileOutputStream = new FileOutputStream(tofile)) {
TransformerHandler saxHandler = createTransformerHandler(fileOutputStream);
saxHandler.startDocument();
saxHandler.startElement(null, "modules", "modules", new AttributesImpl());
for (IvyNode dependency : dependencies) {
if (dependency.getModuleRevision() == null
|| dependency.isCompletelyEvicted()) {
continue;
}
startModule(saxHandler, dependency);
Set<ArtifactDownloadReport> artifactsOfModuleRev = moduleRevToArtifactsMap.get(dependency
.getModuleRevision().getId());
if (artifactsOfModuleRev != null) {
for (ArtifactDownloadReport artifact : artifactsOfModuleRev) {
RepositoryCacheManager cache = dependency.getModuleRevision()
.getArtifactResolver().getRepositoryCacheManager();
startArtifact(saxHandler, artifact.getArtifact());
writeOriginLocationIfPresent(cache, saxHandler, artifact);
writeCacheLocationIfPresent(cache, saxHandler, artifact);
for (String artifactDestPath : artifactsToCopy.get(artifact)) {
writeRetrieveLocation(saxHandler, artifactDestPath);
}
saxHandler.endElement(null, "artifact", "artifact");
}
}
saxHandler.endElement(null, "module", "module");
}
saxHandler.endElement(null, "modules", "modules");
saxHandler.endDocument();
}
} catch (SAXException | IOException | TransformerConfigurationException e) {
throw new BuildException("impossible to generate report", e);
}
}
/**
* Creates output XML from all read records using SAX.
* Call this after all records are stored in PortDefinition structures.
* @throws TransformerConfigurationException
* @throws SAXException
* @throws IOException
*/
/*
private void flushXmlSax() throws TransformerConfigurationException, SAXException, IOException {
FileOutputStream fos = new FileOutputStream(fileUrl);
TransformerHandler hd = createHeader(fos);
PortDefinition portDefinition = rootPortDefinition;
// for each record of port
for (Map.Entry<HashKey, TreeRecord> e : portDefinition.dataMap.entrySet()){
TreeRecord record = e.getValue();
List<DataRecord> records = new ArrayList<DataRecord>();
records.add(record.record);
addRecords(hd, records, portDefinition);
}// for record
createFooter(fos, hd);
}*/
private TransformerHandler createHeader(OutputStream os) throws FileNotFoundException, TransformerConfigurationException, SAXException {
StreamResult streamResult = new StreamResult(os);
SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
// SAX2.0 ContentHandler.
TransformerHandler hd = tf.newTransformerHandler();
Transformer serializer = hd.getTransformer();
serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
serializer.setOutputProperty(OutputKeys.ENCODING, this.charset);
//serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"users.dtd");
if (omitNewLines)
serializer.setOutputProperty(OutputKeys.INDENT,"no");
else
serializer.setOutputProperty(OutputKeys.INDENT,"yes");
hd.setResult(streamResult);
hd.startDocument();
String root = (rootElement!=null && rootElement.length()>0) ? rootElement : DEFAULT_ROOT_ELEMENT;
if (useRootElement && dtdPublicId != null && dtdPublicId.trim().length()>0 && dtdSystemId != null && dtdSystemId.trim().length()>0){
hd.startDTD(root, dtdPublicId, dtdSystemId);
hd.endDTD();
}
//if (recordsPerFile!=1){
if (this.useRootElement) {
AttributesImpl atts = new AttributesImpl();
if (rootInfoAttributes) {
atts.addAttribute("", ATTRIBUTE_COMPONENT_ID, ATTRIBUTE_COMPONENT_ID, "CDATA", getId());
atts.addAttribute("", ATTRIBUTE_GRAPH_NAME, ATTRIBUTE_GRAPH_NAME, "CDATA", this.getGraph().getName());
atts.addAttribute("", ATTRIBUTE_CREATED, ATTRIBUTE_CREATED, "CDATA", (new Date()).toString());
}
if (!StringUtils.isEmpty(xsdSchemaLocation)) {
atts.addAttribute(XSI_URI, "schemaLocation", "xsi:schemaLocation", "CDATA", this.xsdSchemaLocation);
}
for (String prefix : namespaces.keySet()) {
String uri = namespaces.get(prefix);
hd.startPrefixMapping(prefix, uri);
}
if (!rootDefaultNamespace.isEmpty()) {
hd.startPrefixMapping("", rootDefaultNamespace);
}
hd.startElement(rootDefaultNamespace, getLocalName(root), root, atts);
}
return hd;
}
/**
* Function which creates an XML file with user parameters
*/
void saveParameters() throws SAXException, IOException, TransformerConfigurationException {
logger.info("Saving user parameters");
StreamResult streamResult = new StreamResult(finalStream);
SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
TransformerHandler hd = tf.newTransformerHandler();
Transformer serializer = hd.getTransformer();
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
hd.setResult(streamResult);
hd.startDocument();
UserParameter<?, ?> projectParameters[] = project.getParameters();
AttributesImpl atts = new AttributesImpl();
atts.addAttribute("", "", UserParameterElementName.COUNT.getElementName(), "CDATA",
String.valueOf(projectParameters.length));
hd.startElement("", "", UserParameterElementName.PARAMETERS.getElementName(), atts);
atts.clear();
// <PARAMETER>
for (UserParameter<?, ?> parameter : project.getParameters()) {
if (canceled)
return;
logger.finest("Saving user parameter " + parameter.getName());
atts.addAttribute("", "", UserParameterElementName.NAME.getElementName(), "CDATA",
parameter.getName());
atts.addAttribute("", "", UserParameterElementName.TYPE.getElementName(), "CDATA",
parameter.getClass().getSimpleName());
hd.startElement("", "", UserParameterElementName.PARAMETER.getElementName(), atts);
atts.clear();
fillParameterElement(parameter, hd);
hd.endElement("", "", UserParameterElementName.PARAMETER.getElementName());
completedParameters++;
}
hd.endElement("", "", UserParameterElementName.PARAMETERS.getElementName());
hd.endDocument();
}
/**
* Function which creates an XML file with user parameters
*/
void saveParameters() throws SAXException, IOException, TransformerConfigurationException {
logger.info("Saving user parameters");
StreamResult streamResult = new StreamResult(finalStream);
SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
TransformerHandler hd = tf.newTransformerHandler();
Transformer serializer = hd.getTransformer();
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
hd.setResult(streamResult);
hd.startDocument();
UserParameter<?, ?> projectParameters[] = project.getParameters();
AttributesImpl atts = new AttributesImpl();
atts.addAttribute("", "", UserParameterElementName.COUNT.getElementName(), "CDATA",
String.valueOf(projectParameters.length));
hd.startElement("", "", UserParameterElementName.PARAMETERS.getElementName(), atts);
atts.clear();
// <PARAMETER>
for (UserParameter<?, ?> parameter : project.getParameters()) {
if (canceled)
return;
logger.finest("Saving user parameter " + parameter.getName());
atts.addAttribute("", "", UserParameterElementName.NAME.getElementName(), "CDATA",
parameter.getName());
atts.addAttribute("", "", UserParameterElementName.TYPE.getElementName(), "CDATA",
parameter.getClass().getSimpleName());
hd.startElement("", "", UserParameterElementName.PARAMETER.getElementName(), atts);
atts.clear();
fillParameterElement(parameter, hd);
hd.endElement("", "", UserParameterElementName.PARAMETER.getElementName());
completedParameters++;
}
hd.endElement("", "", UserParameterElementName.PARAMETERS.getElementName());
hd.endDocument();
}