001: /*
002: * BEGIN_HEADER - DO NOT EDIT
003: *
004: * The contents of this file are subject to the terms
005: * of the Common Development and Distribution License
006: * (the "License"). You may not use this file except
007: * in compliance with the License.
008: *
009: * You can obtain a copy of the license at
010: * https://open-esb.dev.java.net/public/CDDLv1.0.html.
011: * See the License for the specific language governing
012: * permissions and limitations under the License.
013: *
014: * When distributing Covered Code, include this CDDL
015: * HEADER in each file and include the License file at
016: * https://open-esb.dev.java.net/public/CDDLv1.0.html.
017: * If applicable add the following below this CDDL HEADER,
018: * with the fields enclosed by brackets "[]" replaced with
019: * your own identifying information: Portions Copyright
020: * [year] [name of copyright owner]
021: */
022:
023: /*
024: * @(#)FrameworkStatisticsDataWriter.java
025: * Copyright 2004-2007 Sun Microsystems, Inc. All Rights Reserved.
026: *
027: * END_HEADER - DO NOT EDIT
028: */
029: package com.sun.esb.management.common.data.helper;
030:
031: import java.io.BufferedWriter;
032: import java.io.File;
033: import java.io.FileNotFoundException;
034: import java.io.FileWriter;
035: import java.io.IOException;
036: import java.io.Serializable;
037: import java.io.StringWriter;
038: import java.io.Writer;
039: import java.net.MalformedURLException;
040: import java.net.URISyntaxException;
041: import java.util.Map;
042:
043: import javax.xml.parsers.DocumentBuilder;
044: import javax.xml.parsers.DocumentBuilderFactory;
045: import javax.xml.parsers.ParserConfigurationException;
046: import javax.xml.transform.OutputKeys;
047: import javax.xml.transform.Transformer;
048: import javax.xml.transform.TransformerConfigurationException;
049: import javax.xml.transform.TransformerException;
050: import javax.xml.transform.TransformerFactory;
051: import javax.xml.transform.dom.DOMSource;
052: import javax.xml.transform.stream.StreamResult;
053:
054: import org.w3c.dom.Document;
055: import org.w3c.dom.Element;
056: import org.xml.sax.SAXException;
057:
058: import com.sun.esb.management.common.data.FrameworkStatisticsData;
059:
060: /**
061: * @author graj
062: *
063: */
064: public class FrameworkStatisticsDataWriter implements
065: FrameworkStatisticsDataXMLConstants, Serializable {
066:
067: static final long serialVersionUID = -1L;
068:
069: static final String FILE_NAME_KEY = "FrameworkStatisticsData.xml";
070:
071: /** Constructor - Creates an FrameworkStatisticsDataWriter */
072: public FrameworkStatisticsDataWriter() {
073: }
074:
075: /**
076: *
077: * @param document
078: * @param directoryPath
079: * @throws TransformerConfigurationException
080: * @throws TransformerException
081: * @throws Exception
082: */
083: public static void writeToFile(Document document,
084: String directoryPath)
085: throws TransformerConfigurationException,
086: TransformerException, Exception {
087: File file = new File(directoryPath);
088: if ((file.isDirectory() == false) || (file.exists() == false)) {
089: throw new Exception("Directory Path: " + directoryPath
090: + " is invalid.");
091: }
092: String fileLocation = file.getAbsolutePath() + File.separator
093: + FILE_NAME_KEY;
094: System.out.println("Writing out to file: " + fileLocation);
095: File outputFile = new File(fileLocation);
096: // Use a Transformer for aspectOutput
097: TransformerFactory tFactory = TransformerFactory.newInstance();
098: Transformer transformer = tFactory.newTransformer();
099: DOMSource source = new DOMSource(document);
100: StreamResult result = new StreamResult(outputFile);
101:
102: // indent the Output to make it more legible...
103: transformer.setOutputProperty(OutputKeys.METHOD, "xml");
104: transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
105: transformer
106: .setOutputProperty(OutputKeys.MEDIA_TYPE, "text/xml");
107: transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
108: transformer.setOutputProperty(
109: "{http://xml.apache.org/xslt}indent-amount", "4");
110: transformer.setOutputProperty(OutputKeys.INDENT, "yes");
111:
112: transformer.transform(source, result);
113: }
114:
115: /**
116: * Change the contents of text file in its entirety, overwriting any
117: * existing text. This style of implementation throws all exceptions to the
118: * caller.
119: *
120: * @param aFile
121: * is an existing file which can be written to.
122: * @throws IllegalArgumentException
123: * if param does not comply.
124: * @throws FileNotFoundException
125: * if the file does not exist.
126: * @throws IOException
127: * if problem encountered during write.
128: */
129: public static void setContents(File aFile, String aContents)
130: throws FileNotFoundException, IOException {
131: if (aFile == null) {
132: throw new IllegalArgumentException(
133: "File should not be null.");
134: }
135: if (!aFile.exists()) {
136: aFile.createNewFile();
137: }
138: if (!aFile.isFile()) {
139: throw new IllegalArgumentException(
140: "Should not be a directory: " + aFile);
141: }
142: if (!aFile.canWrite()) {
143: throw new IllegalArgumentException(
144: "File cannot be written: " + aFile);
145: }
146:
147: // declared here only to make visible to finally clause; generic
148: // reference
149: Writer output = null;
150: try {
151: // use buffering
152: // FileWriter always assumes default encoding is OK!
153: output = new BufferedWriter(new FileWriter(aFile));
154: output.write(aContents);
155: } finally {
156: // flush and close both "aspectOutput" and its underlying FileWriter
157: if (output != null) {
158: output.close();
159: }
160: }
161: }
162:
163: /**
164: *
165: * @param NMRStatisticsData
166: * data
167: * @return XML string
168: * @throws ParserConfigurationException
169: * @throws TransformerException
170: */
171: public static String serialize(
172: Map<String /* instanceName */, FrameworkStatisticsData> dataMap)
173: throws ParserConfigurationException, TransformerException {
174: Document document = null;
175: FrameworkStatisticsDataWriter writer = new FrameworkStatisticsDataWriter();
176: if (dataMap != null) {
177: DocumentBuilderFactory factory = DocumentBuilderFactory
178: .newInstance();
179: DocumentBuilder builder = factory.newDocumentBuilder();
180: document = builder.newDocument(); // Create from whole cloth
181:
182: // ////////////////////////////////
183: // <FrameworkStatisticsDataList>
184: Element root = (Element) document
185: .createElement(FRAMEWORK_STATISTICS_DATA_LIST_KEY);
186: // xmlns="http://java.sun.com/xml/ns/esb/management/FrameworkStatisticsData"
187: root.setAttribute(NAMESPACE_KEY, NAMESPACE_VALUE);
188: // version = "1.0"
189: root.setAttribute(VERSION_KEY, VERSION_VALUE);
190:
191: for (String instanceName : dataMap.keySet()) {
192: FrameworkStatisticsData data = dataMap
193: .get(instanceName);
194: // ////////////////////////////////
195: // <FrameworkStatisticsData>
196: Element frameworkStatisticsDataElementChild = writer
197: .createFrameworkStatisticsDataElement(document,
198: data);
199: // </FrameworkStatisticsData>
200: root.appendChild(frameworkStatisticsDataElementChild);
201: // ////////////////////////////////
202: }
203:
204: // ////////////////////////////////
205: // </FrameworkStatisticsDataList>
206: document.appendChild(root);
207: // ////////////////////////////////
208:
209: }
210: return writer.writeToString(document);
211: }
212:
213: /**
214: *
215: * @param document
216: * @param data
217: * @return
218: */
219: protected Element createFrameworkStatisticsDataElement(
220: Document document, FrameworkStatisticsData data) {
221: Element frameworkStatisticsDataElement = null;
222: if ((document != null) && (data != null)) {
223:
224: // <FrameworkStatisticsData>
225: frameworkStatisticsDataElement = document
226: .createElement(FRAMEWORK_STATISTICS_DATA_KEY);
227:
228: // <InstanceName>
229: Element instanceNameElementChild = document
230: .createElement(INSTANCE_NAME_KEY);
231: if (instanceNameElementChild != null) {
232: instanceNameElementChild.setTextContent(data
233: .getInstanceName());
234: }
235: // </InstanceName>
236: frameworkStatisticsDataElement
237: .appendChild(instanceNameElementChild);
238:
239: // <StartupTime>
240: Element startupTimeElementChild = document
241: .createElement(STARTUP_TIME_KEY);
242: if (startupTimeElementChild != null) {
243: startupTimeElementChild.setTextContent(data
244: .getStartupTime()
245: + "");
246: }
247: // </StartupTime>
248: frameworkStatisticsDataElement
249: .appendChild(startupTimeElementChild);
250:
251: // <UpTime>
252: Element upTimeElementChild = document
253: .createElement(UP_TIME_KEY);
254: if (upTimeElementChild != null) {
255: upTimeElementChild
256: .setTextContent(data.getUpTime() + "");
257: }
258: // </UpTime>
259: frameworkStatisticsDataElement
260: .appendChild(upTimeElementChild);
261: }
262:
263: return frameworkStatisticsDataElement;
264: }
265:
266: /**
267: * @param document
268: * @return
269: * @throws TransformerException
270: */
271: protected String writeToString(Document document)
272: throws TransformerException {
273: // Use a Transformer for aspectOutput
274: TransformerFactory tFactory = TransformerFactory.newInstance();
275: Transformer transformer = tFactory.newTransformer();
276: DOMSource source = new DOMSource(document);
277: StringWriter writer = new StringWriter();
278: StreamResult result = new StreamResult(writer);
279:
280: transformer.setOutputProperty(OutputKeys.METHOD, "xml");
281: transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
282: transformer
283: .setOutputProperty(OutputKeys.MEDIA_TYPE, "text/xml");
284: transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
285:
286: // indent the aspectOutput to make it more legible...
287: transformer.setOutputProperty(
288: "{http://xml.apache.org/xslt}indent-amount", "4");
289: transformer.setOutputProperty(OutputKeys.INDENT, "yes");
290: transformer.transform(source, result);
291:
292: return result.getWriter().toString();
293: }
294:
295: /**
296: * @param args
297: */
298: public static void main(String[] args) {
299: String uri = "C:/test/schema/frameworkstatistics/FrameworkStatisticsData.xml";
300: try {
301: Map<String /* instanceName */, FrameworkStatisticsData> map = null;
302: map = FrameworkStatisticsDataReader.parseFromFile(uri);
303: for (String instanceName : map.keySet()) {
304: System.out.println(map.get(instanceName)
305: .getDisplayString());
306: }
307:
308: String content = FrameworkStatisticsDataWriter
309: .serialize(map);
310: System.out.println(content);
311: FrameworkStatisticsDataWriter.setContents(new File(uri),
312: content);
313:
314: } catch (MalformedURLException e) {
315: e.printStackTrace();
316: } catch (FileNotFoundException e) {
317: e.printStackTrace();
318: } catch (ParserConfigurationException e) {
319: e.printStackTrace();
320: } catch (SAXException e) {
321: e.printStackTrace();
322: } catch (URISyntaxException e) {
323: e.printStackTrace();
324: } catch (IOException e) {
325: e.printStackTrace();
326: } catch (TransformerException e) {
327: e.printStackTrace();
328: }
329: }
330:
331: }
|