Package org.jconfig.handler

Source Code of org.jconfig.handler.SimpleScriptHandler

/*
* ScriptHandler.java
*
* Created on 17. Dezember 2003, 21:52
*/

package org.jconfig.handler;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.Properties;
import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Vector;

import org.jconfig.Category;
import org.jconfig.Configuration;
import org.jconfig.ConfigurationManagerException;
import org.jconfig.DefaultCategory;
import org.jconfig.ExtensibleConfiguration;
import org.jconfig.VariableManager;
import org.jconfig.error.ErrorReporter;
import org.jconfig.parser.ConfigurationParser;
import org.jconfig.utils.ResourceLocator;
/**
* The SimpleScriptHandler will read in a text file. The file should
* be anntotated where every line containing properties should start
* with either spaces or tabs. Every other line is considered as
* category.
* <br/>
* Example:
* <pre>
* basic:
*   prop1: hello
*   prop2: world
*  
* more:
*   simple_one: 1
*</pre>
*
* @author Andreas Mecky
* @author Terry Dye
*/
public class SimpleScriptHandler extends AbstractHandler {

  private String fileName;
    /**
     * Constructs a SimpleScriptHandler. Nothing special happens during construction.
     */
    public SimpleScriptHandler() {
    }

    /**
     * This method loads all files that are found ending with "_config.script".
     *
     * Example: my_config.script
     *
     * @param configurationName The name of the file to be found.
     * @return The configured/loaded Configuration
     * @throws ConfigurationManagerException thrown if the "_config.script" isn't found
     */
    public Configuration load(String configurationName) throws ConfigurationManagerException {
        fileName = configurationName+"_config.script";
    try {
      ResourceLocator locator = new ResourceLocator(fileName);
      InputStream is = locator.findResource(fileName);
      return load(configurationName,is);
    }
    catch (IOException e) {
      ErrorReporter.getErrorHandler().reportError("Error while trying to read file",e);
            throw new ConfigurationManagerException("Error while trying to read file");
    }
    }
 
  public Configuration load(String configurationName,String fileName) throws ConfigurationManagerException {
    try {
      InputStream is = new FileInputStream(fileName);
      return load(configurationName,is);
    }
    catch (Exception e) {
      ErrorReporter.getErrorHandler().reportError("Error while trying to read file",e);
            throw new ConfigurationManagerException("Error while trying to read file");
    }
  }
 
  public Configuration load(String configurationName,InputStream is) throws ConfigurationManagerException {
        try {
            BufferedReader nis = new BufferedReader(new InputStreamReader(is));           
            String line;
            Vector content = new Vector();
            while ((line=nis.readLine()) != null ) {
                content.add(line);
            }
            nis.close();
            boolean addVar = false;
            Configuration cfg = new ExtensibleConfiguration(configurationName);
            String currentCategoryName = null;
            for ( int i = 0; i < content.size();i++) {
                String tmp = (String)content.get(i);
                if ( tmp != null && tmp.length() > 0 && !tmp.startsWith("#") ) {
                  if ( tmp.startsWith(" ") || tmp.startsWith("\t") ) {
                    if ( tmp.indexOf(":") != -1 ) {
                      String left = tmp.substring(0,tmp.indexOf(":"));
                        left = left.trim();
                        String right = tmp.substring(tmp.indexOf(":")+1);
                        right = right.trim();          
                        if ( addVar ) {
                          cfg.setVariable(left,right);
                        }
                        else {
                          cfg.setProperty(left,right,currentCategoryName);
                        }
                    }
                  }
                  else {
                    String name = tmp;
            name = name.trim();
                      if ( name.endsWith(":")) {
                        name = name.substring(0,name.length()-1);
                      }
                      if ( name.equalsIgnoreCase("variables")) {
                        addVar = true;
                      }
                      else {
                        addVar = false;
                        String extend = null;
                        if ( name.startsWith("extends")) {
                          int pos = name.indexOf(":");
                          if ( pos != -1 ) {
                            cfg.setBaseConfiguration(name.substring(pos+1).trim());
                          }
                        }
                        else {
                          if ( tmp.indexOf(" extends ") != -1 ) {
                              extend = name.substring(name.indexOf(" extends ")+9);
                              extend = extend.trim();
                              name = name.substring(0,name.indexOf(" extends "));                           
                          }
                          Category ec = new DefaultCategory(name);
                          if ( extend != null ) {
                              ec.setExtendsCategory(extend);
                          }
                          cfg.setCategory(ec);
                          currentCategoryName = name;
                        }
                      }
                  }
                }
            }
            return cfg;
        }
        catch (IOException e) {
          ErrorReporter.getErrorHandler().reportError("Error while trying to read file",e);
            throw new ConfigurationManagerException("Error while trying to read file");
        }       
    }

    /**
     * This method is not yet implemented!
     * @param configuration
     * @throws ConfigurationManagerException
     */
    public void store(Configuration configuration) throws ConfigurationManagerException {
    StringBuffer buffer = new StringBuffer();
    if ( configuration.getBaseConfiguration() != null ) {
      buffer.append("extends : ");
      buffer.append(configuration.getBaseConfiguration());
      buffer.append("\n\n");
    }
    VariableManager vm = VariableManager.getInstance();
        Iterator it = vm.getVariables(configuration.getConfigName()).keySet().iterator();
        boolean vars = false;
        if (it.hasNext()) {
            buffer.append("variables:\n");
            vars = true;
        }
        while (it.hasNext()) {
            String varName = (String) it.next();
            String varText = (String) vm.getVariables(configuration.getConfigName()).get(varName);
      buffer.append("\t");
            buffer.append(varName);
            buffer.append(" : ");
            buffer.append(varText);
            buffer.append("\n");
        }
        if (vars) {
            buffer.append("\n");
        }
    String[] cats = configuration.getCategoryNames();
        for (int i = 0; i < cats.length; i++) {
            buffer.append(cats[i]);
            buffer.append(": \n");           
            SortedMap sm = getSortedProperties(cats[i],configuration);
            if (sm != null) {
                Iterator nit = sm.keySet().iterator();
                while (nit.hasNext()) {
                    String name = (String) nit.next();
                    String value = (String)sm.get(name);
                    buffer.append("\t");
                    buffer.append(name);
                    buffer.append(" : ");
                    buffer.append(value);
                    buffer.append("\n");
                }
                buffer.append("\n");
            }
        }
    try {
      FileWriter writer = new FileWriter(getFile());
      writer.write(buffer.toString());
      writer.close();
    }
    catch (Exception e) {
      throw new ConfigurationManagerException("Error while saving script:"+e.getMessage());
    }
    }
 
  protected SortedMap getSortedProperties(String categoryName,Configuration configuration) {
        Properties props = configuration.getProperties(categoryName);
        SortedMap sm = new TreeMap();
        if (props != null) {
            Iterator nit = props.keySet().iterator();
            while (nit.hasNext()) {
                String name = (String) nit.next();
                String value = props.getProperty(name);
                sm.put(name,value);
            }
            return sm;
        }
        return null;
    }

  public File getFile() {
    try {
      return new ResourceLocator(fileName).getFile();
    } catch (IOException e) {
      ErrorReporter.getErrorHandler().reportError("File not found",e);
      return null;
    }
  }
 
  public Configuration load(String configurationName, ConfigurationParser parser) throws ConfigurationManagerException {
    throw new ConfigurationManagerException("Using a specific parser with this handler is not supported");
  }
   
}
TOP

Related Classes of org.jconfig.handler.SimpleScriptHandler

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.