Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. /
 
 
 package org.apache.cayenne.modeler.dialog.db;
 
 import java.io.File;
 import java.util.List;
 
 
 import  org.apache.cayenne.access.DataDomain;
 import  org.apache.cayenne.access.DataNode;
 import  org.apache.cayenne.dba.DbAdapter;
 import  org.apache.cayenne.map.DataMap;
 import  org.apache.cayenne.map.DbAttribute;
 import  org.apache.cayenne.map.DbEntity;
 import  org.apache.cayenne.map.DbRelationship;
 import  org.apache.cayenne.map.ObjAttribute;
 import  org.apache.cayenne.map.ObjEntity;
 import  org.apache.cayenne.map.ObjRelationship;
 import  org.apache.cayenne.map.event.EntityEvent;
 import  org.apache.cayenne.map.event.MapEvent;
 import  org.apache.cayenne.merge.AbstractToDbToken;
 import  org.apache.cayenne.merge.DbMerger;
 import  org.apache.cayenne.merge.ExecutingMergerContext;
 import  org.apache.cayenne.merge.MergeDirection;
 import  org.apache.cayenne.merge.MergerContext;
 import  org.apache.cayenne.merge.MergerToken;
 import  org.apache.cayenne.merge.ModelMergeDelegate;
 import  org.apache.cayenne.project.Project;
 import  org.apache.cayenne.validation.ValidationResult;

 
 public class MergerOptions extends CayenneController {
 
     protected MergerOptionsView view;
     // protected ObjectBinding[] optionBindings;
     protected ObjectBinding sqlBinding;
 
     protected DBConnectionInfo connectionInfo;
     protected DataMap dataMap;
     protected DbAdapter adapter;
     protected String textForSQL;
 
     protected DbMerger merger;
 
     public MergerOptions(ProjectController parentString title,
             DBConnectionInfo connectionInfo, DataMap dataMap) {
         super(parent);
 
         this. = dataMap;
         this. = new MergerTokenSelectorController(parent);
         this. = new MergerOptionsView(.getView());
         this. = connectionInfo;
         /*
          * TODO:? this.generatorDefaults = (DBGeneratorDefaults) parent
          * .getPreferenceDomainForProject() .getDetail("DbGenerator",
          * DBGeneratorDefaults.class, true);
          */
         this..setTitle(title);
         initController();
        // tables.updateTables(dataMap);
        prepareMigrator();
        // generatorDefaults.configureGenerator(generator);
        createSQL();
        refreshView();
    }
    public Component getView() {
        return ;
    }
    /*
     * public DBGeneratorDefaults getGeneratorDefaults() { return generatorDefaults; }
     */
    public String getTextForSQL() {
        return ;
    }
    protected void initController() {
        BindingBuilder builder = new BindingBuilder(
                getApplication().getBindingFactory(),
                this);
         = builder.bindToTextArea(.getSql(), "textForSQL");
        /*
         * optionBindings = new ObjectBinding[5]; optionBindings[0] =
         * builder.bindToStateChangeAndAction(view.getCreateFK(),
         * "generatorDefaults.createFK", "refreshSQLAction()"); optionBindings[1] =
         * builder.bindToStateChangeAndAction(view.getCreatePK(),
         * "generatorDefaults.createPK", "refreshSQLAction()"); optionBindings[2] =
         * builder.bindToStateChangeAndAction(view.getCreateTables(),
         * "generatorDefaults.createTables", "refreshSQLAction()"); optionBindings[3] =
         * builder.bindToStateChangeAndAction(view.getDropPK(),
         * "generatorDefaults.dropPK", "refreshSQLAction()"); optionBindings[4] =
         * builder.bindToStateChangeAndAction(view.getDropTables(),
         * "generatorDefaults.dropTables", "refreshSQLAction()");
         */
        builder.bindToAction(.getGenerateButton(), "generateSchemaAction()");
        builder.bindToAction(.getSaveSqlButton(), "storeSQLAction()");
        builder.bindToAction(.getCancelButton(), "closeAction()");
        // refresh SQL if different tables were selected
        .getTabs().addChangeListener(new ChangeListener() {
            public void stateChanged(ChangeEvent e) {
                if (.getTabs().getSelectedIndex() == 1) {
                    // this assumes that some tables where checked/unchecked... not very
                    // efficient
                    refreshGeneratorAction();
                }
            }
        });
    }

    
check database and create the List of MergerTokens
    protected void prepareMigrator() {
        try {
             = .makeAdapter(getApplication()
                    .getClassLoadingService());
            .setMergerFactory(.mergerFactory());
             = new DbMerger();
            List<MergerToken> mergerTokens = .createMergeTokens(
                    .makeDataSource(getApplication().getClassLoadingService()), );
            .setTokens(mergerTokens);
        }
        catch (Exception ex) {
            reportError("Error loading adapter"ex);
        }
    }

    
Returns SQL statements generated for selected schema generation options.
    protected void createSQL() {
        // convert them to string representation for display
        final StringBuffer buf = new StringBuffer();
        Iterator<MergerToken> it = .getSelectedTokens().iterator();
        String batchTerminator = .getBatchTerminator();
        final String lineEnd = (batchTerminator != null) ? "\n"
                + batchTerminator
                + "\n\n" : "\n\n";
        
        while (it.hasNext()) {
            MergerToken token = it.next();
            if (token instanceof AbstractToDbToken) {
                AbstractToDbToken tdb = (AbstractToDbToken) token;
                for (String sql : tdb.createSql()) {
                    buf.append(sql);
                    buf.append(lineEnd);
                }
            }
        }
         = buf.toString();
    }
    protected void refreshView() {
        /*
         * for (int i = 0; i < optionBindings.length; i++) {
         * optionBindings[i].updateView(); }
         */
        .updateView();
    }
    // ===============
    // Actions
    // ===============

    
Starts options dialog.
    public void startupAction() {
        .pack();
        .setModal(true);
        makeCloseableOnEscape();
        centerView();
        .setVisible(true);
    }
    public void refreshGeneratorAction() {
        // prepareMigrator();
        refreshSQLAction();
    }

    
Updates a text area showing generated SQL.
    public void refreshSQLAction() {
        // sync generator with defaults, make SQL, then sync the view...
        // generatorDefaults.configureGenerator(generator);
        createSQL();
        .updateView();
    }

    
Performs configured schema operations via DbGenerator.
    public void generateSchemaAction() {
        refreshGeneratorAction();
        // sanity check...
        List<MergerToken> tokensToMigrate = .getSelectedTokens();
        if (tokensToMigrate.isEmpty()) {
            JOptionPane.showMessageDialog(getView(), "Nothing to migrate.");
            return;
        }
        
        final ProjectController c = getProjectController();
        
        final Object src = this;
        final DataDomain domain = getProjectController().getCurrentDataDomain();
        final DataNode node = getProjectController().getCurrentDataNode();
        final ModelMergeDelegate delegate = new ModelMergeDelegate (){
            public void dbAttributeAdded(DbAttribute att) {
                if (c.getCurrentDbEntity() == att.getEntity()) {
                    c.fireDbAttributeDisplayEvent(new AttributeDisplayEvent(srcattatt.getEntity(), domain));
                }
            }
            public void dbAttributeModified(DbAttribute att) {
                if (c.getCurrentDbEntity() == att.getEntity()) {
                    c.fireDbAttributeDisplayEvent(new AttributeDisplayEvent(srcattatt.getEntity(), domain));
                }
            }
            public void dbAttributeRemoved(DbAttribute att) {
                if (c.getCurrentDbEntity() == att.getEntity()) {
                    c.fireDbAttributeDisplayEvent(new AttributeDisplayEvent(srcattatt.getEntity(), domain));
                }
            }
            public void dbEntityAdded(DbEntity ent) {
                c.fireDbEntityEvent(new EntityEvent(srcent, MapEvent.ADD));
                c.fireDbEntityDisplayEvent(new EntityDisplayEvent(srcentnodedomain));
            }
            public void dbEntityRemoved(DbEntity ent) {
                c.fireDbEntityEvent(new EntityEvent(srcent, MapEvent.REMOVE));
                c.fireDbEntityDisplayEvent(new EntityDisplayEvent(srcentnodedomain));
            }
            public void dbRelationshipAdded(DbRelationship rel) {
                if (c.getCurrentDbEntity() == rel.getSourceEntity()) {
                    c.fireDbRelationshipDisplayEvent(new RelationshipDisplayEvent(srcrelrel.getSourceEntity(), domain));
                }
            }
            public void dbRelationshipRemoved(DbRelationship rel) {
                if (c.getCurrentDbEntity() == rel.getSourceEntity()) {
                    c.fireDbRelationshipDisplayEvent(new RelationshipDisplayEvent(srcrelrel.getSourceEntity(), domain));
                }
            }
            public void objAttributeAdded(ObjAttribute att) {
                if (c.getCurrentObjEntity() == att.getEntity()) {
                    c.fireObjAttributeDisplayEvent(new AttributeDisplayEvent(srcattatt.getEntity(), domain));
                }
            }
            public void objAttributeModified(ObjAttribute att) {
                if (c.getCurrentObjEntity() == att.getEntity()) {
                    c.fireObjAttributeDisplayEvent(new AttributeDisplayEvent(srcattatt.getEntity(), domain));
                }
            }
            public void objAttributeRemoved(ObjAttribute att) {
                if (c.getCurrentObjEntity() == att.getEntity()) {
                    c.fireObjAttributeDisplayEvent(new AttributeDisplayEvent(srcattatt.getEntity(), domain));
                }
            }
            public void objEntityAdded(ObjEntity ent) {
                c.fireObjEntityEvent(new EntityEvent(srcent, MapEvent.ADD));
                c.fireObjEntityDisplayEvent(new EntityDisplayEvent(srcentnodedomain));
            }
            public void objEntityRemoved(ObjEntity ent) {
                c.fireObjEntityEvent(new EntityEvent(srcent, MapEvent.REMOVE));
                c.fireObjEntityDisplayEvent(new EntityDisplayEvent(srcentnodedomain));
            }
            public void objRelationshipAdded(ObjRelationship rel) {
                if (c.getCurrentObjEntity() == rel.getSourceEntity()) {
                    c.fireObjRelationshipDisplayEvent(new RelationshipDisplayEvent(srcrelrel.getSourceEntity(), domain));
                }
            }
            public void objRelationshipRemoved(ObjRelationship rel) {
                if (c.getCurrentObjEntity() == rel.getSourceEntity()) {
                    c.fireObjRelationshipDisplayEvent(new RelationshipDisplayEvent(srcrelrel.getSourceEntity(), domain));
                }
            }
            
        };
        try {
            DataSource dataSource = .makeDataSource(getApplication()
                    .getClassLoadingService());
            // generator.runGenerator(dataSource);
            MergerContext mergerContext = new ExecutingMergerContext(
                    ,
                    dataSource,
                    delegate);
            boolean modelChanged = false;
            for (MergerToken tok : tokensToMigrate) {
                int numOfFailuresBefore = mergerContext
                        .getValidationResult()
                        .getFailures()
                        .size();
                tok.execute(mergerContext);
                if (!modelChanged && tok.getDirection().equals(MergeDirection.TO_MODEL)) {
                    modelChanged = true;
                }
                if (numOfFailuresBefore == mergerContext
                        .getValidationResult()
                        .getFailures()
                        .size()) {
                    // looks like the token executed without failures
                    .removeToken(tok);
                }
            }
            
            if (modelChanged) {
                // mark the model as unsaved
                Project project = Application.getProject();
                project.setModified(true);
                ProjectController projectController = Application
                        .getInstance()
                        .getFrameController()
                        .getProjectController();
                projectController.setDirty(true);
            }
            
            ValidationResult failures = mergerContext.getValidationResult();
            if (failures == null || !failures.hasFailures()) {
                JOptionPane.showMessageDialog(getView(), "Migration Complete.");
            }
            else {
                new ValidationResultBrowser(this).startupAction(
                        "Migration Complete",
                        "Migration finished. The following problem(s) were ignored.",
                        failures);
            }
        }
        catch (Throwable th) {
            reportError("Migration Error"th);
        }
    }

    
Allows user to save generated SQL in a file.
    public void storeSQLAction() {
        JFileChooser fc = new JFileChooser();
        fc.setDialogTitle("Save SQL Script");
        File projectDir = Application.getProject().getProjectDirectory();
        if (projectDir != null) {
            fc.setCurrentDirectory(projectDir);
        }
        if (fc.showSaveDialog(getView()) == .) {
            refreshGeneratorAction();
            try {
                File file = fc.getSelectedFile();
                FileWriter fw = new FileWriter(file);
                PrintWriter pw = new PrintWriter(fw);
                pw.print();
                pw.flush();
                pw.close();
            }
            catch (IOException ex) {
                reportError("Error Saving SQL"ex);
            }
        }
    }
    
    }
    public void closeAction() {
        .dispose();
    }
New to GrepCode? Check out our FAQ X