PageRenderTime 37ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/projects/netbeans-7.3/j2ee.common/src/org/netbeans/modules/j2ee/common/DatasourceUIHelper.java

https://gitlab.com/essere.lab.public/qualitas.class-corpus
Java | 779 lines | 517 code | 114 blank | 148 comment | 87 complexity | 4b24311f1e90913082bbd535552d4ae1 MD5 | raw file
  1. /*
  2. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
  3. *
  4. * Copyright 1997-2010 Oracle and/or its affiliates. All rights reserved.
  5. *
  6. * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
  7. * Other names may be trademarks of their respective owners.
  8. *
  9. * The contents of this file are subject to the terms of either the GNU
  10. * General Public License Version 2 only ("GPL") or the Common
  11. * Development and Distribution License("CDDL") (collectively, the
  12. * "License"). You may not use this file except in compliance with the
  13. * License. You can obtain a copy of the License at
  14. * http://www.netbeans.org/cddl-gplv2.html
  15. * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
  16. * specific language governing permissions and limitations under the
  17. * License. When distributing the software, include this License Header
  18. * Notice in each file and include the License file at
  19. * nbbuild/licenses/CDDL-GPL-2-CP. Oracle designates this
  20. * particular file as subject to the "Classpath" exception as provided
  21. * by Oracle in the GPL Version 2 section of the License file that
  22. * accompanied this code. If applicable, add the following below the
  23. * License Header, with the fields enclosed by brackets [] replaced by
  24. * your own identifying information:
  25. * "Portions Copyrighted [year] [name of copyright owner]"
  26. *
  27. * Contributor(s):
  28. *
  29. * The Original Software is NetBeans. The Initial Developer of the Original
  30. * Software is Sun Microsystems, Inc. Portions Copyright 1997-2006 Sun
  31. * Microsystems, Inc. All Rights Reserved.
  32. *
  33. * If you wish your version of this file to be governed by only the CDDL
  34. * or only the GPL Version 2, indicate your decision by adding
  35. * "[Contributor] elects to include this software in this distribution
  36. * under the [CDDL or GPL Version 2] license." If you do not indicate a
  37. * single choice of license, a recipient has the option to distribute
  38. * your version of this file under either the CDDL, the GPL Version 2 or
  39. * to extend the choice of license to its licensees as provided above.
  40. * However, if you add GPL Version 2 code and therefore, elected the GPL
  41. * Version 2 license, then the option applies only if the new code is
  42. * made subject to such option by the copyright holder.
  43. */
  44. package org.netbeans.modules.j2ee.common;
  45. import java.awt.Color;
  46. import java.awt.Component;
  47. import java.awt.Dimension;
  48. import java.awt.event.ActionEvent;
  49. import java.awt.event.ActionListener;
  50. import java.awt.event.InputEvent;
  51. import java.awt.event.KeyAdapter;
  52. import java.awt.event.KeyEvent;
  53. import java.lang.reflect.Method;
  54. import java.util.ArrayList;
  55. import java.util.Collection;
  56. import java.util.Collections;
  57. import java.util.Comparator;
  58. import java.util.HashSet;
  59. import java.util.LinkedList;
  60. import java.util.List;
  61. import java.util.Set;
  62. import java.util.logging.Level;
  63. import java.util.logging.Logger;
  64. import javax.swing.AbstractListModel;
  65. import javax.swing.ComboBoxEditor;
  66. import javax.swing.DefaultListCellRenderer;
  67. import javax.swing.JComboBox;
  68. import javax.swing.JList;
  69. import javax.swing.JSeparator;
  70. import javax.swing.ListCellRenderer;
  71. import javax.swing.MutableComboBoxModel;
  72. import javax.swing.SwingUtilities;
  73. import javax.swing.text.JTextComponent;
  74. import org.netbeans.api.project.Project;
  75. import org.netbeans.modules.j2ee.core.api.support.progress.ProgressSupport;
  76. import org.netbeans.modules.j2ee.core.api.support.progress.ProgressSupport.Action;
  77. import org.netbeans.modules.j2ee.core.api.support.progress.ProgressSupport.Context;
  78. import org.netbeans.modules.j2ee.deployment.common.api.ConfigurationException;
  79. import org.netbeans.modules.j2ee.deployment.devmodules.spi.J2eeModuleProvider;
  80. import org.netbeans.modules.j2ee.deployment.common.api.Datasource;
  81. import org.netbeans.modules.j2ee.deployment.common.api.DatasourceAlreadyExistsException;
  82. import org.netbeans.modules.j2ee.persistence.dd.common.PersistenceUnit;
  83. import org.netbeans.modules.j2ee.persistence.spi.provider.PersistenceProviderSupplier;
  84. import org.netbeans.modules.j2ee.persistence.spi.server.ServerStatusProvider2;
  85. import org.openide.util.Exceptions;
  86. import org.openide.util.NbBundle;
  87. /**
  88. *
  89. * DatasourceUIHelper populates and manages the content of the combobox for a data sources management.
  90. *
  91. * @author Libor Kotouc
  92. *
  93. * @since 1.6
  94. */
  95. public final class DatasourceUIHelper {
  96. private static final class Separator extends JSeparator {
  97. Separator() {
  98. setPreferredSize(new Dimension(getWidth(), 1));
  99. setForeground(Color.BLACK);
  100. }
  101. }
  102. static final Separator SEPARATOR_ITEM = new Separator();
  103. static final Object NEW_ITEM = new Object() {
  104. @Override
  105. public String toString() {
  106. return NbBundle.getMessage(DatasourceUIHelper.class, "LBL_NEW_DATASOURCE"); // NOI18N
  107. }
  108. };
  109. static final Object SELECT_SERVER_ITEM = new Object() {
  110. @Override
  111. public String toString() {
  112. return NbBundle.getMessage(DatasourceUIHelper.class, "LBL_SELECT_SERVER"); // NOI18N
  113. }
  114. };
  115. private static class DatasourceComboBoxModel extends AbstractListModel implements MutableComboBoxModel {
  116. private List<Object> items;
  117. private Object selectedItem;
  118. private List<Datasource> datasources;
  119. private Object previousItem;
  120. private DatasourceComboBoxModel(List<Datasource> datasources, List<Object> items) {
  121. this.datasources = datasources;
  122. this.items = items;
  123. }
  124. @Override
  125. public void setSelectedItem(Object anItem) {
  126. if (selectedItem == null || !selectedItem.equals(anItem)) {
  127. previousItem = selectedItem;
  128. selectedItem = anItem;
  129. fireContentsChanged(this, 0, -1);
  130. }
  131. }
  132. @Override
  133. public Object getSelectedItem() {
  134. return selectedItem;
  135. }
  136. @Override
  137. public Object getElementAt(int index) {
  138. return items.get(index);
  139. }
  140. @Override
  141. public int getSize() {
  142. return items.size();
  143. }
  144. Object getPreviousItem() {
  145. return previousItem;
  146. }
  147. List<Datasource> getDatasources() {
  148. return datasources;
  149. }
  150. @Override
  151. public void addElement(Object elem) {
  152. items.add(elem);
  153. }
  154. @Override
  155. public void removeElement(Object elem) {
  156. items.remove(elem);
  157. }
  158. @Override
  159. public void insertElementAt(Object elem, int index) {
  160. items.set(index, elem);
  161. }
  162. @Override
  163. public void removeElementAt(int index) {
  164. items.remove(index);
  165. }
  166. }
  167. private static class DatasourcePUComboBoxModel extends AbstractListModel implements MutableComboBoxModel {
  168. private List<Object> items;
  169. private Object selectedItem;
  170. private List<Datasource> datasources;
  171. private Object previousItem;
  172. private final List<PersistenceUnit> pUnits;
  173. private DatasourcePUComboBoxModel(List<Datasource> datasources, List<PersistenceUnit> pUnits, List<Object> items) {
  174. this.datasources = datasources;
  175. this.pUnits = pUnits;
  176. this.items = items;
  177. }
  178. @Override
  179. public void setSelectedItem(Object anItem) {
  180. if (selectedItem == null || !selectedItem.equals(anItem)) {
  181. previousItem = selectedItem;
  182. selectedItem = anItem;
  183. fireContentsChanged(this, 0, -1);
  184. }
  185. }
  186. @Override
  187. public Object getSelectedItem() {
  188. return selectedItem;
  189. }
  190. @Override
  191. public Object getElementAt(int index) {
  192. return items.get(index);
  193. }
  194. @Override
  195. public int getSize() {
  196. return items.size();
  197. }
  198. Object getPreviousItem() {
  199. return previousItem;
  200. }
  201. List<Datasource> getDatasources() {
  202. return datasources;
  203. }
  204. @Override
  205. public void addElement(Object elem) {
  206. items.add(elem);
  207. }
  208. @Override
  209. public void removeElement(Object elem) {
  210. items.remove(elem);
  211. }
  212. @Override
  213. public void insertElementAt(Object elem, int index) {
  214. items.set(index, elem);
  215. }
  216. @Override
  217. public void removeElementAt(int index) {
  218. items.remove(index);
  219. }
  220. }
  221. /**
  222. * Get data source list cell renderer.
  223. * @return data source list cell renderer instance.
  224. * @since 1.16
  225. */
  226. public static ListCellRenderer createDatasourceListCellRenderer() {
  227. return new DatasourceListCellRenderer();
  228. }
  229. private static class DatasourceListCellRenderer extends DefaultListCellRenderer {
  230. @Override
  231. public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
  232. if (isSelected) {
  233. setBackground(list.getSelectionBackground());
  234. setForeground(list.getSelectionForeground());
  235. } else {
  236. setBackground(list.getBackground());
  237. setForeground(list.getForeground());
  238. }
  239. if (value instanceof Datasource) {
  240. Datasource ds = (Datasource) value;
  241. setText(ds != null ? ds.getDisplayName() : ""); // NOI18N
  242. setToolTipText(ds.toString());
  243. }
  244. else
  245. if (value == SEPARATOR_ITEM) {
  246. return SEPARATOR_ITEM;
  247. }
  248. else {
  249. setText(value != null ? value.toString() : ""); // NOI18N
  250. setToolTipText(""); // NOI18N
  251. }
  252. return this;
  253. }
  254. }
  255. /**
  256. * Get data source comparator.
  257. * @return data source comparator instance.
  258. * @since 1.16
  259. */
  260. public static Comparator<Datasource> createDatasourceComparator() {
  261. return new DatasourceComparator();
  262. }
  263. private static class DatasourceComparator implements Comparator<Datasource> {
  264. @Override
  265. public int compare(Datasource ds1, Datasource ds2) {
  266. if (ds1 == null) {
  267. return ds2 == null ? 0 : -1;
  268. }
  269. else {
  270. if (ds2 == null) {
  271. return 1;
  272. }
  273. else {
  274. String dispName1 = ds1.getDisplayName();
  275. String dispName2 = ds2.getDisplayName();
  276. if (dispName1 == null) {
  277. return dispName2 == null ? 0 : -1;
  278. }
  279. else {
  280. return dispName2 == null ? 1 : dispName1.compareToIgnoreCase(dispName2);
  281. }
  282. }
  283. }
  284. }
  285. }
  286. private static class DatasourceComboBoxEditor implements ComboBoxEditor {
  287. private ComboBoxEditor delegate;
  288. private Object oldValue;
  289. DatasourceComboBoxEditor(ComboBoxEditor delegate) {
  290. this.delegate = delegate;
  291. }
  292. @Override
  293. public Component getEditorComponent() {
  294. return delegate.getEditorComponent();
  295. }
  296. @Override
  297. public void setItem(Object anObject) {
  298. JTextComponent editor = getEditor();
  299. if (anObject != null) {
  300. String text = (anObject instanceof Datasource ? ((Datasource)anObject).getJndiName() : anObject.toString());
  301. editor.setText(text);
  302. oldValue = anObject;
  303. }
  304. else {
  305. editor.setText("");
  306. }
  307. }
  308. // this method is taken from javax.swing.plaf.basic.BasicComboBoxEditor
  309. @Override
  310. public Object getItem() {
  311. JTextComponent editor = getEditor();
  312. Object newValue = editor.getText();
  313. if (oldValue != null && !(oldValue instanceof String)) {
  314. // The original value is not a string. Should return the value in it's
  315. // original type.
  316. if (newValue.equals(oldValue.toString())) {
  317. return oldValue;
  318. } else {
  319. // Must take the value from the editor and get the value and cast it to the new type.
  320. Class<?> cls = oldValue.getClass();
  321. try {
  322. Method method = cls.getMethod("valueOf", String.class); // NOI18N
  323. newValue = method.invoke(oldValue, new Object[] { editor.getText() });
  324. } catch (Exception ex) {
  325. // Fail silently and return the newValue (a String object)
  326. Logger.getLogger("DatasourceUIHelper").log(Level.FINE, "ignored exception", ex); //NOI18N
  327. }
  328. }
  329. }
  330. return newValue;
  331. }
  332. @Override
  333. public void selectAll() {
  334. delegate.selectAll();
  335. }
  336. @Override
  337. public void addActionListener(ActionListener l) {
  338. delegate.addActionListener(l);
  339. }
  340. @Override
  341. public void removeActionListener(ActionListener l) {
  342. delegate.removeActionListener(l);
  343. }
  344. private JTextComponent getEditor() {
  345. Component comp = getEditorComponent();
  346. assert (comp instanceof JTextComponent);
  347. return (JTextComponent)comp;
  348. }
  349. }
  350. private DatasourceUIHelper() {
  351. }
  352. /**
  353. * Entry point for the combobox initialization. It connects combobox with its content and
  354. * add items for the combobox content management.
  355. *
  356. * @param provider Java EE module provider.
  357. * @param combo combobox to manage.
  358. */
  359. public static void connect(J2eeModuleProvider provider, JComboBox combo) {
  360. connect(null, provider, combo, null, false);
  361. }
  362. /**
  363. * Entry point for the combobox initialization. It connects combobox with its content and
  364. * add items for the combobox content management. Fill list with datasources with persistence unit combination if match
  365. *
  366. * @param project is used to determine existing persistence units and combine with datasources
  367. * @param provider Java EE module provider.
  368. * @param combo combobox to manage.
  369. */
  370. public static void connect(Project project, J2eeModuleProvider provider, JComboBox combo) {
  371. boolean canServerBeSelected = false;
  372. ServerStatusProvider2 serverStatusProvider = project.getLookup().lookup(ServerStatusProvider2.class);
  373. if (serverStatusProvider != null && !serverStatusProvider.validServerInstancePresent()) {
  374. canServerBeSelected = true;
  375. }
  376. connect(project, provider, combo, null, canServerBeSelected);
  377. }
  378. private static List<Datasource> fetchDataSources(final J2eeModuleProvider provider) {
  379. // fetch datasources asynchronously
  380. Collection<Action> actions = new ArrayList<Action>();
  381. final List<Datasource> datasources = new ArrayList<Datasource>();
  382. actions.add(new ProgressSupport.BackgroundAction() {
  383. @Override
  384. public void run(Context actionContext) {
  385. String msg = NbBundle.getMessage(DatasourceUIHelper.class, "MSG_retrievingDS");
  386. actionContext.progress(msg);
  387. try {
  388. datasources.addAll(getDatasources(provider));
  389. } catch (ConfigurationException e) {
  390. // TODO: provide a feedback to the user
  391. }
  392. }
  393. });
  394. ProgressSupport.invoke(actions);
  395. return datasources;
  396. }
  397. private static final void connect(final Project project, final J2eeModuleProvider provider, final JComboBox combo, final Datasource selectedDatasource, boolean canServerBeSelected) {
  398. assert(provider != null);
  399. combo.setEditor(new DatasourceComboBoxEditor(combo.getEditor()));
  400. combo.setRenderer(new DatasourceListCellRenderer());
  401. final List<Datasource> datasources = fetchDataSources(provider);
  402. populate(datasources, provider.isDatasourceCreationSupported(), combo, selectedDatasource, false, canServerBeSelected);
  403. Component toListenOn = (combo.isEditable() ? combo.getEditor().getEditorComponent() : combo);
  404. toListenOn.addKeyListener(new KeyAdapter() {
  405. @Override
  406. public void keyPressed(final KeyEvent e) {
  407. int keyCode = e.getKeyCode();
  408. if (KeyEvent.VK_ENTER == keyCode) {
  409. Object selectedItem = combo.getSelectedItem();
  410. if (selectedItem == NEW_ITEM) {
  411. performCreateDatasource(provider, combo, false);
  412. e.consume();
  413. } else if (selectedItem == SELECT_SERVER_ITEM) {
  414. performServerSelection(project, provider, combo);
  415. e.consume();
  416. }
  417. }
  418. }
  419. });
  420. combo.addActionListener(new ActionListener() {
  421. Object previousItem;
  422. int previousIndex = combo.getSelectedIndex();
  423. @Override
  424. public void actionPerformed(ActionEvent e) {
  425. Object selectedItem = combo.getSelectedItem();
  426. // skipping of separator
  427. if (selectedItem == SEPARATOR_ITEM) {
  428. int selectedIndex = combo.getSelectedIndex();
  429. if (selectedIndex > previousIndex) {
  430. previousIndex = selectedIndex + 1;
  431. previousItem = combo.getItemAt(previousIndex);
  432. } else {
  433. previousIndex = selectedIndex - 1;
  434. previousItem = combo.getItemAt(previousIndex);
  435. }
  436. combo.setSelectedItem(previousItem);
  437. // handling mouse click, see KeyEvent.getKeyModifiersText(e.getModifiers())
  438. } else if ((e.getModifiers() & InputEvent.BUTTON1_MASK) != 0) {
  439. if (selectedItem == NEW_ITEM) {
  440. performCreateDatasource(provider, combo, true);
  441. } else if (selectedItem == SELECT_SERVER_ITEM) {
  442. performServerSelection(project, provider, combo);
  443. }
  444. }
  445. }
  446. });
  447. }
  448. private static boolean isContainerManaged(Project project) {
  449. PersistenceProviderSupplier providerSupplier = project.getLookup().lookup(PersistenceProviderSupplier.class);
  450. return providerSupplier != null && providerSupplier.supportsDefaultProvider();
  451. }
  452. private static void performServerSelection(Project project, J2eeModuleProvider provider, final JComboBox combo) {
  453. ServerStatusProvider2 serverStatusProvider = project.getLookup().lookup(ServerStatusProvider2.class);
  454. if (serverStatusProvider.selectServer()) {
  455. provider = project.getLookup().lookup(J2eeModuleProvider.class);
  456. // if server which does not support Data Sources was chosen then
  457. // do not bother populating the list
  458. if (isContainerManaged(project)) {
  459. final List<Datasource> datasources = fetchDataSources(provider);
  460. populate(datasources, provider.isDatasourceCreationSupported(), combo, null, false, false);
  461. }
  462. }
  463. }
  464. private static void performCreateDatasource(final J2eeModuleProvider provider, final JComboBox combo, boolean selectItemLater) {
  465. final DatasourceComboBoxModel model = (DatasourceComboBoxModel) combo.getModel();
  466. final DatasourceCustomizer dsc = new DatasourceCustomizer(model.getDatasources());
  467. boolean accept = dsc.showDialog();
  468. Collection<Action> actions = new ArrayList<Action>();
  469. final Datasource[] ds = new Datasource[1];
  470. // creating datasources asynchronously
  471. if (accept) {
  472. final String password = dsc.getPassword();
  473. final String jndiName = dsc.getJndiName();
  474. final String url = dsc.getUrl();
  475. final String username = dsc.getUsername();
  476. final String driverClassName = dsc.getDriverClassName();
  477. actions.add(new ProgressSupport.BackgroundAction() {
  478. @Override
  479. public void run(Context actionContext) {
  480. String msg = NbBundle.getMessage(DatasourceUIHelper.class, "MSG_creatingDS");
  481. actionContext.progress(msg);
  482. try {
  483. ds[0] = provider.createDatasource(jndiName, url, username, password, driverClassName);
  484. } catch (DatasourceAlreadyExistsException daee) { // it should not occur bcs it should be already handled in DatasourceCustomizer
  485. StringBuilder sb = new StringBuilder();
  486. for (Object conflict : daee.getDatasources()) {
  487. sb.append(conflict.toString() + "\n"); // NOI18N
  488. }
  489. String message = NbBundle.getMessage(DatasourceUIHelper.class, "ERR_DsConflict", sb.toString());
  490. Logger.getLogger("global").log(Level.INFO, message, Exceptions.attachLocalizedMessage(daee, message));
  491. } catch (ConfigurationException ce) {
  492. // TODO: provide a feedback to the user
  493. }
  494. }
  495. @Override
  496. public boolean isEnabled() {
  497. return password != null;
  498. }
  499. });
  500. }
  501. // fetch datasources asynchronously
  502. final List<Datasource> datasources = new ArrayList<Datasource>();
  503. actions.add(new ProgressSupport.BackgroundAction() {
  504. @Override
  505. public void run(Context actionContext) {
  506. String msg = NbBundle.getMessage(DatasourceUIHelper.class, "MSG_retrievingDS");
  507. actionContext.progress(msg);
  508. try {
  509. datasources.addAll(getDatasources(provider));
  510. } catch (ConfigurationException e) {
  511. // TODO: provide a feedback to the user
  512. }
  513. }
  514. @Override
  515. public boolean isEnabled() {
  516. return ds[0] != null;
  517. }
  518. });
  519. ProgressSupport.invoke(actions);
  520. combo.setPopupVisible(false);
  521. if (ds[0] == null) {
  522. SwingUtilities.invokeLater(new Runnable() {
  523. @Override
  524. public void run() {
  525. setSelectedItem(combo, model.getPreviousItem());
  526. }
  527. });
  528. } else {
  529. populate(datasources, provider.isDatasourceCreationSupported(), combo, ds[0], selectItemLater, false);
  530. }
  531. }
  532. /**
  533. * Returns a sorted list of all datasources (from the module and the server)
  534. */
  535. private static List<Datasource> getDatasources(final J2eeModuleProvider provider) throws ConfigurationException {
  536. Set<Datasource> moduleDatasources = provider.getModuleDatasources();
  537. Set<Datasource> serverDatasources = provider.getServerDatasources();
  538. int initSize = moduleDatasources.size() + serverDatasources.size();
  539. Set<Datasource> datasources = new HashSet<Datasource>(initSize);
  540. datasources.addAll(moduleDatasources);
  541. datasources.addAll(serverDatasources);
  542. ArrayList<Datasource> sortedDatasources = new ArrayList<Datasource>(datasources);
  543. Collections.sort(sortedDatasources, new DatasourceComparator());
  544. return sortedDatasources;
  545. }
  546. // private static List<PersistenceUnit> getPU(final Project project){
  547. // String persistenceUnit = null;
  548. // PersistenceScope persistenceScopes[] = PersistenceUtils.getPersistenceScopes(project);
  549. // if (persistenceScopes.length > 0) {
  550. // FileObject persXml = persistenceScopes[0].getPersistenceXml();
  551. // if (persXml != null) {
  552. // Persistence persistence = PersistenceMetadata.getDefault().getRoot(persXml);
  553. // PersistenceUnit units[] = persistence.getPersistenceUnit();
  554. // if (units.length > 0) {
  555. // persistenceUnit = units[0].getName();
  556. // if(units.length>1) {//find best
  557. // String forAll=null;
  558. // String forOne=null;
  559. // for(int i=0;i<units.length && forOne==null;i++) {
  560. // PersistenceUnit tmp=units[i];
  561. // if(forAll ==null && !tmp.isExcludeUnlistedClasses()) forAll=tmp.getName();//first match sutable for all entities in the project
  562. // if(tmp.isExcludeUnlistedClasses()) {
  563. // String []classes = tmp.getClass2();
  564. // for(String clas:classes){
  565. // if(entity.equals(clas)) {
  566. // forOne = tmp.getName();
  567. // break;
  568. // }
  569. // }
  570. // }
  571. // }
  572. // //try again with less restrictions (i.e. for j2se even without exclude-unlisted-classes node, it's by default true)
  573. // if(forOne==null && forAll!=null){//there is exist pu without exclude-unlisted-classes
  574. // for(int i=0;i<units.length && forOne==null;i++) {
  575. // PersistenceUnit tmp=units[i];
  576. // if(!tmp.isExcludeUnlistedClasses()) {//verify only pu without exclude-unlisted-classes as all other was examined in previos try
  577. // String []classes = tmp.getClass2();
  578. // for(String clas:classes){
  579. // if(entity.equals(clas)) {
  580. // forOne = tmp.getName();
  581. // break;
  582. // }
  583. // }
  584. // }
  585. // }
  586. // }
  587. //
  588. // persistenceUnit = forOne != null ? forOne : (forAll != null ? forAll : persistenceUnit);
  589. // }
  590. // }
  591. // }
  592. // }
  593. // return persistenceUnit;
  594. // }
  595. private static List populate(List<Datasource> datasources, boolean creationSupported, final JComboBox combo, final Datasource selectedDatasource, boolean selectItemLater, boolean serverSelectionSupported) {
  596. List<Object> items = (datasources == null ? new LinkedList<Object>() : new LinkedList<Object>(datasources));
  597. if (items.size() > 0) {
  598. items.add(SEPARATOR_ITEM);
  599. }
  600. if (creationSupported) {
  601. items.add(NEW_ITEM);
  602. }
  603. if (serverSelectionSupported) {
  604. items.add(SELECT_SERVER_ITEM);
  605. }
  606. DatasourceComboBoxModel model = new DatasourceComboBoxModel(datasources, items);
  607. combo.setModel(model);
  608. if (selectedDatasource != null) {
  609. // Ensure that the correct item is selected before listeners like FocusListener are called.
  610. // ActionListener.actionPerformed() is not called if this method is already called from
  611. // actionPerformed(), in that case selectItemLater should be set to true and setSelectedItem()
  612. // below is called asynchronously so that the actionPerformed() is called
  613. setSelectedItem(combo, selectedDatasource);
  614. if (selectItemLater) {
  615. SwingUtilities.invokeLater(new Runnable() { // postpone item selection to enable event firing from JCombobox.setSelectedItem()
  616. @Override
  617. public void run() {
  618. setSelectedItem(combo, selectedDatasource);
  619. }
  620. });
  621. }
  622. }
  623. return datasources;
  624. }
  625. private static void setSelectedItem(final JComboBox combo, final Object item) {
  626. combo.setSelectedItem(item);
  627. if (combo.isEditable() && combo.getEditor() != null) {
  628. // item must be set in the editor in case of editable combobox
  629. combo.configureEditor(combo.getEditor(), combo.getSelectedItem());
  630. }
  631. }
  632. private class DatasourcePuPair implements Comparable<DatasourcePuPair> {
  633. private Datasource datasource;
  634. private PersistenceUnit pu;
  635. public DatasourcePuPair(Datasource datasource, PersistenceUnit pu) {
  636. this.datasource= datasource;
  637. this.pu = pu;
  638. }
  639. @Override
  640. public boolean equals(Object obj) {
  641. if(obj instanceof DatasourcePuPair) {
  642. DatasourcePuPair pa=(DatasourcePuPair) obj;
  643. return datasource.equals(pa.datasource) && ((pu==null && pa.pu==null) || (pu!=null && pu.equals(pa.pu)));
  644. }
  645. else return false;
  646. }
  647. @Override
  648. public int hashCode() {
  649. int hash = 7;
  650. hash = 17 * hash + (this.datasource != null ? this.datasource.hashCode() : 0);
  651. hash = 17 * hash + (this.pu != null ? this.pu.hashCode() : 0);
  652. return hash;
  653. }
  654. @Override
  655. public int compareTo(DatasourcePuPair o) {
  656. String s1 = datasource.getDisplayName() + "( "+pu.getName()+" )";
  657. String s2 = o.datasource.getDisplayName() + "( "+o.pu.getName()+" )";
  658. return s1.compareTo(s2);
  659. }
  660. @Override
  661. public String toString() {
  662. return datasource.getDisplayName() + "( "+pu.getName()+" )";
  663. }
  664. }
  665. }