Package

Source Code of ProjectBuilder2

import javax.swing.JPanel;

import java.awt.Frame;
import java.awt.BorderLayout;

import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JMenu;
import javax.swing.JEditorPane;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JSplitPane;
import javax.swing.JTextArea;
import javax.swing.UIManager;

import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;

import javax.swing.JLabel;
import javax.swing.JTree;
import javax.swing.JScrollPane;
import javax.swing.JButton;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;

//import org.jdom.Document;
//import org.jdom.Element;
//import org.jdom.JDOMException;

import fbench.FBench;
import fbench.Library;
import fbench.LibraryElementView;
import fbench.dom.DOMTranslationModel;
import fbench.dom.StyleSheetSource;
import java.awt.Font;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.PrintStream;
import java.util.Hashtable;
import java.util.StringTokenizer;
import java.util.Vector;

public class ProjectBuilder2 extends JFrame implements Runnable {

  private static final long serialVersionUID = 1L;

  private JPanel jContentPane = null;

  private JMenuBar menuBar = null;

  private JMenu fileMenu = null;

  private JMenuItem exitMenuItem = null;

  private JEditorPane outputPane = null;

  private JSplitPane mainSplitPane = null;

  private JPanel leftPanel = null;

  private JComboBox xslComboBox = null;

  private JLabel xslComboLabel = null;

  private JScrollPane jScrollPane = null;

  private ProjectTreeModel fileTree = null;

  private JButton buildButton = null;

  private JCheckBox treeCellRenderer = null;

  private static String errorBuffer = null;

  private InputStream errStream = null;

  private Process compileProc = null;

  private boolean errorOccured = false;

  private static final String checkFilesPersistDataName = "ProjectBuilder2.checked.files";

  private Hashtable<String, Boolean> checkStore = new Hashtable<String, Boolean>();

  private Vector<File> projectFiles = new Vector<File>();

  private LibraryElementView currentElementView = null;
 
  private JCheckBox buildOnlyCheckBox = null;

  /**
   * This method initializes jScrollPane
   *
   * @return javax.swing.JScrollPane
   */
  private JScrollPane getJScrollPane() {
    if (jScrollPane == null) {
      jScrollPane = new JScrollPane();
      jScrollPane.setViewportView(getFileTree());
    }
    return jScrollPane;
  }

  /**
   * This method initializes fileTree
   *
   * @return javax.swing.JTree
   */
  private JTree getFileTree() {
    if (fileTree == null) {
      if (document == null)
        fileTree = new ProjectTreeModel(new DefaultMutableTreeNode(
            "Project"), this);
      else {
        String file = Library.getFilePath(document);
        file = file.substring(file.lastIndexOf(File.separatorChar) + 1);
        fileTree = new ProjectTreeModel(
            new DefaultMutableTreeNode(file), this);
      }
    }
    return fileTree;
  }
 
  private JCheckBox getBuildOnlyCheckBox(){
    if(buildOnlyCheckBox == null){
      buildOnlyCheckBox = new JCheckBox();
      buildOnlyCheckBox.setText("Generate source only");
      buildOnlyCheckBox.setToolTipText("If this box is checked the source code generated will not be compiled.");
      buildOnlyCheckBox.setSelected(false);
    }
    return buildOnlyCheckBox;
  }

  /**
   * This method initializes buildButton
   *
   * @return javax.swing.JButton
   */
  private JButton getBuildButton() {
    if (buildButton == null) {
      buildButton = new JButton();
      buildButton.setText("Build");
      buildButton.setFont(new Font("Dialog", Font.BOLD, 14));
      buildButton.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent e) {
          build();
        }
      });
    }
    return buildButton;
  }

  public static void main(String[] args) {
    try {
      UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
    } catch (Exception e) {
    }
    System.setProperty("user.dir", System.getProperty("user.dir")
        + "\\..\\..");
    String path = System.getProperty("user.dir")
        + "\\src\\fst1\\FST1_VIEW.sys";

    Library.setDocumentSource(new fbench.dom.DocumentSource() {

      public File getSource(String docname) {
        File src = FBench.getSource(new File("src"), docname);
        return src;
      }
    });

    org.w3c.dom.Document doc = Library.load(new File(path));
    Library.putDocument(path, doc);
    ProjectBuilder2 b = new ProjectBuilder2(null, doc);
    b.setVisible(true);
  }

  /**
   * @param owner
   */
  public ProjectBuilder2(Frame owner, org.w3c.dom.Document doc) {
    // super(owner);
    initialize();
    if (doc != null)
      fillTree(doc);
  }

  public ProjectBuilder2() {
    // super((Frame)null);
    initialize();
  }

  /**
   * This method initializes this
   *
   * @return void
   */
  private void initialize() {
    this.setLayout(null);
    this.setSize(690, 421);
    this.setTitle("Project Builder");
    this.setJMenuBar(getPJMenuBar());
    this.setContentPane(getJContentPane());
    this.addWindowListener(new java.awt.event.WindowAdapter() {
      public void windowClosing(java.awt.event.WindowEvent e) {
        ProjectBuilder2.this.dispose();
      }
    });
  }

  /**
   * This method initializes jContentPane
   *
   * @return javax.swing.JPanel
   */
  private JPanel getJContentPane() {
    if (jContentPane == null) {
      jContentPane = new JPanel();
      jContentPane.setLayout(new BorderLayout());
      jContentPane.add(getMainSplitPane(), BorderLayout.CENTER);
    }
    return jContentPane;
  }

  /**
   * This method initializes menuBar
   *
   * @return javax.swing.JMenuBar
   */
  private JMenuBar getPJMenuBar() {
    if (menuBar == null) {
      menuBar = new JMenuBar();
      menuBar.add(getFileMenu());
    }
    return menuBar;
  }

  /**
   * This method initializes fileMenu
   *
   * @return javax.swing.JMenu
   */
  private JMenu getFileMenu() {
    if (fileMenu == null) {
      fileMenu = new JMenu();
      fileMenu.setText("File");
      fileMenu.add(getExitMenuItem());
    }
    return fileMenu;
  }

  /**
   * This method initializes exitMenuItem
   *
   * @return javax.swing.JMenuItem
   */
  private JMenuItem getExitMenuItem() {
    if (exitMenuItem == null) {
      exitMenuItem = new JMenuItem("Exit");
      exitMenuItem.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent e) {
          ProjectBuilder2.this.setVisible(false);
          ProjectBuilder2.this.dispose();
        }
      });
    }
    return exitMenuItem;
  }

  /**
   * This method initializes outputPane
   *
   * @return javax.swing.JEditorPane
   */
  private JEditorPane getOutputPane() {
    if (outputPane == null) {
      outputPane = new JEditorPane();
      outputPane.setEditable(false);
    }
    return outputPane;
  }

  /**
   * This method initializes mainSplitPane
   *
   * @return javax.swing.JSplitPane
   */
  private JSplitPane getMainSplitPane() {
    if (mainSplitPane == null) {
      mainSplitPane = new JSplitPane();
      mainSplitPane.setDividerLocation(250);
      mainSplitPane.setContinuousLayout(true);
      mainSplitPane.setLeftComponent(getLeftPanel());
      mainSplitPane.setRightComponent(new JScrollPane(getOutputPane()));
    }
    return mainSplitPane;
  }

  /**
   * This method initializes leftPanel
   *
   * @return javax.swing.JPanel
   */
  private JPanel getLeftPanel() {
    if (leftPanel == null) {
      GridBagConstraints gridBagConstraints4 = new GridBagConstraints();
      gridBagConstraints4.gridx = 1;
      gridBagConstraints4.gridwidth = 3;
      gridBagConstraints4.gridy = 3;
      GridBagConstraints gridBagConstraints5 = new GridBagConstraints();
      gridBagConstraints5.gridx = 0;
      gridBagConstraints5.gridwidth = 1;
      gridBagConstraints5.gridy = 3;
      GridBagConstraints gridBagConstraints3 = new GridBagConstraints();
      gridBagConstraints3.fill = GridBagConstraints.BOTH;
      gridBagConstraints3.gridy = 1;
      gridBagConstraints3.weightx = 1.0;
      gridBagConstraints3.weighty = 1.0;
      gridBagConstraints3.gridwidth = 3;
      gridBagConstraints3.gridx = 0;
      GridBagConstraints gridBagConstraints1 = new GridBagConstraints();
      gridBagConstraints1.gridx = 0;
      gridBagConstraints1.gridy = 0;
      xslComboLabel = new JLabel();
      xslComboLabel.setText("Compiler:");
      GridBagConstraints gridBagConstraints = new GridBagConstraints();
      gridBagConstraints.fill = GridBagConstraints.VERTICAL;
      gridBagConstraints.gridy = 0;
      gridBagConstraints.weightx = 1.0;
      gridBagConstraints.gridx = 2;
      leftPanel = new JPanel();
      leftPanel.setLayout(new GridBagLayout());
      leftPanel.add(getXslComboBox(), gridBagConstraints);
      leftPanel.add(xslComboLabel, gridBagConstraints1);
      leftPanel.add(getJScrollPane(), gridBagConstraints3);
      leftPanel.add(getBuildButton(), gridBagConstraints4);
      leftPanel.add(getBuildOnlyCheckBox(), gridBagConstraints5);
    }
    return leftPanel;
  }

  /**
   * This method initializes xslComboBox
   *
   * @return javax.swing.JComboBox
   */
  private JComboBox getXslComboBox() {
    if (xslComboBox == null) {
      xslComboBox = new JComboBox();
      String[] sheets = StyleSheetSource.getAllSheets();
      for (String sheet : sheets)
        xslComboBox.addItem(sheet);
      xslComboBox.setSelectedItem("DOMtoJava.xsl");
    }
    return xslComboBox;
  }

  private org.w3c.dom.Document document = null;

  private void fillTree(org.w3c.dom.Document doc) {
    document = doc;
    fileTree = null;
    outputPane.setText("");
    jScrollPane.setViewportView(getFileTree());

    Runnable runnable = new Runnable() {
      public void run() {
        String filePath = Library.getFilePath(document);
        File file = new File(filePath);
        if(!file.exists()){
          filePath ="src/".replace('/', File.separatorChar) + filePath;
          file = new File(filePath);
        }
       
        if(!file.exists()){
          System.err.println("File not found: " + filePath);
          return;
        }
         
        DependencyBuilder depBuilder = new DependencyBuilder(filePath,
            true, null);
        try {
          org.jdom.Document depDoc = depBuilder.getDependencyTree();
          for (Object obj : depDoc.getRootElement().getChildren()) {
            addElement((org.jdom.Element) obj);
          }
        } catch (IOException e) {
          e.printStackTrace();
        } catch (org.jdom.JDOMException e) {
          e.printStackTrace();
        }
        fileTree.expandAll(true);
      }
    };
    new Thread(runnable).start();
  }

  private void addElement(org.jdom.Element elem) {
    String src = System.getProperty("user.dir")
        + "\\src\\".replace('\\', File.separatorChar);
    if (elem.getName().equalsIgnoreCase("fbtype")) {
      String path = elem.getAttributeValue("FileLocation");
      if (path != null) {
        File file = new File(path);

        String type = path.substring(path
            .lastIndexOf(File.separatorChar) + 1);
        if (type.contains("."))
          type = type.substring(0, type.lastIndexOf('.'));

        if (!type.startsWith("SUBL") && !type.startsWith("PUBL")
            && !type.startsWith("SUBSCRIBE")
            && !type.startsWith("PUBLISH")) {

          projectFiles.add(file);
          boolean checkState = !checkClass(path);
          if (checkStore.containsKey(path))
            checkState = checkStore.get(path);
          else
            checkStore.put(path, checkState);
          this.fileTree.addNode(path.replace(src, ""), file, false,
              checkState);
        }
      }
    }

    for (Object obj : elem.getChildren())
      addElement((org.jdom.Element) obj);
  }

  /**
   * Checks that the given fbt doesn't already exist in fbrt.jar.
   *
   * @param loc
   *            Path to fbt file
   * @return True = present in fbrt.jar
   */
  private boolean checkClass(String loc) {
    String cp = System.getProperty("java.class.path");
    StringTokenizer tokens = new StringTokenizer(cp, ";");

    String srcPath = System.getProperty("user.dir") + File.separatorChar
        + "src";
    String className = new String(loc);

    // Handle special cases
    if (className.contains(srcPath))
      className = className.substring(srcPath.length() + 1);
    className = className.substring(0, className.length() - 4);
    className = "fb.rt." + className.replace(File.separatorChar, '.');
    try {
      Class theClass = Class.forName(className);
      String url = theClass.getProtectionDomain().getCodeSource()
          .getLocation().toExternalForm();
      if (url.startsWith("file:/"))
        url = url.substring("file:/".length()).trim();

      String token = null;
      while (tokens.hasMoreTokens()) {
        token = tokens.nextToken().trim();
        token = token.replace(File.separator, "/");
        if (url.equals(token)) {
          return true;
        }
      }

      if (url.endsWith("fbrt.jar")) {
        return true;
      }
    } catch (Throwable e) {
    }

    return false;
  }

  private void build() {
    File[] build = fileTree.getSelectedFiles();
    outputPane.setText("");
    String xslSheet = (String) getXslComboBox().getSelectedItem();
    String languageName = StyleSheetSource.getLanguageForSheet(xslSheet);
    build = buildSource(build, xslSheet);
    if(!getBuildOnlyCheckBox().isSelected()){
      if (!this.errorOccured && languageName.equalsIgnoreCase("Java"))
        compileJava(build);
    }
  }

  private File[] buildSource(File[] files, String xslSheet) {
    errorOccured = false;
    String error = null;

    StringBuilder builder = new StringBuilder(outputPane.getText());
    builder.append("Building source code... (" + xslSheet + ")\n");
    Vector<File> toCompile = new Vector<File>();
    String languageName = StyleSheetSource.getLanguageForSheet(xslSheet);
    String fileExtension = StyleSheetSource
        .getFileExtensionForSheet(xslSheet);

    for (File fbFile : files) {
      System.out.println(fbFile);
      builder.append(fbFile + "\n");
      org.w3c.dom.Document doc = Library.load(fbFile);
      if (doc != null) {
        DOMTranslationModel translator = new DOMTranslationModel(doc,
            null, xslSheet, languageName);
        String source = translator.performTranslation();

        if (source != null) {
          source = FBench.removeHTML(source);

          String sourcePath = adjustPath(fbFile.getPath(),
              fileExtension);
          File file = new File(sourcePath);
          if (file.exists())
            file.delete();
          toCompile.add(file);

          FileOutputStream fo = null;
          try {
            file.getParentFile().mkdirs();
            file.createNewFile();
            fo = new FileOutputStream(file);
            PrintStream ps = new PrintStream(fo);
            ps.println(source);
            fo.close();
          } catch (FileNotFoundException e) {
            e.printStackTrace();
            error = "File error: " + sourcePath;
          } catch (IOException e) {
            e.printStackTrace();
            error = "File error: " + sourcePath;
          }

          continue;
        } else
          error = "Translation to source failed.";

        errorOccured = true;
        System.err.println(error);
        builder.append(error + "\n");
        break;

      } else
        error = "File error: " + fbFile;

      System.err.println(error);
      errorOccured = true;
      break;
    }
    outputPane.setText(builder.toString());

    File[] array = new File[toCompile.size()];
    return toCompile.toArray(array);
  }

  private boolean compileJava(File[] files) {
    boolean errorsOccured = false;

    StringBuilder sb = new StringBuilder();
    for (File sourceFile : files) {
      if (sourceFile != null)
        sb.append("\"" + sourceFile + "\"\n");
    }

    String sourceFiles = sb.toString();
    sb = new StringBuilder(outputPane.getText());
    sb.append("\nCompiling Java source...\n");
    sb.append(sourceFiles.replace("\"", ""));
   
    String classpath = FBench.theBench.getProps().getProperty("classpath");
    if(classpath == null)
      classpath = System.getProperty("java.class.path");

    try {
      errorBuffer = null;
      String compileCmd = FBench
          .adjustCommand(FBench.theBench.getProps().getProperty(
              "javac")
              + " -classpath "
              // + "\"" + "./rt;./fbrt.jar;" + "\"" + " ");
              + "\"" + "./" + FBench.getRTPathRoot() + ";./fbrt.jar;" //vv
              //+ System.getProperty("java.class.path")
              + FBench.theBench.getProps().getProperty("classpath")
              + "\"" + " ");
     
      String javacpath = FBench.adjustCommand(FBench.theBench.getProps().getProperty("javac"));

      String javaDir = javacpath.substring(0, javacpath.indexOf("javac"));
     
      //System.out.println("1111 "+javacpath.substring(javacpath.indexOf("-classpath ")));
//      String env = " "
//          + javacpath.substring(javacpath.indexOf("-classpath "))
//          + " -classpath "
////          + "\"" + "./rt;./fbrt.jar;"
//          + "\"" + System.getProperty("java.class.path")
//          + "\"" + " " +
//          sourceFiles;
     
      System.out.println("\n\n" + compileCmd + sourceFiles + "\n\n");
      //compileProc = Runtime.getRuntime().exec(compileCmd + sourceFiles);
      compileProc = Runtime.getRuntime().exec("javac"+env, null, new File(javaDir));
      //compileProc = Runtime.getRuntime().exec("javac"+env, null, new File(javaDir));
      errStream = compileProc.getErrorStream();
      (new Thread(this)).start();
      compileProc.waitFor();

    } catch (IOException e) {
      e.printStackTrace();
      errorsOccured = true;
    } catch (InterruptedException e) {
      System.err.println("Compile interrupted.");
      sb.append("Compile interrupted.\n");
      errorsOccured = true;
    }

    if (errorBuffer != null && errorBuffer.length() > 0) {
      sb.append(errorBuffer + "\n");
      System.err.println(sb.toString());
      errorsOccured = true;
    }

    if (!errorsOccured)
      sb.append("Build completed successfully.");
    else
      sb.append("Build completed with errors.");

    outputPane.setText(sb.toString());

    return errorsOccured;
  }

  public void run() {
    log(errStream, getOutputPane(), false);
  }

  public void showDialog(Vector args) {
    FBench fBench = ((FBench) args.get(1));
    this.currentElementView = fBench.getSelectedView();
    this.checkStore = (Hashtable<String, Boolean>) currentElementView
        .getOpaqueData(checkFilesPersistDataName);
    if (this.checkStore == null) {
      checkStore = new Hashtable<String, Boolean>();
      currentElementView.putOpaqueData(checkFilesPersistDataName,
          checkStore);
    }
    super.setVisible(true);
    fillTree(fBench.getSelectedDoc());
  }

  public static void log(InputStream strm, JEditorPane pane, boolean lnos) {
    try {
      LineNumberReader lrdr = new LineNumberReader(new InputStreamReader(
          strm));
      for (String line = lrdr.readLine(); line != null; line = lrdr
          .readLine()) {
        if (lnos)
          errorBuffer += lrdr.getLineNumber() + " ";
        errorBuffer += line + '\n';
      }

      lrdr.close();
    } catch (IOException ioexception) {
    }
  }

  private static String adjustPath(String path, String ex) {
    String rtPath = FBench.theBench.getProps().getProperty("rtPath");
    if(rtPath == null)
      rtPath = "rt\\fb\\rt".replace('\\', File.separatorChar);
    String result = path.replace("src", rtPath);
    result = result.substring(0, result.length() - 4) + ex;
    return result;

  }

  public void handleNodeSelected(CheckNode node) {
    String path = node.toString();
    for (String key : checkStore.keySet()) {
      if (key.substring(key.lastIndexOf(File.separatorChar) + 1)
          .equalsIgnoreCase(path)) {
        checkStore.put(key, node.isSelected());
        break;
      }
    }
  }
} // @jve:decl-index=0:visual-constraint="10,10"
TOP

Related Classes of ProjectBuilder2

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.