Package com.simoncat.beans

Source Code of com.simoncat.beans.OnlyDir

package com.simoncat.beans;


import com.simoncat.vo.Event;
import com.simoncat.vo.Server;
import java.util.Collection;

import java.io.*;

import java.util.Properties;
import javax.servlet.*;
import javax.servlet.http.*;


import com.simoncat.beans.XMLServers;


//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;



import com.thoughtworks.xstream.persistence.PersistenceStrategy;
import com.thoughtworks.xstream.persistence.FilePersistenceStrategy;

import java.util.Iterator;

import java.util.Vector;
import java.util.Date;

import java.text.SimpleDateFormat;

public class XMLEvents
{
   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>";
  
   protected SimpleDateFormat dfMySQLDate = new SimpleDateFormat("yyyy-MM-dd");
   protected SimpleDateFormat dfDateField = new SimpleDateFormat("M/d/yy");
  
   public boolean addEvent(Event event,String path,String serName,String date_dir){
       try{
         //cut just path
      String ruta = path.substring(0,path.lastIndexOf("/"))+"/"+serName;
      if(date_dir!=null)
        ruta=ruta+"/"+date_dir;
      //verify if exis the month's folder
      boolean exists = (new File(ruta)).exists();
        if (!exists) {
          new File(ruta).mkdirs();
            //System.out.println("created:"+ruta);
        }

      //System.out.println("RUTA:"+ruta+"/"+serName);
      PersistenceStrategy strategy = new FilePersistenceStrategy(new File(ruta));
      // creates the list:
      List list = new XmlArrayList(strategy);
      list.add(event);
      return true;
    }
    catch(Exception e){
      e.printStackTrace();
      return false;
    }
   }
  
   public Event getEventByID(String id,String path,String serName){
       PersistenceStrategy strategy = new FilePersistenceStrategy(new File(path+"/"+serName));
    // creates the list:
    List list = new XmlArrayList(strategy);
    for(Iterator it = list.iterator(); it.hasNext(); ) {
      Event event = (Event) it.next();
      if(event.getId().equals(id)) {
        return event;
      }
    }
    return null;
   }
  
   public Event[] loadEventsServerByRange(String startDate,String endDate,String path,String serName){
      
    // creates the list of folder and subforlders events
    //System.out.println("RUUUTTTTAAAA---->"+path);
    File file =new File(path+"/"+serName);
    if(file.exists()){
      //test subdirectories
      OnlyDir onlyDir = new OnlyDir();
      String[] listDirs = file.list(onlyDir);
      Vector vector =new Vector();
      for(int i = 0;i<listDirs.length;i++){
        try{
          PersistenceStrategy strategy = new FilePersistenceStrategy(new File(path+"/"+serName+"/"+listDirs[i]));
          List list = new XmlArrayList(strategy);
       
          for(Iterator it = list.iterator(); it.hasNext(); ) {
           
            Event event = (Event) it.next();
            //Date dateEvent =  new Date(event.getDate());
            //dfMySQLDate.format(dfDateField.parse(request.getParameter("EventDate")));
             //String s = dfMySQLDate.format(dfDateField.parse(startDate));
            //Date start = new Date("08/31/2008");
            //String e=dfMySQLDate.format(dfDateField.parse(endDate))
            //Date end = new Date("10/04/2008");
            //Date end = new Date(dfMySQLDate.format(endDate));
            //if(dateEvent.equals(start) || dateEvent.equals(end) || (dateEvent.after(start) && dateEvent.before(end))) {
              vector.add(event);
             
            //}
           
          }
         
        }
        catch(Exception e){
          e.printStackTrace();
        }
      }
      if(vector.size()>0){
        Event[] arre = new Event[vector.size()];
        vector.toArray(arre);
        return arre;
      }
      else{
        return null
      }
    }
    else{
      return null;
    }
   
   }
     
   public Event[] getAllEvents(String path,String serName){
       PersistenceStrategy strategy = new FilePersistenceStrategy(new File(path+"/"+serName));
    // creates the list:
    List list = new XmlArrayList(strategy);
    if(list.size()>0){
      Event[] array = (Event[])list.toArray(new Event[list.size()]);
      return array;
    }
    else
      return null;
   }
  
   public boolean delEvent(String id,String path,String serName){
       PersistenceStrategy strategy = new FilePersistenceStrategy(new File(path+"/"+serName));
    // creates the list:
    List list = new XmlArrayList(strategy);
    for(Iterator it = list.iterator(); it.hasNext(); ) {
      Event event = (Event) it.next();
      if(event.getId().equals(id)) {
        it.remove();
        return true;
      }
    }
    return false;
   }
  
   public boolean updEvent(String id,Event newEvent,String path,String serName){
       PersistenceStrategy strategy = new FilePersistenceStrategy(new File(path+"/"+serName));
    // creates the list:
    List list = new XmlArrayList(strategy);
    for(Iterator it = list.iterator(); it.hasNext(); ) {
      Event event = (Event) it.next();
      if(event.getId().equals(id)) {
        it.remove();
        list.add(newEvent);
        return true;
      }
    }
    return false;
   }
  
  

public boolean writeToXmlSingle(Event event,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(event)
      } catch (Exception e)
      {
         e.printStackTrace();
   r=false;
      }
  return r; 
   }
public boolean writeToXml(Event event,String path,ServletContext sc)
   {
      boolean r=true;
      try
      {
   //CREAR xml Single con datos del servidor
   writeToXmlSingle(event,path,sc);
      } catch (Exception e)
      {
         e.printStackTrace();
   r=false;
      }
      return r; 
   }
  
    public Server loadEventsServerByName(String name,String path){
  //////Server[] servers = readXmls(path);
  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[] readXml(String path)
   {
      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.Event.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);
     //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');
      }
    }
    String xml=buf.toString();
    try{
      Server ser = (Server)xstream.fromXML(xml);       
      ser.setFilePath(path1  + "WEB-INF" + c + s[i]);
      serverList.add(ser);
    }
    catch(Exception e){
      System.out.println("PROBLEMA LEYENDO EL XML");
    }
  }
   }
      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);
      }
      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 OnlyDir implements FilenameFilter{
 
  public boolean accept(File dir,String name){
    return (new File(dir+"/"+name)).isDirectory();
  }
}
TOP

Related Classes of com.simoncat.beans.OnlyDir

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.