Package framework.utils

Source Code of framework.utils.ConfigAbstract

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package framework.utils;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.JDomDriver;
import com.thoughtworks.xstream.io.xml.JDomReader;
import java.awt.GraphicsEnvironment;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.io.Writer;
import java.nio.channels.FileLock;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

/**
*
* @author finder
*/
public abstract class ConfigAbstract {
  static private RandomAccessFile      lockFile;
  static private FileLock          lockFileLockObject;
  static private PrintStream        logStream;
 
  static private ConfigAbstract      config;
  private int                version = 101;
  private File              lastOpenDialogPath;
 
  public boolean lockInstance(){
    if (lockFile != null){
      return true;
    }
    try {
      File        lockFileName = new File(getProgramHome(), "lock.tmp");
      lockFile = new RandomAccessFile(lockFileName, "rwd");
      lockFileLockObject = lockFile.getChannel().tryLock();
      if (lockFileLockObject == null){
        lockFile.close();
        lockFile = null;
        if (!GraphicsEnvironment.isHeadless()){
          JOptionPane.showMessageDialog(null,
              "Приложение " + getProgramNormalName() + " уже запущено!",
              "Повторный запуск", JOptionPane.ERROR_MESSAGE);
        }
        return false;
      }
      lockFile.write(1);
    }
    catch (IOException ex) {
      if (lockFile != null){
        try {
          lockFile.close();
        }
        catch (IOException ex1) {
          ex1.printStackTrace();
        }
        lockFile = null;
      }
      ex.printStackTrace();
    }
    return true;
  }

  public void unlockInstance(){
    try {
      if (lockFileLockObject != null){
          lockFileLockObject.release();
          lockFileLockObject = null;
      }
      if (lockFile != null){
        lockFile.close();
        lockFile = null;
      }
    }
    catch (IOException ex) {
      ex.printStackTrace();
    }
  }
 
  protected  ConfigAbstract() {
  }
 
  /**
   * В списке возвращяемых класоов должен быть как минимум класс самого конфига.
   * @return
   */
  protected abstract Class[] getClassList();

  protected XStream createSerializer(){
    XStream        target = new XStream(new JDomDriver());
    target.processAnnotations(new Class[]{ConfigAbstract.class});
    Class[]        arr = getClassList();
    boolean        found = false;
    for (Class clazz: arr){
      if (this.getClass().equals(clazz)){
        found = true;
        break;
      }
    }
    if (!found){
      throw new IllegalArgumentException("Класс конфига не перечислен в списке доступных для загрузки класоов");
    }
    target.processAnnotations(arr);
    return target;
  }
 
  public <T> void toFile(T object, Writer file) throws Exception{
    XStream      s = createSerializer();
    s.toXML(object, file);
  }
 
  @SuppressWarnings("unchecked")
  public <T> T fromFile(T object, Reader file) throws Exception{
    XStream      s = createSerializer();
    return (T) s.fromXML(file, object);
  }

  @SuppressWarnings("unchecked")
  public <T> T fromXml(T object, Element el) throws Exception{
    XStream      s = createSerializer();
    return (T) s.unmarshal(new JDomReader(el), object);
  }

  public String getEnterpriseName(){
    return "Infotechservice";
  }

  public abstract String getProgramNormalName();
  public abstract String getProgramSampleName();

  protected boolean isAppdirGlobal(){
    return false;
  }
 
  public String getProgramHome(){   
    String          systemName = System.getProperty("os.name");
    if (systemName.toLowerCase().startsWith("window")) {
      if (isAppdirGlobal()){
        //C:\Documents and Settings\All User\Application Data\Infotechservice\Intel Clinic\
        String          home = System.getenv("ALLUSERSPROFILE");
        return home + File.separator + "Application Data" + File.separator
            + getEnterpriseName() + File.separator + getProgramNormalName();
      }
      else{
        //C:\Documents and Settings\<user name>\Application Data\Infotechservice\Intel Clinic\
        return System.getenv("APPDATA") + File.separator
            + getEnterpriseName() + File.separator + getProgramNormalName();
      }
    }
    else {
      if (isAppdirGlobal()){
        //\var\data\infotechservice\intelclinic\
        return File.separator + "var" + File.separator + "data" + File.separator
            + getEnterpriseName().toLowerCase()
            + File.separator + getProgramSampleName();
      }
      else{
        //\home\<user name>\.infotechservice\intelclinic\
        String          home = System.getProperty("user.home");
        return home + File.separator + "." + getEnterpriseName().toLowerCase()
              + File.separator + getProgramSampleName();       
      }
    }     
  };

  public void storeLogToConfigFolder(){
    try {
      OutputStream      os = new FileOutputStream(new File(getProgramHome(), "applog.txt"), true);
      logStream = new PrintStream(os, true, "UTF8");
      System.err.close();
      System.out.close();
      System.in.close();
      System.setErr(logStream);
      System.setOut(logStream);
    }
    catch (IOException ex) {
      ex.printStackTrace();
    }
  }

  protected File getConfigFile(){
    String        configPatgh = getProgramHome() + File.separator + "config.xml";
    File        cfile = new File(configPatgh);
    return cfile.getAbsoluteFile();
  }

  protected abstract void load();

  protected void loadInstance() throws FileNotFoundException, JDOMException, IOException, Exception{
    config = this;
    File          file = getConfigFile();
    if (file.exists()){
      FileInputStream        stream = null;
      InputStreamReader      reader = null;
      try {
        stream = new FileInputStream(file);
        reader = new InputStreamReader(stream, "UTF-8");
        SAXBuilder          builder = new SAXBuilder();
        Document          confXml = builder.build(reader);
        Element            root = confXml.getRootElement();
        if (root != null){
          String      vers= root.getChildTextTrim("version");
          if (String.valueOf(version).equals(vers)){
            config = fromXml(this, root);
            return;
          }
          else{
            System.out.println("Config version not equal! Create new config.");
          }
        }
        else{
          System.out.println("Config load error! Create new config.");
        }
      }/* catch (FileNotFoundException ex) {
        // Файл уже был проверен на существование, случилось нечто странное
        MessageBox.showExceptionOnly(ex);
      } catch (Exception ex) {
        MessageBox.showExceptionAndHalt(new ClipsException("Ошибка при чтении настрек программы", ex));
      }*/
      finally{
        if (reader != null) {
          reader.close();
        }
        if (stream != null) {
          stream.close();
        }
      }
    }
    else{
      System.out.println("Config file not fond! Create new config.");
    }
    config.save();
  }

  public abstract void save();

  public void saveInstance() throws IOException, Exception{
    File          file = getConfigFile();
    FileOutputStream    stream = null;
    OutputStreamWriter    writer = null;
    try {
      if (!file.exists()) {
        File    parents = file.getParentFile();
        if (parents != null) {
          parents.mkdirs();
        }
        file.createNewFile();
      }
      stream = new FileOutputStream(file, false);
      writer = new OutputStreamWriter(stream, "UTF-8");
      toFile(this, writer);
    }
  /*  catch (IOException ex) {
      MessageBox.showException(new ClipsException("Ошибка при сохранении настрек программы", ex));
    }
    catch (Exception ex) {
      MessageBox.showException(new ClipsException("Ошибка при сохранении настрек программы", ex));
    } */
    finally {
      if (writer != null){
        writer.close();
      }
      if (stream != null){
        stream.close();
      }
    }
  }
 
  public static ConfigAbstract getInstance() {
    if (config == null) {
      throw new IllegalStateException("Обьект конфигурации не существует.");
    }
    return config;
  }

  public static boolean isLoaded(){
    return config != null;
  }
 
  public File getLastOpenDialogPath() {
    if (lastOpenDialogPath == null){
      return new File(System.getProperty("user.home"));
    }
    return lastOpenDialogPath;
  }

  public void setLastOpenDialogPath(File lastOpenDialogPath) {
    this.lastOpenDialogPath = lastOpenDialogPath.getAbsoluteFile();
    save();
  }

  public void dispose(){
    save();
    if (logStream != null){
      logStream.close();
    }
    unlockInstance();
    config = null;
  }
}
TOP

Related Classes of framework.utils.ConfigAbstract

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.