001: /*
002: * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
003: *
004: * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
005: *
006: * The contents of this file are subject to the terms of either the GNU
007: * General Public License Version 2 only ("GPL") or the Common
008: * Development and Distribution License("CDDL") (collectively, the
009: * "License"). You may not use this file except in compliance with the
010: * License. You can obtain a copy of the License at
011: * http://www.netbeans.org/cddl-gplv2.html
012: * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
013: * specific language governing permissions and limitations under the
014: * License. When distributing the software, include this License Header
015: * Notice in each file and include the License file at
016: * nbbuild/licenses/CDDL-GPL-2-CP. Sun designates this
017: * particular file as subject to the "Classpath" exception as provided
018: * by Sun in the GPL Version 2 section of the License file that
019: * accompanied this code. If applicable, add the following below the
020: * License Header, with the fields enclosed by brackets [] replaced by
021: * your own identifying information:
022: * "Portions Copyrighted [year] [name of copyright owner]"
023: *
024: * Contributor(s):
025: *
026: * The Original Software is NetBeans. The Initial Developer of the Original
027: * Software is Sun Microsystems, Inc. Portions Copyright 1997-2007 Sun
028: * Microsystems, Inc. All Rights Reserved.
029: *
030: * If you wish your version of this file to be governed by only the CDDL
031: * or only the GPL Version 2, indicate your decision by adding
032: * "[Contributor] elects to include this software in this distribution
033: * under the [CDDL or GPL Version 2] license." If you do not indicate a
034: * single choice of license, a recipient has the option to distribute
035: * your version of this file under either the CDDL, the GPL Version 2 or
036: * to extend the choice of license to its licensees as provided above.
037: * However, if you add GPL Version 2 code and therefore, elected the GPL
038: * Version 2 license, then the option applies only if the new code is
039: * made subject to such option by the copyright holder.
040: */
041: package org.netbeans.modules.form.j2ee;
042:
043: import java.awt.Dialog;
044: import java.awt.EventQueue;
045: import java.sql.Connection;
046: import java.util.concurrent.*;
047: import java.util.logging.Level;
048: import java.util.logging.Logger;
049: import javax.swing.DefaultComboBoxModel;
050: import javax.swing.JPanel;
051: import org.netbeans.api.db.explorer.ConnectionManager;
052: import org.netbeans.api.db.explorer.DatabaseConnection;
053: import org.netbeans.api.db.explorer.JDBCDriver;
054: import org.netbeans.api.db.explorer.JDBCDriverManager;
055: import org.netbeans.api.db.explorer.support.DatabaseExplorerUIs;
056: import org.netbeans.api.project.FileOwnerQuery;
057: import org.netbeans.api.project.Project;
058: import org.netbeans.modules.form.DataImporter;
059: import org.netbeans.modules.form.FormEditor;
060: import org.netbeans.modules.form.FormJavaSource;
061: import org.netbeans.modules.form.FormModel;
062: import org.netbeans.modules.form.RADComponent;
063: import org.netbeans.modules.j2ee.metadata.model.api.MetadataModel;
064: import org.netbeans.modules.j2ee.persistence.api.PersistenceScope;
065: import org.netbeans.modules.j2ee.persistence.api.metadata.orm.EntityMappingsMetadata;
066: import org.netbeans.modules.j2ee.persistence.dd.persistence.model_1_0.PersistenceUnit;
067: import org.openide.DialogDescriptor;
068: import org.openide.DialogDisplayer;
069: import org.openide.NotifyDescriptor;
070: import org.openide.filesystems.FileObject;
071: import org.openide.util.NbBundle;
072: import org.openide.util.RequestProcessor;
073:
074: /**
075: * Importer of list of JPA entities.
076: *
077: * @author Jan Stola
078: */
079: public class JPADataImporter extends JPanel implements DataImporter {
080:
081: /** This method is called from within the constructor to
082: * initialize the form.
083: * WARNING: Do NOT modify this code. The content of this method is
084: * always regenerated by the Form Editor.
085: */
086: // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
087: private void initComponents() {
088:
089: importerLabel = new javax.swing.JLabel();
090: connectionLabel = new javax.swing.JLabel();
091: tableLabel = new javax.swing.JLabel();
092: tableCombo = new javax.swing.JComboBox();
093: connectionCombo = new javax.swing.JComboBox();
094:
095: importerLabel.setText(org.openide.util.NbBundle.getMessage(
096: JPADataImporter.class, "MSG_ImportData")); // NOI18N
097:
098: connectionLabel.setText(org.openide.util.NbBundle.getMessage(
099: JPADataImporter.class, "LBL_ImportDBConnection")); // NOI18N
100:
101: tableLabel.setText(org.openide.util.NbBundle.getMessage(
102: JPADataImporter.class, "LBL_ImportDBTable")); // NOI18N
103:
104: tableCombo.setEnabled(false);
105: tableCombo.setRenderer(J2EEUtils.DBColumnInfo.getRenderer());
106:
107: connectionCombo
108: .addActionListener(new java.awt.event.ActionListener() {
109: public void actionPerformed(
110: java.awt.event.ActionEvent evt) {
111: connectionComboActionPerformed(evt);
112: }
113: });
114:
115: org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(
116: this );
117: this .setLayout(layout);
118: layout
119: .setHorizontalGroup(layout
120: .createParallelGroup(
121: org.jdesktop.layout.GroupLayout.LEADING)
122: .add(
123: layout
124: .createSequentialGroup()
125: .addContainerGap()
126: .add(
127: layout
128: .createParallelGroup(
129: org.jdesktop.layout.GroupLayout.LEADING)
130: .add(
131: importerLabel)
132: .add(
133: layout
134: .createSequentialGroup()
135: .add(
136: layout
137: .createParallelGroup(
138: org.jdesktop.layout.GroupLayout.LEADING)
139: .add(
140: connectionLabel)
141: .add(
142: tableLabel))
143: .addPreferredGap(
144: org.jdesktop.layout.LayoutStyle.RELATED)
145: .add(
146: layout
147: .createParallelGroup(
148: org.jdesktop.layout.GroupLayout.LEADING)
149: .add(
150: tableCombo,
151: 0,
152: 238,
153: Short.MAX_VALUE)
154: .add(
155: connectionCombo,
156: 0,
157: 238,
158: Short.MAX_VALUE))))
159: .addContainerGap()));
160: layout
161: .setVerticalGroup(layout
162: .createParallelGroup(
163: org.jdesktop.layout.GroupLayout.LEADING)
164: .add(
165: layout
166: .createSequentialGroup()
167: .addContainerGap()
168: .add(importerLabel)
169: .addPreferredGap(
170: org.jdesktop.layout.LayoutStyle.RELATED)
171: .add(
172: layout
173: .createParallelGroup(
174: org.jdesktop.layout.GroupLayout.BASELINE)
175: .add(
176: connectionLabel)
177: .add(
178: connectionCombo,
179: org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
180: org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
181: org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
182: .addPreferredGap(
183: org.jdesktop.layout.LayoutStyle.RELATED)
184: .add(
185: layout
186: .createParallelGroup(
187: org.jdesktop.layout.GroupLayout.BASELINE)
188: .add(tableLabel)
189: .add(
190: tableCombo,
191: org.jdesktop.layout.GroupLayout.PREFERRED_SIZE,
192: org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
193: org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
194: .addContainerGap(
195: org.jdesktop.layout.GroupLayout.DEFAULT_SIZE,
196: Short.MAX_VALUE)));
197: }// </editor-fold>//GEN-END:initComponents
198:
199: private void connectionComboActionPerformed(
200: java.awt.event.ActionEvent evt) {//GEN-FIRST:event_connectionComboActionPerformed
201: Object selItem = connectionCombo.getSelectedItem();
202: if (selItem instanceof DatabaseConnection) {
203: DatabaseConnection connection = (DatabaseConnection) selItem;
204: Connection con = J2EEUtils.establishConnection(connection);
205: if (con == null)
206: return; // User canceled the connection dialog
207: fillTableCombo(connection);
208: } else {
209: assert (selItem == null);
210: }
211: }//GEN-LAST:event_connectionComboActionPerformed
212:
213: /**
214: * Fills the content of <code>tableCombo</code>.
215: *
216: * @param connection database connection.
217: */
218: private void fillTableCombo(DatabaseConnection connection) {
219: DefaultComboBoxModel model = new DefaultComboBoxModel();
220: for (J2EEUtils.DBColumnInfo table : J2EEUtils
221: .tableNamesForConnection(connection)) {
222: model.addElement(table);
223: }
224: tableCombo.setModel(model);
225: tableCombo.setEnabled(tableCombo.getModel().getSize() != 0);
226: tableCombo.setSelectedItem(tableCombo.getSelectedItem());
227: }
228:
229: /**
230: * Imports list of JPA entities that correspond to selected DB table.
231: *
232: * @param formModel form to import the data into.
233: * @return the component encapsulating the imported data.
234: */
235: public Future<RADComponent> importData(final FormModel formModel) {
236: removeAll();
237: if (FormJavaSource.isInDefaultPackage(formModel)) {
238: // 97982: default package
239: DialogDisplayer.getDefault().notify(
240: new NotifyDescriptor.Message(NbBundle.getMessage(
241: getClass(), "MSG_ImportToDefaultPackage"))); // NOI18N
242: return null;
243: }
244: initComponents();
245: DatabaseExplorerUIs.connect(connectionCombo, ConnectionManager
246: .getDefault());
247: DialogDescriptor dd = new DialogDescriptor(this , NbBundle
248: .getMessage(getClass(), "TITLE_ImportData"), // NOI18N
249: true, null);
250: Dialog dialog = DialogDisplayer.getDefault().createDialog(dd);
251: dialog.setVisible(true);
252: if (dd.getValue() != DialogDescriptor.OK_OPTION)
253: return null;
254: FutureTask<RADComponent> task = new FutureTask<RADComponent>(
255: new Callable<RADComponent>() {
256: public RADComponent call() throws Exception {
257: final RADComponent[] resultList = new RADComponent[1];
258: try {
259: J2EEUtils.DBColumnInfo table = (J2EEUtils.DBColumnInfo) tableCombo
260: .getSelectedItem();
261: if ((table == null) || !table.isValid())
262: return null;
263: String tableName = table.getName();
264: DatabaseConnection connection = (DatabaseConnection) connectionCombo
265: .getSelectedItem();
266: FileObject formFile = FormEditor
267: .getFormDataObject(formModel)
268: .getFormFile();
269: Project project = FileOwnerQuery
270: .getOwner(formFile);
271:
272: // Make sure persistence.xml file exists
273: FileObject persistenceXML = J2EEUtils
274: .getPersistenceXML(project, true);
275:
276: // Initializes persistence unit and persistence descriptor
277: PersistenceUnit unit = J2EEUtils
278: .initPersistenceUnit(
279: persistenceXML, connection);
280:
281: // Initializes project's classpath
282: JDBCDriver[] driver = JDBCDriverManager
283: .getDefault()
284: .getDrivers(
285: connection.getDriverClass());
286: J2EEUtils.updateProjectForUnit(
287: persistenceXML, unit, driver[0]);
288:
289: // Obtain description of entity mappings
290: PersistenceScope scope = PersistenceScope
291: .getPersistenceScope(formFile);
292: MetadataModel<EntityMappingsMetadata> mappings = scope
293: .getEntityMappingsModel(unit
294: .getName());
295:
296: // Find entity that corresponds to the dragged table
297: String[] entityInfo = J2EEUtils.findEntity(
298: mappings, tableName);
299:
300: // Create a new entity (if there isn't one that corresponds to the dragged table)
301: if (entityInfo == null) {
302: // Generates a Java class for the entity
303: J2EEUtils.createEntity(formFile
304: .getParent(), scope, unit,
305: connection, tableName, null);
306:
307: mappings = scope
308: .getEntityMappingsModel(unit
309: .getName());
310: entityInfo = J2EEUtils.findEntity(
311: mappings, tableName);
312: } else {
313: // Add the entity into the persistence unit if it is not there already
314: J2EEUtils.addEntityToUnit(
315: entityInfo[1], unit, project);
316: }
317:
318: J2EEUtils.makeEntityObservable(formFile,
319: entityInfo, mappings);
320:
321: final String puName = unit.getName();
322: final String[] info = entityInfo;
323: EventQueue.invokeAndWait(new Runnable() {
324: public void run() {
325: try {
326: RADComponent entityManager = J2EEUtils
327: .findEntityManager(
328: formModel,
329: puName);
330: if (entityManager == null) {
331: entityManager = J2EEUtils
332: .createEntityManager(
333: formModel,
334: puName);
335: }
336: RADComponent queryBean = DBTableDrop
337: .createQueryBean(
338: formModel,
339: entityManager,
340: info[0]);
341: resultList[0] = DBTableDrop
342: .createResultListBean(
343: formModel,
344: queryBean, info);
345: } catch (Exception ex) {
346: Logger
347: .getLogger(
348: getClass()
349: .getName())
350: .log(
351: Level.INFO,
352: ex.getMessage(),
353: ex);
354: }
355: }
356: });
357: } catch (Exception ex) {
358: Logger.getLogger(getClass().getName()).log(
359: Level.INFO, ex.getMessage(), ex);
360: }
361: return resultList[0];
362: }
363: });
364: RequestProcessor.getDefault().post(task);
365: return task;
366: }
367:
368: // Variables declaration - do not modify//GEN-BEGIN:variables
369: private javax.swing.JComboBox connectionCombo;
370: private javax.swing.JLabel connectionLabel;
371: private javax.swing.JLabel importerLabel;
372: private javax.swing.JComboBox tableCombo;
373: private javax.swing.JLabel tableLabel;
374: // End of variables declaration//GEN-END:variables
375:
376: }
|