package com.simoncat.beans;
import com.simoncat.vo.Server;
import java.util.Collection;
import java.io.*;
import java.util.Properties;
import javax.servlet.*;
import javax.servlet.http.*;
/**
* A sample DOM counter. This sample program illustrates how to
* traverse a DOM tree in order to information about the document.
*
* @version $id$
*/
//import util.Arguments;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import org.apache.xerces.dom.TextImpl;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.persistence.FileStreamStrategy;
import com.thoughtworks.xstream.persistence.StreamStrategy;
import com.thoughtworks.xstream.persistence.XmlArrayList;
import java.util.List;
import java.util.ArrayList;
public class XMLServers
{
private final static String XML_PROLOG = "<?xml version=\"1.0\"?>";
private final static String ROOT_OPEN = "<servers>";
private final static String SERVER_OPEN = " <server>";
private final static String NAME_OPEN = " <name>";
private final static String IP_OPEN = " <i_p>";
private final static String USER_OPEN = " <user>";
private final static String PASSWORD_OPEN = " <password>";
private final static String OBSERVATION_OPEN = " <observation>";
private final static String SERVER_CLOSE = " </server>";
private final static String NAME_CLOSE = "</name>";
private final static String IP_CLOSE = "</i_p>";
private final static String USER_CLOSE = "</user>";
private final static String PASSWORD_CLOSE = "</password>";
private final static String OBSERVATION_CLOSE = "</observation>";
private final static String ROOT_CLOSE = "</servers>";
public boolean writeToXmlSingle(Server server,String path,ServletContext sc)
{
BufferedWriter writer = null; //Declare writer here so it can be closed in finally clause
boolean r=true;
try
{
Properties sysprops = System.getProperties();
String c = sysprops.getProperty("file.separator");
//PrintWriter out = response.getWriter();
String notes = "this is the string";
String filename = "servers.xml";
String path1 = new String();
//ServletContext sc = this.getServletContext();
path1 = sc.getRealPath("/");
//FileOutputStream fos = new FileOutputStream(path + c + filename);
//byte[] bytes = notes.getBytes();
//fos.write(bytes);
//System.out.println("++++++++++++++++Created " + filename + " in " + path1 + "WEB-INF" + c);
//System.out.println("+++");
File file = new File(path1 + "WEB-INF" + c + filename);
//System.out.println("+++ EXISTS:"+file.exists());
StringBuffer buf = null; //A buffer that may be used to hold already written file content
//prepares the file strategy to directory /tmp
StreamStrategy strategy = new FileStreamStrategy(new File(path1+ "WEB-INF" + c));
// creates the list:
List list = new XmlArrayList(strategy);
list.add(server);
} catch (Exception e)
{
e.printStackTrace();
r=false;
}
return r;
}
public boolean writeToXml(Server server,String path,ServletContext sc)
{
boolean r=true;
try
{
//CREAR xml Single con datos del servidor
writeToXmlSingle(server,path,sc);
} catch (Exception e)
{
e.printStackTrace();
r=false;
}
return r;
}
//version enterio q crea el xml single y adiciona el nuevo servidor al archivo servers.xml
// eliminado por q al presentar se duplican los datos de servidores
public boolean writeToXml_(Server server,String path,ServletContext sc)
{
BufferedWriter writer = null; //Declare writer here so it can be closed in finally clause
boolean r=true;
try
{
Properties sysprops = System.getProperties();
String c = sysprops.getProperty("file.separator");
//PrintWriter out = response.getWriter();
String notes = "this is the string";
String filename = "servers.xml";
String path1 = new String();
//ServletContext sc = this.getServletContext();
path1 = sc.getRealPath("/");
//FileOutputStream fos = new FileOutputStream(path + c + filename);
//byte[] bytes = notes.getBytes();
//fos.write(bytes);
//System.out.println("++++++++++++++++Created " + filename + " in " + path1 + "WEB-INF" + c);
//System.out.println("+++");
File file = new File(path1 + "WEB-INF" + c + filename);
//System.out.println("+++ EXISTS:"+file.exists());
StringBuffer buf = null; //A buffer that may be used to hold already written file content
if (file.exists())
{
//Create buffer (with appropriate size to reduce overhead/increase performance)
buf = new StringBuffer((file.length() <= Integer.MAX_VALUE) ? (int) file.length() : Integer.MAX_VALUE);
//Connect to file and read into buffer
BufferedReader reader = new BufferedReader(new FileReader(file));
for (String line = null; (line = reader.readLine()) != null; )
{
//Ensure root elements and xml prolog is NOT put into buffer
if (!(line.startsWith(XML_PROLOG) || line.startsWith(ROOT_OPEN) || line.startsWith(ROOT_CLOSE)))
{
buf.append(line);
buf.append('\n');
}
}
}
writer = new BufferedWriter(new FileWriter(file));
writer.write(XML_PROLOG);
writer.newLine();
writer.write(ROOT_OPEN);
writer.newLine();
if (buf != null)
{
writer.write(buf.toString());
}
writer.write(SERVER_OPEN);
writer.newLine();
writer.write(NAME_OPEN);
writer.write(server.getName());
writer.write(NAME_CLOSE);
writer.newLine();
writer.write(IP_OPEN);
writer.write(server.getI_P());
writer.write(IP_CLOSE);
writer.newLine();
writer.write(USER_OPEN);
writer.write(server.getUser());
writer.write(USER_CLOSE);
writer.newLine();
writer.write(PASSWORD_OPEN);
writer.write(server.getPassword());
writer.write(PASSWORD_CLOSE);
writer.newLine();
writer.write(OBSERVATION_OPEN);
if(server.getObservation()!=null)
writer.write(server.getObservation());
writer.write(OBSERVATION_CLOSE);
writer.newLine();
writer.write(SERVER_CLOSE);
writer.newLine();
writer.write(ROOT_CLOSE);
writer.newLine();
//CREAR xml Single con datos del servidor
writeToXmlSingle(server,path,sc);
} catch (Exception e)
{
e.printStackTrace();
r=false;
} finally
{
if (writer != null)
{
try
{
writer.close();
} catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
return r;
}
public Server loadServerByName(String name,ServletContext sc){
Server[] servers = readXmls("",sc);
Server s=null;
for(int i=0;i<servers.length;i++){
if(servers[i].getName().equals(name)){
s=servers[i];
break;
}
}
return s;
}
public Server[] readXmls(String path,ServletContext sc)
{
BufferedWriter writer = null; //Declare writer here so it can be closed in finally clause
boolean r=true;
Server servers[] = null;
ArrayList <Server>serverList = new ArrayList();
try
{
Properties sysprops = System.getProperties();
String c = sysprops.getProperty("file.separator");
//PrintWriter out = response.getWriter();
String notes = "this is the string";
String filename = "servers.xml";
String path1 = new String();
//ServletContext sc = this.getServletContext();
path1 = sc.getRealPath("/");
//FileOutputStream fos = new FileOutputStream(path + c + filename);
//byte[] bytes = notes.getBytes();
//fos.write(bytes);
File f = new File(path1 + "WEB-INF" + c );
FilenameFilter ff = new OnlyExt("xml");
String s[] = f.list(ff);
XStream xstream = new XStream(); // Require XPP3 library
xstream.alias("server",com.simoncat.vo.Server.class);
for(int i=0;i<s.length;i++){
//System.out.println("++++++++++++++++to Read " + s[i] + " in " + path1 + "WEB-INF" + c);
File file = new File(path1 + "WEB-INF" + c + s[i]);
//System.out.println("+++ EXISTS:"+file.exists());
StringBuffer buf = null; //A buffer that may be used to hold already written file content
//Create buffer (with appropriate size to reduce overhead/increase performance)
buf = new StringBuffer((file.length() <= Integer.MAX_VALUE) ? (int) file.length() : Integer.MAX_VALUE);
//System.out.println("1+");
//Connect to file and read into buffer
BufferedReader reader = new BufferedReader(new FileReader(file));
//System.out.println("2+");
for (String line = null; (line = reader.readLine()) != null; ){
//Ensure root elements and xml prolog is NOT put into buffer
if (!(line.startsWith(XML_PROLOG) || line.startsWith(ROOT_OPEN) || line.startsWith(ROOT_CLOSE))){
buf.append(line);
buf.append('\n');
}
//System.out.println("3+");
}
//System.out.println("4+");
String xml=buf.toString();
//System.out.println("5+");
try{
Server ser = (Server)xstream.fromXML(xml);
//System.out.println("-->"+ser.toString());
ser.setFilePath(path1 + "WEB-INF" + c + s[i]);
serverList.add(ser);
}
catch(Exception e){
System.out.println("PROBLEMA LEYENDO EL XML");
}
//System.out.println("6+");
}
}
catch(Exception e){
e.printStackTrace();
}
if(serverList.size()>0){
servers= new Server[serverList.size()];
for(int jj=0;jj<servers.length;jj++)
servers[jj]=(Server)serverList.get(jj);
}
//System.out.println("7+");
return servers;
}
public Server[] readXml(String path,ServletContext sc)
{
BufferedWriter writer = null; //Declare writer here so it can be closed in finally clause
boolean r=true;
try
{
//DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
//InputStream documentStream = new ByteArrayInputStream(documentXMLSourceString.getBytes("utf-8"));
//Document document = db.parse(documentStream);
Properties sysprops = System.getProperties();
String c = sysprops.getProperty("file.separator");
//PrintWriter out = response.getWriter();
String notes = "this is the string";
String filename = "servers.xml";
String path1 = new String();
//ServletContext sc = this.getServletContext();
path1 = sc.getRealPath("/");
//FileOutputStream fos = new FileOutputStream(path + c + filename);
//byte[] bytes = notes.getBytes();
//fos.write(bytes);
//System.out.println("++++++++++++++++Created " + filename + " in " + path1 + "WEB-INF" + c);
//System.out.println("+++");
File file = new File(path1 + "WEB-INF" + c + filename);
//System.out.println("+++ EXISTS:"+file.exists());
StringBuffer buf = null; //A buffer that may be used to hold already written file content
if (file.exists())
{
//Create buffer (with appropriate size to reduce overhead/increase performance)
buf = new StringBuffer((file.length() <= Integer.MAX_VALUE) ? (int) file.length() : Integer.MAX_VALUE);
//Connect to file and read into buffer
BufferedReader reader = new BufferedReader(new FileReader(file));
for (String line = null; (line = reader.readLine()) != null; )
{
//Ensure root elements and xml prolog is NOT put into buffer
if (!(line.startsWith(XML_PROLOG) || line.startsWith(ROOT_OPEN) || line.startsWith(ROOT_CLOSE)))
{
buf.append(line);
buf.append('\n');
}
}
DOMCount ndc = new DOMCount();
ndc.count("com.simoncat.beans.wrappers.DOMParser",path1 + "WEB-INF" + c + filename);
}
} catch (Exception e)
{
e.printStackTrace();
r=false;
}
return new Server[4];
}
//Other methods...
}
class DOMCount {
//
// Constants
//
/** Default parser name. */
private static final String
DEFAULT_PARSER_NAME = "com.simoncat.beans.wrappers.DOMParser";
private static boolean setValidation = false; //defaults
private static boolean setNameSpaces = true;
private static boolean setSchemaSupport = true;
private static boolean setSchemaFullSupport = false;
private static boolean setDeferredDOM = true;
//
// Data
//
/** Elements. */
private long elements;
/** Attributes. */
private long attributes;
/** Characters. */
private long characters;
/** Ignorable whitespace. */
private long ignorableWhitespace;
//
// Public static methods
//
/** Counts the resulting document tree. */
public static void count(String parserWrapperName, String uri) {
try {
DOMParserWrapper parser =
(DOMParserWrapper)Class.forName(parserWrapperName).newInstance();
DOMCount counter = new DOMCount();
long before = System.currentTimeMillis();
//parser.setFeature( "http://apache.org/xml/features/dom/defer-node-expansion",setDeferredDOM );
//parser.setFeature( "http://xml.org/sax/features/validation",setValidation );
//parser.setFeature( "http://xml.org/sax/features/namespaces",setNameSpaces );
//parser.setFeature( "http://apache.org/xml/features/validation/schema",setSchemaSupport );
//parser.setFeature( "http://apache.org/xml/features/validation/schema-full-checking",setSchemaFullSupport );
Document document = parser.parse(uri);
counter.traverse(document);
long after = System.currentTimeMillis();
counter.printResults(uri, after - before);
} catch (org.xml.sax.SAXParseException spe) {
} catch (org.xml.sax.SAXNotRecognizedException ex ){
} catch (org.xml.sax.SAXNotSupportedException ex ){
} catch (org.xml.sax.SAXException se) {
if (se.getException() != null)
se.getException().printStackTrace(System.err);
else
se.printStackTrace(System.err);
} catch (Exception e) {
e.printStackTrace(System.err);
}
} // print(String,String,boolean)
//
// Public methods
//
/** Traverses the specified node, recursively. */
public void traverse(Node node) {
// is there anything to do?
if (node == null) {
return;
}
int type = node.getNodeType();
switch (type) {
// print document
case Node.DOCUMENT_NODE: {
elements = 0;
attributes = 0;
characters = 0;
ignorableWhitespace = 0;
traverse(((Document)node).getDocumentElement());
break;
}
// print element with attributes
case Node.ELEMENT_NODE: {
elements++;
NamedNodeMap attrs = node.getAttributes();
if (attrs != null) {
attributes += attrs.getLength();
}
NodeList children = node.getChildNodes();
if (children != null) {
int len = children.getLength();
for (int i = 0; i < len; i++) {
traverse(children.item(i));
}
}
break;
}
// handle entity reference nodes
case Node.ENTITY_REFERENCE_NODE: {
NodeList children = node.getChildNodes();
if (children != null) {
int len = children.getLength();
for (int i = 0; i < len; i++) {
traverse(children.item(i));
}
}
break;
}
// print text
case Node.CDATA_SECTION_NODE: {
characters += node.getNodeValue().length();
break;
}
case Node.TEXT_NODE: {
if (node instanceof TextImpl) {
if (((TextImpl)node).isIgnorableWhitespace())
ignorableWhitespace += node.getNodeValue().length();
else
characters += node.getNodeValue().length();
} else
characters += node.getNodeValue().length();
break;
}
}
} // traverse(Node)
/** Prints the results. */
public void printResults(String uri, long time) {
// filename.xml: 631 ms (4 elems, 0 attrs, 78 spaces, 0 chars)
System.out.print(uri);
System.out.print(": ");
System.out.print(time);
System.out.print(" ms (");
System.out.print(elements);
System.out.print(" elems, ");
System.out.print(attributes);
System.out.print(" attrs, ");
System.out.print(ignorableWhitespace);
System.out.print(" spaces, ");
System.out.print(characters);
System.out.print(" chars)");
System.out.println();
} // printResults(String,long)
//
// Main
//
} // class DOMCount
class OnlyExt implements FilenameFilter{
String ext;
public OnlyExt(String ext){
this.ext="." + ext;
}
public boolean accept(File dir,String name){
return name.endsWith(ext) && (name.length()<8);
}
}