List of usage examples for javax.swing UIManager setLookAndFeel
@SuppressWarnings("deprecation") public static void setLookAndFeel(String className) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException
From source file:com.ejie.uda.jsonI18nEditor.Editor.java
public static void main(String[] args) { SwingUtilities.invokeLater(() -> { try {//from w ww . ja v a 2 s .c o m // Only use native look an feel when not running Linux, Linux might cause visual issues if (!SystemUtils.IS_OS_LINUX) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } } catch (Exception e) { // } new Editor().launch(); }); }
From source file:livecanvas.mesheditor.MeshEditor.java
public static void main(String[] args) throws Exception { // AlloyLookAndFeel.setProperty("alloy.licenseCode", // "2011/06/29#asidjoaisdjoasidjid@mailinator.com#lj8xv#1a193l"); // AlloyLookAndFeel.setProperty("alloy.isToolbarEffectsEnabled", // "false");//w ww. j a v a 2 s. c om // try { // AlloyLookAndFeel alloyLnF = new AlloyLookAndFeel(); // alloyLnF.setTheme(new GlassTheme(), true); // UIManager.setLookAndFeel(alloyLnF); // } catch (UnsupportedLookAndFeelException ex) { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // } JFrame f = new JFrame("LiveCanvas - Mesh Editor"); final MeshEditor meshEditor = new MeshEditor(); f.setJMenuBar(meshEditor.getMenuBar()); f.getContentPane().add(meshEditor); f.getContentPane().add(meshEditor.getToolBar(), BorderLayout.NORTH); f.pack(); f.setLocationRelativeTo(null); f.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { System.exit(0); // meshEditor.exit(); } }); f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); f.setVisible(true); // meshEditor.open(new File("C:/Users/Jasleen/Desktop/prez.mesh")); }
From source file:uk.ac.ox.cbrg.cpfp.uploadapp.UploadApplet.java
@Override public void init() { // Set errorFlag to false - no errors yet ;-) errorFlag = false;/*from w ww . j a va 2 s. c om*/ // <PARAM> tag handling uploadFiles = new Vector<UploadFile>(); uploadURL = getParameter("UPLOADURL"); if (uploadURL == null) { uploadURL = ""; } fileExtensions = getParameter("EXTENSIONS"); if (fileExtensions == null) { fileExtensions = ""; } chunkSize = Long.parseLong(getParameter("CHUNKSIZE")); if (chunkSize == 0) { chunkSize = 10485760; // 10MB } // Get cookies from browser so session can be used for uploads try { JSObject myBrowser = (JSObject) JSObject.getWindow(this); JSObject myDocument = (JSObject) myBrowser.getMember("document"); browserCookie = (String) myDocument.getMember("cookie"); jso = JSObject.getWindow(this); } catch (Exception e) { e.printStackTrace(); } // Use Nimbus look and feel rather than default try { for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (UnsupportedLookAndFeelException e) { } catch (ClassNotFoundException e) { } catch (InstantiationException e) { } catch (IllegalAccessException e) { } // Invoke Applet try { java.awt.EventQueue.invokeAndWait(new Runnable() { public void run() { initComponents(); } }); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:gov.nih.nci.nbia.StandaloneDMV3.java
public void constructLoginWin() { try {//w w w . j a v a 2s . c om UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception ex) { ex.printStackTrace(); } frame = new JFrame("Standalone Download Manager"); frame.setResizable(false); if (true) { frame.setBounds(100, 100, 910, 528); frame.setContentPane(createloginPanelV2()); } else { frame.setBounds(100, 100, 928, 690); frame.setContentPane(constructLoginPanel()); } frame.setTitle(winTitle); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }
From source file:ca.uviccscu.lp.server.main.AddGameDialog.java
/** * @param args the command line arguments *///from ww w. ja v a2 s. c o m public static void main(String args[]) { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception ex) { // } java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { AddGameDialog dialog = new AddGameDialog(new javax.swing.JFrame(), true); dialog.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent e) { System.exit(0); } }); dialog.setVisible(true); } }); }
From source file:jeplus.gui.EPlusEditorPanel.java
public static void main(String[] args) { try {/* w ww . ja v a2 s . c o m*/ UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); // UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel"); // UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel"); // UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); } catch (Exception ex) { System.err.println(ex); } JFrame frame = new JFrame("E+ idf TextPanel test"); frame.getContentPane().add(new EPlusEditorPanel()); //frame.getContentPane().add(new EPlusTextPanel (null, null, 1, null, null, null)); frame.setSize(800, 800); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); }
From source file:org.jfree.chart.demo.PanScrollZoomDemo.java
/** * Starting point for the demo.//from www. ja va 2s . c o m * * @param args the command line arguments (ignored). */ public static void main(final String[] args) { try { final String lookAndFeelClassName = WindowsLookAndFeel.class.getName(); UIManager.setLookAndFeel(lookAndFeelClassName); } catch (Exception ex) { System.out.println(ex.getMessage()); } final PanScrollZoomDemo demo = new PanScrollZoomDemo("Pan & Scroll & Zoom - Demo"); demo.pack(); demo.setVisible(true); }
From source file:com.peterbochs.PeterBochsDebugger.java
public static void main(String[] args) { WebServiceUtil.log("peter-bochs", "start", null, null, null); try {//from w w w . j a va2s . c om UIManager.setLookAndFeel("com.peterswing.white.PeterSwingWhiteLookAndFeel"); } catch (Exception e) { e.printStackTrace(); } if (args.length == 0) { String errorMessage = "Wrong number of argument\n\n"; errorMessage += "\nIn Linux/Mac : java -jar peter-bochs-debugger.jar bochs -f bochsrc.bxrc"; errorMessage += "\nIn windows : java -jar peter-bochs-debugger.jar c:\\program files\\bochs2.4.3\\bochsdbg.exe -q -f bochsrc.bxrc"; errorMessage += "\n!!! if using peter-bochs in windows, you need to pass the full path of bochs exe and -q to the parameter. (!!! relative path of bochs exe will not work)"; errorMessage += "\n!!! to use \"experimental feature\", please add \"-debug\" to the parameter list"; System.out.println(errorMessage); JOptionPane.showMessageDialog(null, errorMessage); System.exit(1); } else { if (args[0].equals("-version") || args[0].equals("-v")) { System.out.println(Global.version); System.exit(1); } } for (String str : args) { if (str.contains("bochsrc") || str.contains(".bxrc")) { bochsrc = str; } } String osName = System.getProperty("os.name").toLowerCase(); if (osName.toLowerCase().contains("windows")) { os = OSType.win; } else if (osName.toLowerCase().contains("mac")) { os = OSType.mac; } else { os = OSType.linux; } if (os == OSType.mac) { com.apple.eawt.Application macApp = com.apple.eawt.Application.getApplication(); // System.setProperty("dock:name", "Your Application Name"); macApp.setDockIconImage(new ImageIcon( PeterBochsDebugger.class.getClassLoader().getResource("com/peterbochs/icons/peter.png")) .getImage()); // java.awt.PopupMenu menu = new java.awt.PopupMenu(); // menu.add(new MenuItem("test")); // macApp.setDockMenu(menu); macApp.addApplicationListener(new MacAboutBoxHandler()); } if (ArrayUtils.contains(args, "-debug")) { Global.debug = true; args = (String[]) ArrayUtils.removeElement(args, "-debug"); } else { Global.debug = false; } try { if (PeterBochsDebugger.class.getProtectionDomain().getCodeSource().getLocation().getFile() .endsWith(".jar")) { JarFile jarFile = new JarFile( PeterBochsDebugger.class.getProtectionDomain().getCodeSource().getLocation().getFile()); if (System.getProperty("os.name").toLowerCase().contains("linux")) { if (System.getProperty("os.arch").contains("64")) { if (Global.debug) { System.out.println("Loading linux 64 bits jogl"); } CommonLib.writeFile( jarFile.getInputStream( new JarEntry("com/peterbochs/jogl_dll/linux_amd64/libgluegen-rt.so")), new File("libgluegen-rt.so")); CommonLib.writeFile( jarFile.getInputStream( new JarEntry("com/peterbochs/jogl_dll/linux_amd64/libjogl_awt.so")), new File("libjogl_awt.so")); CommonLib.writeFile( jarFile.getInputStream( new JarEntry("com/peterbochs/jogl_dll/linux_amd64/libjogl_cg.so")), new File("libjogl_cg.so")); CommonLib.writeFile( jarFile.getInputStream( new JarEntry("com/peterbochs/jogl_dll/linux_amd64/libjogl.so")), new File("libjogl.so")); } else { if (Global.debug) { System.out.println("Loading linux 32 bits jogl"); } CommonLib.writeFile( jarFile.getInputStream( new JarEntry("com/peterbochs/jogl_dll/linux_i586/libgluegen-rt.so")), new File("libgluegen-rt.so")); CommonLib.writeFile( jarFile.getInputStream( new JarEntry("com/peterbochs/jogl_dll/linux_i586/libjogl_awt.so")), new File("libjogl_awt.so")); CommonLib.writeFile( jarFile.getInputStream( new JarEntry("com/peterbochs/jogl_dll/linux_i586/libjogl_cg.so")), new File("libjogl_cg.so")); CommonLib.writeFile( jarFile.getInputStream( new JarEntry("com/peterbochs/jogl_dll/linux_i586/libjogl.so")), new File("libjogl.so")); } try { File f = new File("."); Runtime.getRuntime().load(f.getAbsolutePath() + File.separator + "libjogl.so"); System.out.println("Loading " + f.getAbsolutePath() + File.separator + "libjogl.so"); Runtime.getRuntime().load(f.getAbsolutePath() + File.separator + "libjogl_awt.so"); Runtime.getRuntime().load(f.getAbsolutePath() + File.separator + "libjogl_cg.so"); Runtime.getRuntime().load(f.getAbsolutePath() + File.separator + "libgluegen-rt.so"); } catch (UnsatisfiedLinkError e) { e.printStackTrace(); System.err.println("Native code library failed to load.\n" + e); System.err.println( "Solution : Please add \"-Djava.library.path=.\" to start peter-bochs\n" + e); } } else if (System.getProperty("os.name").toLowerCase().contains("windows")) { CommonLib.writeFile(jarFile.getInputStream(new JarEntry("com/peterbochs/exe/PauseBochs.exe")), new File("PauseBochs.exe")); CommonLib.writeFile(jarFile.getInputStream(new JarEntry("com/peterbochs/exe/StopBochs.exe")), new File("StopBochs.exe")); CommonLib.writeFile(jarFile.getInputStream(new JarEntry("com/peterbochs/exe/ndisasm.exe")), new File("ndisasm.exe")); if (System.getProperty("os.arch").contains("64")) { if (Global.debug) { System.out.println("Loading windows 64 bits jogl"); } CommonLib.writeFile( jarFile.getInputStream( new JarEntry("com/peterbochs/jogl_dll/windows_amd64/jogl.dll")), new File("jogl.dll")); CommonLib.writeFile( jarFile.getInputStream( new JarEntry("com/peterbochs/jogl_dll/windows_amd64/jogl_awt.dll")), new File("jogl_awt.dll")); CommonLib.writeFile( jarFile.getInputStream( new JarEntry("com/peterbochs/jogl_dll/windows_amd64/jogl_cg.dll")), new File("jogl_cg.dll")); CommonLib.writeFile( jarFile.getInputStream( new JarEntry("com/peterbochs/jogl_dll/windows_amd64/gluegen-rt.dll")), new File("gluegen-rt.dll")); } else { if (Global.debug) { System.out.println("Loading windows 32 bits jogl"); } CommonLib.writeFile( jarFile.getInputStream( new JarEntry("com/peterbochs/jogl_dll/windows_i586/jogl.dll")), new File("jogl.dll")); CommonLib.writeFile( jarFile.getInputStream( new JarEntry("com/peterbochs/jogl_dll/windows_i586/jogl_awt.dll")), new File("jogl_awt.dll")); CommonLib.writeFile( jarFile.getInputStream( new JarEntry("com/peterbochs/jogl_dll/windows_i586/jogl_cg.dll")), new File("jogl_cg.dll")); CommonLib.writeFile( jarFile.getInputStream( new JarEntry("com/peterbochs/jogl_dll/windows_i586/gluegen-rt.dll")), new File("gluegen-rt.dll")); } try { File f = new File("."); System.load(f.getAbsolutePath() + File.separator + "jogl.dll"); System.load(f.getAbsolutePath() + File.separator + "jogl_awt.dll"); System.load(f.getAbsolutePath() + File.separator + "jogl_cg.dll"); System.load(f.getAbsolutePath() + File.separator + "gluegen-rt.dll"); } catch (UnsatisfiedLinkError e) { e.printStackTrace(); System.err.println("Native code library failed to load.\n" + e); System.err.println( "Solution : Please add \"-Djava.library.path=.\" to start peter-bochs\n" + e); } } } } catch (IOException e) { e.printStackTrace(); } if (ArrayUtils.contains(args, "-loadBreakpoint")) { Setting.getInstance().setLoadBreakpointAtStartup(true); args = (String[]) ArrayUtils.removeElement(args, "-loadBreakpoint"); } else if (ArrayUtils.contains(args, "-loadbreakpoint")) { Setting.getInstance().setLoadBreakpointAtStartup(true); args = (String[]) ArrayUtils.removeElement(args, "-loadbreakpoint"); } for (int x = 0; x < args.length; x++) { if (args[x].toLowerCase().startsWith("-osdebug")) { Global.osDebug = CommonLib.string2long(args[x].replaceAll("-.*=", "")); args = (String[]) ArrayUtils.removeElement(args, args[x]); x = -1; } else if (args[x].toLowerCase().startsWith("-profilingmemoryport")) { Global.profilingMemoryPort = (int) CommonLib.string2long(args[x].replaceAll("-.*=", "")); args = (String[]) ArrayUtils.removeElement(args, args[x]); x = -1; } else if (args[x].toLowerCase().startsWith("-profilingjmpport")) { Global.profilingJmpPort = (int) CommonLib.string2long(args[x].replaceAll("-.*=", "")); args = (String[]) ArrayUtils.removeElement(args, args[x]); x = -1; } else if (args[x].toLowerCase().startsWith("-loadelf")) { Global.elfPaths = args[x].replaceAll("-loadelf=", "").split(","); Setting.getInstance().setLoadSystemMapAtStartup(true); args = (String[]) ArrayUtils.removeElement(args, args[x]); x = -1; } else if (args[x].toLowerCase().startsWith("-loadmap")) { System.out.println("-loadmap is not deprecated, please use -loadelf."); } } arguments = args; SwingUtilities.invokeLater(new Runnable() { public void run() { PeterBochsDebugger inst = new PeterBochsDebugger(); PeterBochsDebugger.instance = inst; new Thread("preventSetVisibleHang thread") { public void run() { try { Thread.sleep(10000); if (preventSetVisibleHang) { System.out.println( "setVisible(true) cause system hang, this probably a swing bug, so force exit, please restart"); System.exit(-1); } } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); if (Global.debug) { System.out.println("setVisible(true)"); } inst.setVisible(true); preventSetVisibleHang = false; if (Global.debug) { System.out.println("end setVisible(true)"); } } }); }
From source file:eu.cassandra.training.gui.MainGUI.java
/** * Constructor of the Training Module GUI. * /*ww w .j av a 2s.co m*/ * @throws UnsupportedLookAndFeelException * @throws IllegalAccessException * @throws InstantiationException * @throws ClassNotFoundException * @throws FileNotFoundException */ public MainGUI() throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException, FileNotFoundException { setForeground(new Color(0, 204, 51)); // Enable the closing of the frame when pressing the x on the upper corner // of the window addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { Utils.cleanFiles(); System.exit(0); } }); // Cleaning temporary files from the temp folder when starting the GUI. // Utils.cleanFiles(); // Change the platforms look and feel to Nimbus LookAndFeel lnf = new javax.swing.plaf.nimbus.NimbusLookAndFeel(); UIManager.put("NimbusLookAndFeel", Color.GREEN); UIManager.setLookAndFeel(lnf); // Setting the basic attributes of the Training Module GUI setTitle("Training Module (BETA)"); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 1228, 799); // Creating the menu bar and adding the menu items JMenuBar menuBar = new JMenuBar(); setJMenuBar(menuBar); JMenu mnNewMenu = new JMenu("File"); menuBar.add(mnNewMenu); JMenuItem mntmExit = new JMenuItem("Exit"); mntmExit.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { Utils.cleanFiles(); System.exit(0); } }); mnNewMenu.add(mntmExit); JMenu mnExit = new JMenu("Help"); menuBar.add(mnExit); JMenuItem mntmManual = new JMenuItem("Manual"); mnExit.add(mntmManual); JMenuItem mntmAbout = new JMenuItem("About"); mnExit.add(mntmAbout); contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); // Adding the tabbed pane to the content pane final JTabbedPane tabbedPane = new JTabbedPane(JTabbedPane.TOP); GroupLayout gl_contentPane = new GroupLayout(contentPane); gl_contentPane.setHorizontalGroup(gl_contentPane.createParallelGroup(Alignment.LEADING) .addComponent(tabbedPane, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 1202, Short.MAX_VALUE)); gl_contentPane.setVerticalGroup(gl_contentPane.createParallelGroup(Alignment.LEADING) .addGroup(gl_contentPane.createSequentialGroup() .addComponent(tabbedPane, GroupLayout.PREFERRED_SIZE, 736, GroupLayout.PREFERRED_SIZE) .addContainerGap(47, Short.MAX_VALUE))); // TABS // final JPanel importTab = new JPanel(); tabbedPane.addTab("Import Data", null, importTab, null); tabbedPane.setDisplayedMnemonicIndexAt(0, 0); tabbedPane.setEnabledAt(0, true); importTab.setLayout(null); final JPanel trainingTab = new JPanel(); tabbedPane.addTab("Train Activity Models", null, trainingTab, null); tabbedPane.setDisplayedMnemonicIndexAt(1, 1); tabbedPane.setEnabledAt(1, false); trainingTab.setLayout(null); final JPanel createResponseTab = new JPanel(); tabbedPane.addTab("Create Response Models", null, createResponseTab, null); tabbedPane.setEnabledAt(2, false); createResponseTab.setLayout(null); // RESPONSE MODEL TAB // final JPanel responseParametersPanel = new JPanel(); responseParametersPanel.setLayout(null); responseParametersPanel.setBorder( new TitledBorder(null, "Response Parameters", TitledBorder.LEADING, TitledBorder.TOP, null, null)); responseParametersPanel.setBounds(6, 6, 394, 271); createResponseTab.add(responseParametersPanel); final JPanel activityModelSelectionPanel = new JPanel(); activityModelSelectionPanel.setLayout(null); activityModelSelectionPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Activity Model Selection", TitledBorder.LEADING, TitledBorder.TOP, null, null)); activityModelSelectionPanel.setBounds(6, 516, 394, 192); createResponseTab.add(activityModelSelectionPanel); final JPanel responsePanel = new JPanel(); responsePanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Activity Model Change Preview", TitledBorder.LEADING, TitledBorder.TOP, null, null)); responsePanel.setBounds(417, 6, 770, 385); createResponseTab.add(responsePanel); responsePanel.setLayout(new BorderLayout(0, 0)); final JPanel pricingPreviewPanel = new JPanel(); pricingPreviewPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Pricing Scheme Preview", TitledBorder.LEADING, TitledBorder.TOP, null, null)); pricingPreviewPanel.setBounds(417, 438, 770, 259); createResponseTab.add(pricingPreviewPanel); pricingPreviewPanel.setLayout(new BorderLayout(0, 0)); final JPanel pricingSchemePanel = new JPanel(); pricingSchemePanel.setLayout(null); pricingSchemePanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Pricing Scheme Selection", TitledBorder.LEADING, TitledBorder.TOP, null, null)); pricingSchemePanel.setBounds(6, 274, 394, 243); createResponseTab.add(pricingSchemePanel); // ///////////////// // RESPONSE TAB // // //////////////// // RESPONSE PARAMETERS // final JLabel lblSensitivity = new JLabel("Sensitivity"); lblSensitivity.setBounds(10, 28, 78, 16); responseParametersPanel.add(lblSensitivity); final JSlider sensitivitySlider = new JSlider(); sensitivitySlider.setPaintLabels(true); sensitivitySlider.setSnapToTicks(true); sensitivitySlider.setPaintTicks(true); sensitivitySlider.setMinorTickSpacing(10); sensitivitySlider.setMajorTickSpacing(10); sensitivitySlider.setBounds(111, 28, 214, 45); responseParametersPanel.add(sensitivitySlider); final JLabel lblAwareness = new JLabel("Awareness"); lblAwareness.setBounds(10, 79, 78, 16); responseParametersPanel.add(lblAwareness); final JSlider awarenessSlider = new JSlider(); awarenessSlider.setPaintLabels(true); awarenessSlider.setPaintTicks(true); awarenessSlider.setMajorTickSpacing(10); awarenessSlider.setMinorTickSpacing(10); awarenessSlider.setSnapToTicks(true); awarenessSlider.setBounds(111, 79, 214, 45); responseParametersPanel.add(awarenessSlider); final JLabel label_7 = new JLabel("Response Model"); label_7.setBounds(10, 153, 103, 16); responseParametersPanel.add(label_7); final JRadioButton optimalCaseRadioButton = new JRadioButton("Optimal Case Scenario"); responseModelButtonGroup.add(optimalCaseRadioButton); optimalCaseRadioButton.setBounds(111, 131, 170, 18); responseParametersPanel.add(optimalCaseRadioButton); final JRadioButton normalCaseRadioButton = new JRadioButton("Normal Case Scenario"); normalCaseRadioButton.setSelected(true); responseModelButtonGroup.add(normalCaseRadioButton); normalCaseRadioButton.setBounds(111, 152, 170, 18); responseParametersPanel.add(normalCaseRadioButton); final JRadioButton discreteCaseRadioButton = new JRadioButton("Discrete Case Scenario"); discreteCaseRadioButton.setSelected(true); responseModelButtonGroup.add(discreteCaseRadioButton); discreteCaseRadioButton.setBounds(111, 173, 170, 18); responseParametersPanel.add(discreteCaseRadioButton); final JButton previewResponseButton = new JButton("Preview Response Model"); previewResponseButton.setEnabled(false); previewResponseButton.setBounds(24, 198, 157, 28); responseParametersPanel.add(previewResponseButton); final JButton createResponseButton = new JButton("Create Response Model"); createResponseButton.setEnabled(false); createResponseButton.setBounds(191, 198, 162, 28); responseParametersPanel.add(createResponseButton); final JButton createResponseAllButton = new JButton("Create Response All"); createResponseAllButton.setEnabled(false); createResponseAllButton.setBounds(111, 232, 157, 28); responseParametersPanel.add(createResponseAllButton); // SELECT ACTIVITY MODEL // final JLabel lblSelectedActivity = new JLabel("Selected Activity"); lblSelectedActivity.setBounds(10, 21, 130, 16); activityModelSelectionPanel.add(lblSelectedActivity); JScrollPane activityListScrollPane = new JScrollPane(); activityListScrollPane.setBounds(20, 39, 355, 143); activityModelSelectionPanel.add(activityListScrollPane); final JList<String> activitySelectList = new JList<String>(); activityListScrollPane.setViewportView(activitySelectList); activitySelectList.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null)); final JButton commitButton = new JButton("Commit"); commitButton.setEnabled(false); commitButton.setBounds(151, 209, 89, 23); pricingSchemePanel.add(commitButton); JLabel lblBasicSchema = new JLabel("Basic Schema (Start-End-Value)"); lblBasicSchema.setBounds(10, 18, 182, 14); pricingSchemePanel.add(lblBasicSchema); JLabel lblNewSchemastart = new JLabel("New Schema (Start-End-Value)"); lblNewSchemastart.setBounds(197, 18, 177, 14); pricingSchemePanel.add(lblNewSchemastart); JScrollPane basicPricingSchemeScrollPane = new JScrollPane(); basicPricingSchemeScrollPane.setBounds(10, 43, 177, 161); pricingSchemePanel.add(basicPricingSchemeScrollPane); final JTextPane basicPricingSchemePane = new JTextPane(); basicPricingSchemeScrollPane.setViewportView(basicPricingSchemePane); basicPricingSchemePane.setText("00:00-23:59-0.05"); JScrollPane newPricingScrollPane = new JScrollPane(); newPricingScrollPane.setBounds(197, 43, 177, 161); pricingSchemePanel.add(newPricingScrollPane); final JTextPane newPricingSchemePane = new JTextPane(); newPricingScrollPane.setViewportView(newPricingSchemePane); JPanel buttonPanel = new JPanel(); buttonPanel.setBounds(682, 390, 265, 33); createResponseTab.add(buttonPanel); final JButton dailyResponseButton = new JButton("Daily Times"); dailyResponseButton.setEnabled(false); buttonPanel.add(dailyResponseButton); final JButton startResponseButton = new JButton("Start Time"); startResponseButton.setEnabled(false); buttonPanel.add(startResponseButton); final JPanel exportTab = new JPanel(); tabbedPane.addTab("Export Models", null, exportTab, null); tabbedPane.setEnabledAt(3, false); exportTab.setLayout(null); // PANELS // // DATA IMPORT TAB // final JPanel dataFilePanel = new JPanel(); dataFilePanel .setBorder(new TitledBorder(null, "Data File", TitledBorder.LEADING, TitledBorder.TOP, null, null)); dataFilePanel.setBounds(6, 6, 622, 284); importTab.add(dataFilePanel); dataFilePanel.setLayout(null); final JPanel disaggregationPanel = new JPanel(); disaggregationPanel.setLayout(null); disaggregationPanel.setBorder( new TitledBorder(null, "Disaggregation", TitledBorder.LEADING, TitledBorder.TOP, null, null)); disaggregationPanel.setBounds(629, 6, 567, 284); importTab.add(disaggregationPanel); final JPanel dataReviewPanel = new JPanel(); dataReviewPanel.setBorder( new TitledBorder(null, "Data Preview", TitledBorder.LEADING, TitledBorder.TOP, null, null)); dataReviewPanel.setBounds(6, 293, 622, 407); importTab.add(dataReviewPanel); dataReviewPanel.setLayout(new BorderLayout(0, 0)); final JPanel consumptionModelPanel = new JPanel(); consumptionModelPanel.setBounds(629, 293, 567, 407); importTab.add(consumptionModelPanel); consumptionModelPanel.setBorder( new TitledBorder(null, "Consumption Model", TitledBorder.LEADING, TitledBorder.TOP, null, null)); consumptionModelPanel.setLayout(new BorderLayout(0, 0)); // TRAINING ACTIVITY TAB // final JPanel trainingParametersPanel = new JPanel(); trainingParametersPanel.setLayout(null); trainingParametersPanel.setBorder( new TitledBorder(null, "Training Parameters", TitledBorder.LEADING, TitledBorder.TOP, null, null)); trainingParametersPanel.setBounds(6, 6, 621, 256); trainingTab.add(trainingParametersPanel); final JPanel applianceSelectionPanel = new JPanel(); applianceSelectionPanel.setLayout(null); applianceSelectionPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Appliance/Activity Selection", TitledBorder.LEADING, TitledBorder.TOP, null, null)); applianceSelectionPanel.setBounds(630, 6, 557, 256); trainingTab.add(applianceSelectionPanel); final JPanel expectedPowerPanel = new JPanel(); expectedPowerPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Expected Power Preview", TitledBorder.LEADING, TitledBorder.TOP, null, null)); expectedPowerPanel.setBounds(630, 261, 557, 447); trainingTab.add(expectedPowerPanel); expectedPowerPanel.setLayout(new BorderLayout(0, 0)); contentPane.setLayout(gl_contentPane); // EXPORT TAB // JPanel modelExportPanel = new JPanel(); modelExportPanel.setLayout(null); modelExportPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Model Export Selection", TitledBorder.LEADING, TitledBorder.TOP, null, null)); modelExportPanel.setBounds(10, 11, 596, 267); exportTab.add(modelExportPanel); final JPanel exportPreviewPanel = new JPanel(); exportPreviewPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Export Model Preview", TitledBorder.LEADING, TitledBorder.TOP, null, null)); exportPreviewPanel.setBounds(10, 310, 1187, 387); exportTab.add(exportPreviewPanel); exportPreviewPanel.setLayout(new BorderLayout(0, 0)); JPanel exportButtonsPanel = new JPanel(); exportButtonsPanel.setBounds(322, 279, 536, 33); exportTab.add(exportButtonsPanel); JPanel connectionPanel = new JPanel(); connectionPanel.setLayout(null); connectionPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Connection Properties", TitledBorder.LEADING, TitledBorder.TOP, null, null)); connectionPanel.setBounds(606, 11, 581, 267); exportTab.add(connectionPanel); // COMPONENTS // // IMPORT TAB // // DATA IMPORT // final JLabel lblSource = new JLabel("Data Source:"); lblSource.setBounds(23, 47, 71, 16); dataFilePanel.add(lblSource); final JTextField pathField = new JTextField(); pathField.setEditable(false); pathField.setBounds(99, 41, 405, 28); dataFilePanel.add(pathField); pathField.setColumns(10); final JButton dataBrowseButton = new JButton("Browse"); dataBrowseButton.setBounds(516, 41, 87, 28); dataFilePanel.add(dataBrowseButton); final JButton resetButton = new JButton("Reset"); resetButton.setBounds(516, 81, 87, 28); dataFilePanel.add(resetButton); final JLabel lblDataMeasurementsFrom = new JLabel("Data Measurements From:"); lblDataMeasurementsFrom.setBounds(23, 90, 154, 16); dataFilePanel.add(lblDataMeasurementsFrom); final JRadioButton singleApplianceRadioButton = new JRadioButton("Single Appliance"); singleApplianceRadioButton.setEnabled(false); dataMeasurementsButtonGroup.add(singleApplianceRadioButton); singleApplianceRadioButton.setBounds(242, 110, 115, 18); dataFilePanel.add(singleApplianceRadioButton); final JRadioButton installationRadioButton = new JRadioButton("Installation"); installationRadioButton.setSelected(true); installationRadioButton.setEnabled(false); dataMeasurementsButtonGroup.add(installationRadioButton); installationRadioButton.setBounds(242, 89, 115, 18); dataFilePanel.add(installationRadioButton); final JLabel labelConsumptionModel = new JLabel("Consumption Model:"); labelConsumptionModel.setBounds(23, 179, 120, 16); dataFilePanel.add(labelConsumptionModel); final JButton importDataButton = new JButton("Import Data"); importDataButton.setEnabled(false); importDataButton.setBounds(23, 237, 126, 28); dataFilePanel.add(importDataButton); final JButton disaggregateButton = new JButton("Disaggregate"); disaggregateButton.setEnabled(false); disaggregateButton.setBounds(216, 237, 147, 28); dataFilePanel.add(disaggregateButton); final JButton createEventsButton = new JButton("Create Events Dataset"); createEventsButton.setEnabled(false); createEventsButton.setBounds(422, 237, 181, 28); dataFilePanel.add(createEventsButton); final JTextField consumptionPathField = new JTextField(); consumptionPathField.setEnabled(false); consumptionPathField.setEditable(false); consumptionPathField.setColumns(10); consumptionPathField.setBounds(99, 197, 405, 28); dataFilePanel.add(consumptionPathField); final JButton consumptionBrowseButton = new JButton("Browse"); consumptionBrowseButton.setEnabled(false); consumptionBrowseButton.setBounds(516, 197, 87, 28); dataFilePanel.add(consumptionBrowseButton); JLabel lblTypeOfMeasurements = new JLabel("Type of Measurements"); lblTypeOfMeasurements.setBounds(23, 141, 154, 16); dataFilePanel.add(lblTypeOfMeasurements); final JRadioButton activePowerRadioButton = new JRadioButton("Active Power (P)"); powerButtonGroup.add(activePowerRadioButton); activePowerRadioButton.setEnabled(false); activePowerRadioButton.setBounds(242, 140, 115, 18); dataFilePanel.add(activePowerRadioButton); final JRadioButton activeAndReactivePowerRadioButton = new JRadioButton("Active and Reactive Power (P, Q)"); activeAndReactivePowerRadioButton.setSelected(true); powerButtonGroup.add(activeAndReactivePowerRadioButton); activeAndReactivePowerRadioButton.setEnabled(false); activeAndReactivePowerRadioButton.setBounds(242, 161, 262, 18); dataFilePanel.add(activeAndReactivePowerRadioButton); // ////////////////// // DISAGGREGATION // // ///////////////// final JLabel lblAppliancesDetected = new JLabel("Detected Appliances "); lblAppliancesDetected.setBounds(18, 33, 130, 16); disaggregationPanel.add(lblAppliancesDetected); JScrollPane scrollPane_2 = new JScrollPane(); scrollPane_2.setBounds(145, 31, 396, 231); disaggregationPanel.add(scrollPane_2); final JList<String> detectedApplianceList = new JList<String>(); scrollPane_2.setViewportView(detectedApplianceList); detectedApplianceList.setEnabled(false); detectedApplianceList.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null)); // //////////////// // TRAINING TAB // // //////////////// // TRAINING PARAMETERS // final JLabel label_1 = new JLabel("Times Per Day"); label_1.setBounds(19, 40, 103, 16); trainingParametersPanel.add(label_1); final JRadioButton timesHistogramRadioButton = new JRadioButton("Histogram"); timesHistogramRadioButton.setSelected(true); timesDailyButtonGroup.add(timesHistogramRadioButton); timesHistogramRadioButton.setBounds(160, 38, 87, 18); trainingParametersPanel.add(timesHistogramRadioButton); final JRadioButton timesNormalRadioButton = new JRadioButton("Normal Distribution"); timesNormalRadioButton.setEnabled(false); timesDailyButtonGroup.add(timesNormalRadioButton); timesNormalRadioButton.setBounds(304, 40, 137, 18); trainingParametersPanel.add(timesNormalRadioButton); JRadioButton timesGaussianRadioButton = new JRadioButton("Gaussian Mixture"); timesGaussianRadioButton.setEnabled(false); timesDailyButtonGroup.add(timesGaussianRadioButton); timesGaussianRadioButton.setBounds(478, 38, 137, 18); trainingParametersPanel.add(timesGaussianRadioButton); final JLabel label_2 = new JLabel("Start Time"); label_2.setBounds(19, 133, 103, 16); trainingParametersPanel.add(label_2); final JRadioButton startHistogramRadioButton = new JRadioButton("Histogram"); startHistogramRadioButton.setSelected(true); startTimeButtonGroup.add(startHistogramRadioButton); startHistogramRadioButton.setBounds(160, 131, 87, 18); trainingParametersPanel.add(startHistogramRadioButton); final JRadioButton startNormalRadioButton = new JRadioButton("Normal Distribution"); // startNormalRadioButton.setEnabled(false); startTimeButtonGroup.add(startNormalRadioButton); startNormalRadioButton.setBounds(304, 133, 137, 18); trainingParametersPanel.add(startNormalRadioButton); final JRadioButton startGaussianRadioButton = new JRadioButton("Gaussian Mixture"); startGaussianRadioButton.setSelected(true); startTimeButtonGroup.add(startGaussianRadioButton); startGaussianRadioButton.setBounds(478, 131, 137, 18); trainingParametersPanel.add(startGaussianRadioButton); final JLabel label_3 = new JLabel("Duration"); label_3.setBounds(19, 86, 103, 16); trainingParametersPanel.add(label_3); final JRadioButton durationHistogramRadioButton = new JRadioButton("Histogram"); durationHistogramRadioButton.setSelected(true); durationButtonGroup.add(durationHistogramRadioButton); durationHistogramRadioButton.setBounds(160, 84, 87, 18); trainingParametersPanel.add(durationHistogramRadioButton); final JRadioButton durationNormalRadioButton = new JRadioButton("Normal Distribution"); durationNormalRadioButton.setSelected(true); durationButtonGroup.add(durationNormalRadioButton); durationNormalRadioButton.setBounds(304, 86, 137, 18); trainingParametersPanel.add(durationNormalRadioButton); final JRadioButton durationGaussianRadioButton = new JRadioButton("Gaussian Mixture"); durationButtonGroup.add(durationGaussianRadioButton); durationGaussianRadioButton.setBounds(478, 84, 137, 18); trainingParametersPanel.add(durationGaussianRadioButton); final JButton trainingButton = new JButton("Train"); trainingButton.setBounds(125, 194, 115, 28); trainingParametersPanel.add(trainingButton); final JButton trainAllButton = new JButton("Train All"); trainAllButton.setBounds(366, 194, 115, 28); trainingParametersPanel.add(trainAllButton); // APPLIANCE SELECTION // final JLabel label_4 = new JLabel("Selected Appliance"); label_4.setBounds(18, 33, 130, 16); applianceSelectionPanel.add(label_4); JScrollPane scrollPane_1 = new JScrollPane(); scrollPane_1.setBounds(128, 29, 419, 216); applianceSelectionPanel.add(scrollPane_1); final JList<String> selectedApplianceList = new JList<String>(); scrollPane_1.setViewportView(selectedApplianceList); selectedApplianceList.setEnabled(false); selectedApplianceList.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null)); // DISTRIBUTION SELECTION // JPanel distributionSelectionPanel = new JPanel(); distributionSelectionPanel.setBounds(80, 261, 482, 33); trainingTab.add(distributionSelectionPanel); final JButton dailyTimesButton = new JButton("Daily Times"); dailyTimesButton.setEnabled(false); distributionSelectionPanel.add(dailyTimesButton); final JButton durationButton = new JButton("Duration"); durationButton.setEnabled(false); distributionSelectionPanel.add(durationButton); final JButton startTimeButton = new JButton("Start Time"); startTimeButton.setEnabled(false); distributionSelectionPanel.add(startTimeButton); final JButton startTimeBinnedButton = new JButton("Start Time Binned"); startTimeBinnedButton.setEnabled(false); distributionSelectionPanel.add(startTimeBinnedButton); final JPanel distributionPreviewPanel = new JPanel(); distributionPreviewPanel.setBorder(new TitledBorder(UIManager.getBorder("TitledBorder.border"), "Distribution Preview", TitledBorder.LEADING, TitledBorder.TOP, null, null)); distributionPreviewPanel.setBounds(6, 299, 621, 409); trainingTab.add(distributionPreviewPanel); distributionPreviewPanel.setLayout(new BorderLayout(0, 0)); // ////////////////// // EXPORT TAB /////// // ///////////////// JLabel exportModelLabel = new JLabel("Select Model"); exportModelLabel.setBounds(10, 34, 151, 16); modelExportPanel.add(exportModelLabel); JScrollPane scrollPane = new JScrollPane(); scrollPane.setBounds(83, 32, 503, 212); modelExportPanel.add(scrollPane); final JList<String> exportModelList = new JList<String>(); scrollPane.setViewportView(exportModelList); exportModelList.setEnabled(false); exportModelList.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null)); // EXPORT TAB // final JButton exportDailyButton = new JButton("Daily Times"); exportDailyButton.setEnabled(false); exportButtonsPanel.add(exportDailyButton); final JButton exportDurationButton = new JButton("Duration"); exportDurationButton.setEnabled(false); exportButtonsPanel.add(exportDurationButton); final JButton exportStartButton = new JButton("Start Time"); exportStartButton.setEnabled(false); exportButtonsPanel.add(exportStartButton); final JButton exportStartBinnedButton = new JButton("Start Time Binned"); exportStartBinnedButton.setEnabled(false); exportButtonsPanel.add(exportStartBinnedButton); final JButton exportExpectedPowerButton = new JButton("Expected Power"); exportExpectedPowerButton.setEnabled(false); exportButtonsPanel.add(exportExpectedPowerButton); JLabel usernameLabel = new JLabel("Username:"); usernameLabel.setBounds(46, 27, 71, 16); connectionPanel.add(usernameLabel); final JTextField usernameTextField; usernameTextField = new JTextField(); usernameTextField.setText("user"); usernameTextField.setColumns(10); usernameTextField.setBounds(122, 21, 405, 28); connectionPanel.add(usernameTextField); final JButton exportButton = new JButton("Export Entity"); exportButton.setEnabled(false); exportButton.setBounds(46, 178, 147, 28); connectionPanel.add(exportButton); final JButton exportAllBaseButton = new JButton("Export All Base"); exportAllBaseButton.setEnabled(false); exportAllBaseButton.setBounds(203, 178, 177, 28); connectionPanel.add(exportAllBaseButton); final JButton exportAllResponseButton = new JButton("Export All Response"); exportAllResponseButton.setEnabled(false); exportAllResponseButton.setBounds(390, 178, 181, 28); connectionPanel.add(exportAllResponseButton); JLabel passwordLabel = new JLabel("Password:"); passwordLabel.setBounds(46, 62, 71, 16); connectionPanel.add(passwordLabel); JLabel UrlLabel = new JLabel("URL:"); UrlLabel.setBounds(46, 105, 71, 16); connectionPanel.add(UrlLabel); final JTextField urlTextField; urlTextField = new JTextField(); urlTextField.setText("https://160.40.50.233:8443/cassandra/api"); urlTextField.setColumns(10); urlTextField.setBounds(122, 99, 405, 28); connectionPanel.add(urlTextField); final JButton connectButton = new JButton("Connect"); connectButton.setEnabled(false); connectButton.setBounds(217, 138, 147, 28); connectionPanel.add(connectButton); final JPasswordField passwordField; passwordField = new JPasswordField(); passwordField.setBounds(122, 60, 405, 28); connectionPanel.add(passwordField); final JTextField householdNameTextField; householdNameTextField = new JTextField(); householdNameTextField.setEnabled(false); householdNameTextField.setBounds(166, 225, 405, 31); connectionPanel.add(householdNameTextField); householdNameTextField.setColumns(10); final JLabel householdNameLabel = new JLabel("Export Household Name:"); householdNameLabel.setBounds(24, 233, 147, 14); connectionPanel.add(householdNameLabel); JButton btnOpenPlatform = new JButton("Open Platform"); btnOpenPlatform.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { Desktop.getDesktop() .browse(new URL("https://cassandra.iti.gr:8443/cassandra/app.html").toURI()); } catch (Exception e) { e.printStackTrace(); } } }); btnOpenPlatform.setBounds(401, 138, 147, 28); connectionPanel.add(btnOpenPlatform); // ////////////////// // ACTIONS /////// // ///////////////// // IMPORT TAB // // DATA IMPORT //// dataBrowseButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the browse button to * input the data file on the Data File panel of the Import Data tab. * */ @Override public void actionPerformed(ActionEvent e) { // Opens the browse panel to find the data set file JFileChooser fc = new JFileChooser("./"); // Adds a filter to the type of files acceptable for selection fc.setFileSelectionMode(JFileChooser.FILES_ONLY); fc.setFileFilter(new MyFilter2()); int returnVal = fc.showOpenDialog(contentPane); // After choosing the file some of the options in the Data File panel // are unlocked if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); pathField.setText(file.getAbsolutePath()); importDataButton.setEnabled(true); activePowerRadioButton.setEnabled(true); activeAndReactivePowerRadioButton.setEnabled(true); installationRadioButton.setEnabled(true); singleApplianceRadioButton.setEnabled(true); } } }); consumptionBrowseButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the browse button to * input the consumption model file on the Data File panel of the Import * Data tab. * */ @Override public void actionPerformed(ActionEvent e) { // Opens the browse panel to find the consumption model file JFileChooser fc = new JFileChooser("./"); // Adds a filter to the type of files acceptable for selection fc.setFileSelectionMode(JFileChooser.FILES_ONLY); fc.setFileFilter(new MyFilter()); int returnVal = fc.showOpenDialog(contentPane); // After choosing the file some of the options in the Data File panel // are unlocked if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); consumptionPathField.setText(file.getAbsolutePath()); createEventsButton.setEnabled(true); } } }); resetButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the reset button * on the Data File panel of the Import Data tab. All the imported and * created entities are removed and the Training Module goes back to its * initial state. * */ @Override public void actionPerformed(ActionEvent e) { // Cleaning the Import Data tab components pathField.setText(""); consumptionPathField.setText(""); importDataButton.setEnabled(false); disaggregateButton.setEnabled(false); createEventsButton.setEnabled(false); installation = new Installation(); dataBrowseButton.setEnabled(true); consumptionBrowseButton.setEnabled(false); installationRadioButton.setEnabled(false); installationRadioButton.setSelected(true); singleApplianceRadioButton.setEnabled(false); activePowerRadioButton.setEnabled(false); activeAndReactivePowerRadioButton.setEnabled(false); activeAndReactivePowerRadioButton.setSelected(true); dataReviewPanel.removeAll(); dataReviewPanel.updateUI(); consumptionModelPanel.removeAll(); consumptionModelPanel.updateUI(); detectedApplianceList.setSelectedIndex(-1); detectedAppliances.clear(); detectedApplianceList.setListData(new String[0]); detectedApplianceList.repaint(); // Cleaning the Training Activity Models tab components distributionPreviewPanel.removeAll(); distributionPreviewPanel.updateUI(); expectedPowerPanel.removeAll(); expectedPowerPanel.updateUI(); selectedApplianceList.setSelectedIndex(-1); selectedAppliances.clear(); selectedApplianceList.setListData(new String[0]); selectedApplianceList.repaint(); timesHistogramRadioButton.setSelected(true); durationNormalRadioButton.setSelected(true); startGaussianRadioButton.setSelected(true); // Cleaning the Create Response Models tab components sensitivitySlider.setValue(50); awarenessSlider.setValue(50); normalCaseRadioButton.setSelected(true); previewResponseButton.setEnabled(false); createResponseButton.setEnabled(false); createResponseAllButton.setEnabled(false); pricingPreviewPanel.removeAll(); pricingPreviewPanel.updateUI(); responsePanel.removeAll(); responsePanel.updateUI(); activitySelectList.setSelectedIndex(-1); activityModels.clear(); activitySelectList.setListData(new String[0]); activitySelectList.repaint(); basicPricingSchemePane.setText("00:00-23:59-0.05"); newPricingSchemePane.setText(""); commitButton.setEnabled(false); dailyResponseButton.setEnabled(false); startResponseButton.setEnabled(false); // Cleaning the Export Models tab components exportModelList.setSelectedIndex(-1); exportModels.clear(); exportModelList.setListData(new String[0]); exportModelList.repaint(); exportPreviewPanel.removeAll(); exportPreviewPanel.updateUI(); exportDailyButton.setEnabled(false); exportDurationButton.setEnabled(false); exportStartButton.setEnabled(false); exportStartBinnedButton.setEnabled(false); exportExpectedPowerButton.setEnabled(false); exportButton.setEnabled(false); exportAllBaseButton.setEnabled(false); exportAllResponseButton.setEnabled(false); householdNameTextField.setEnabled(false); // Disabling the necessary tabs tabbedPane.setEnabledAt(1, false); tabbedPane.setEnabledAt(2, false); tabbedPane.setEnabledAt(3, false); // Clearing the arrayList in need tempAppliances.clear(); tempActivities.clear(); // Removing temporary files Utils.cleanFiles(); trained = false; } }); singleApplianceRadioButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Single Appliance * radio button on the Data File panel of the Import Data tab. */ @Override public void actionPerformed(ActionEvent e) { consumptionPathField.setEnabled(false); consumptionBrowseButton.setEnabled(false); consumptionPathField.setText(""); } }); installationRadioButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Installation * radio button on the Data File panel of the Import Data tab. */ @Override public void actionPerformed(ActionEvent e) { consumptionPathField.setEnabled(false); consumptionBrowseButton.setEnabled(false); consumptionPathField.setText(""); } }); importDataButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Import Data * button on the Data File panel of the Import Data tab. */ @Override public void actionPerformed(ActionEvent e) { Component root = SwingUtilities.getRoot((JButton) e.getSource()); try { root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); // Change the state of some components installationRadioButton.setEnabled(false); singleApplianceRadioButton.setEnabled(false); importDataButton.setEnabled(false); dataBrowseButton.setEnabled(false); activePowerRadioButton.setEnabled(false); activeAndReactivePowerRadioButton.setEnabled(false); // Check if both active and reactive activeOnly data set are available boolean power = activePowerRadioButton.isSelected(); int parse = -1; // Parsing the measurements file try { parse = Utils.parseMeasurementsFile(pathField.getText(), power); } catch (IOException e2) { e2.printStackTrace(); } // If everything is OK if (parse == -1) { try { // Creating new installation installation = new Installation(pathField.getText(), power); } catch (IOException e2) { e2.printStackTrace(); } // Show the measurements in the preview chart ChartPanel chartPanel = null; try { chartPanel = installation.measurementsChart(); } catch (IOException e1) { e1.printStackTrace(); } dataReviewPanel.add(chartPanel, BorderLayout.CENTER); dataReviewPanel.validate(); disaggregateButton.setEnabled(false); createEventsButton.setEnabled(false); // Enable the appropriate buttons given source of measurements if (installationRadioButton.isSelected()) { disaggregateButton.setEnabled(true); } else if (singleApplianceRadioButton.isSelected()) { consumptionPathField.setEnabled(true); consumptionBrowseButton.setEnabled(true); } // Add installation to the export models list exportModels.addElement(installation.toString()); exportModels.addElement(installation.getPerson().getName()); householdNameTextField.setText(installation.getName()); // Enable Export Models tab exportModelList.setEnabled(true); exportModelList.setModel(exportModels); tabbedPane.setEnabledAt(3, true); } // In case of an error during the measurement parsing show the line of // error and reset settings. else { JFrame error = new JFrame(); JOptionPane.showMessageDialog(error, "Parsing measurements file failed. The problem seems to be in line " + parse + ".Check the selected buttons and the file provided and try again.", "Inane error", JOptionPane.ERROR_MESSAGE); resetButton.doClick(); } } finally { root.setCursor(Cursor.getDefaultCursor()); } } }); disaggregateButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Disaggregate * button on the Data File panel of the Import Data tab in order to * automatically analyse the data set and extract the appliances and * activities within. */ @Override public void actionPerformed(ActionEvent e) { Component root = SwingUtilities.getRoot((JButton) e.getSource()); try { root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); // Get auxiliary files containing appliances and activities which are // the output of the disaggregation process. String filename = pathField.getText(); File file = new File(filename); String folder = file.getParent() + "/"; String fileNameWithExtension = file.getName(); String fileName = file.getName().substring(0, file.getName().length() - 4); filename = pathField.getText().substring(0, pathField.getText().length() - 4); File appliancesFile = new File(Constants.resultFolder + fileName + "ApplianceList.csv"); File activitiesFile = new File(Constants.resultFolder + fileName + "ActivityList.csv"); if ((Constants.USE_FILES == false) || (!appliancesFile.exists() && !activitiesFile.exists())) { try { System.out.println("IN!!!"); Disaggregate dis = new Disaggregate(folder, fileNameWithExtension); appliancesFile = new File(Constants.resultFolder + fileName + "ApplianceList.csv"); activitiesFile = new File(Constants.resultFolder + fileName + "ActivityList.csv"); } catch (Exception e2) { System.out.println("Missing File"); e2.printStackTrace(); } } // If these exist, disaggregation was successful and the procedure can // continue if (appliancesFile.exists() && activitiesFile.exists()) { // Read appliance file and start appliance parsing Scanner input = null; try { input = new Scanner(appliancesFile); } catch (FileNotFoundException e1) { e1.printStackTrace(); } String nextLine; String[] line; while (input.hasNext()) { nextLine = input.nextLine(); line = nextLine.split(","); String name = line[1] + " " + line[0]; // String activity = line[1]; String activity = name; String[] temp = line[0].split(" "); String type = ""; if (temp.length == 1) type = temp[0]; else { for (int i = 0; i < temp.length - 1; i++) type += temp[i] + " "; type = type.trim(); } boolean refFlag = activity.contains("Refrigeration"); boolean wmFlag = name.contains("Washing"); double p = 0, q = 0; int distance = 0, duration = 0; if (refFlag) { p = Double.parseDouble(line[2]); q = Double.parseDouble(line[3]); duration = Integer.parseInt(line[4]); distance = Integer.parseInt(line[5]); // For each appliance found in the file, an temporary Appliance // Entity is created. tempAppliances.add(new ApplianceTemp(name, installation.getName(), type, activity, p, q, duration, distance)); } else if (wmFlag) { double[] pValues = new double[line.length / 2 - 1]; double[] qValues = new double[line.length / 2 - 1]; // For each appliance found in the file, an temporary Appliance // Entity is created. for (int i = 0; i < pValues.length; i++) { pValues[i] = Double.parseDouble(line[2 + 2 * i]); qValues[i] = Double.parseDouble(line[3 + 2 * i]); } tempAppliances.add(new ApplianceTemp(name, installation.getName(), type, activity, pValues, qValues)); } else { p = Double.parseDouble(line[2]); q = Double.parseDouble(line[3]); // For each appliance found in the file, an temporary Appliance // Entity is created. tempAppliances .add(new ApplianceTemp(name, installation.getName(), type, activity, p, q)); } } System.out.println("Appliances:" + tempAppliances.size()); input.close(); // Read activity file and start activity parsing try { input = new Scanner(activitiesFile); } catch (FileNotFoundException e1) { System.out.println("Problem with activity file."); e1.printStackTrace(); } while (input.hasNext()) { nextLine = input.nextLine(); line = nextLine.split(","); // System.out.println(Arrays.toString(line)); // String name = line[0]; // String activity = line[1]; String activity = line[1] + " " + line[0]; String type = line[1]; int start = Integer.parseInt(line[2]); int end = Integer.parseInt(line[3]); // Search for existing activity int activityIndex = findActivity(activity); // if not found, create a new one if (activityIndex == -1) { // System.out.println("In!"); ActivityTemp newActivity = new ActivityTemp(activity, type); newActivity.addEvent(start, end); tempActivities.add(newActivity); // System.out.println(tempActivities.toString()); } // else add data to the found activity else tempActivities.get(activityIndex).addEvent(start, end); } // This is hard copied for now ArrayList<ActivityTemp> activities = findAllActivity("Refrigeration"); for (ActivityTemp activityTemp : activities) { tempActivities.remove(activityTemp); System.out.println("Refrigeration Removed"); } int index = findActivity("Standby"); if (index != -1) { tempActivities.remove(index); System.out.println("Standby Consumption Removed"); } // TODO Add these lines in case we want to remove activities with // small sampling number // System.out.println(tempActivities.size()); // for (int i = tempActivities.size() - 1; i >= 0; i--) // if (tempActivities.get(i).getEvents().size() < threshold) // tempActivities.remove(i); // Create an event file for each activity, in order to be able to // use // it for training the behaviour models if asked from the user for (int i = 0; i < tempActivities.size(); i++) { // tempActivities.get(i).status(); try { tempActivities.get(i).createEventFile(); } catch (IOException e1) { System.out.println("Problem with creating events file."); e1.printStackTrace(); } } input.close(); // Add each found appliance (after converting temporary appliance to // normal appliance) in the installation Entity, to the detected // appliance and export models list for (ApplianceTemp temp : tempAppliances) { Appliance tempAppliance = temp.toAppliance(); installation.addAppliance(tempAppliance); detectedAppliances.addElement(tempAppliance.toString()); exportModels.addElement(tempAppliance.toString()); } // Add appliances corresponding to each activity, remove activities // without appliances and add activities to the selected activities // list. for (int i = tempActivities.size() - 1; i >= 0; i--) { tempActivities.get(i).setAppliances(findAppliances(tempActivities.get(i))); if (tempActivities.get(i).getAppliances().size() == 0) { tempActivities.remove(i); } else selectedAppliances.addElement(tempActivities.get(i).toString()); } } // In case of an error. else { int temp = 8 + ((int) (Math.random() * 2)); for (int i = 0; i < temp; i++) { String name = "Appliance " + i; String powerModel = ""; String reactiveModel = ""; int tempIndex = i % 5; switch (tempIndex) { case 0: powerModel = "{\"n\":1,\"params\":[{\"n\":1,\"values\":[{\"p\":1900,\"d\":1,\"s\":0}]},{\"n\":0,\"values\":[{\"p\":300,\"d\":1,\"s\":0}]}]}"; reactiveModel = "{\"n\":1,\"params\":[{\"n\":1,\"values\":[{\"q\":-40,\"d\":1,\"s\":0}]},{\"n\":0,\"values\":[{\"q\":-10,\"d\":1,\"s\":0}]}]}"; break; case 1: powerModel = "{ \"n\" : 0, \"params\" : [{ \"n\" : 1, \"values\" : [ {\"p\" : 140.0, \"d\" : 20, \"s\": 0.0}]}]}"; reactiveModel = "{ \"n\" : 0, \"params\" : [{ \"n\" : 1, \"values\" : [ {\"q\" : 120.0, \"d\" : 20, \"s\": 0.0}]}]}"; break; case 2: powerModel = "{ \"n\" : 0, \"params\" : [{ \"n\" : 1, \"values\" : [ {\"p\" : 95.0, \"d\" : 20, \"s\": 0.0}, {\"p\" :80.0, \"d\" : 18, \"s\": 0.0}, {\"p\" : 0.0, \"d\" : 73, \"s\": 0.0}]}]}]}"; reactiveModel = "{ \"n\" : 0, \"params\" : [{ \"n\" : 1, \"values\" : [ {\"q\" : 0.0, \"d\" : 20, \"s\": 0.0}, {\"q\" : 0.0, \"d\" : 18, \"s\": 0.0}, {\"q\" : 0.0, \"d\" : 73, \"s\": 0.0}]}]}]}"; break; case 3: powerModel = "{ \"n\" : 0, \"params\" : [{ \"n\" : 1, \"values\" : [ {\"p\" : 30.0, \"d\" : 20, \"s\": 0.0}]}]}"; reactiveModel = "{ \"n\" : 0, \"params\" : [{ \"n\" : 1, \"values\" : [ {\"q\" : -5.0, \"d\" : 20, \"s\": 0.0}]}]}"; break; case 4: powerModel = "{\"n\":1,\"params\":[{\"n\":1,\"values\":[{\"p\":150,\"d\":25,\"s\":0},{\"p\":2000,\"d\":13,\"s\":0},{\"p\":100,\"d\":62,\"s\":0}]}]}"; reactiveModel = "{\"n\":1,\"params\":[{\"n\":1,\"values\":[{\"q\":400,\"d\":25,\"s\":0},{\"q\":200,\"d\":13,\"s\":0},{\"q\":300,\"d\":62,\"s\":0}]}]}"; break; } Appliance tempAppliance = new Appliance(name, installation.getName(), powerModel, reactiveModel, "Demo/eventsAll" + tempIndex + ".csv"); installation.addAppliance(tempAppliance); detectedAppliances.addElement(tempAppliance.toString()); selectedAppliances.addElement(tempAppliance.toString()); exportModels.addElement(tempAppliance.toString()); } } // Enable all appliance/activity lists detectedApplianceList.setEnabled(true); detectedApplianceList.setModel(detectedAppliances); detectedApplianceList.setSelectedIndex(0); tabbedPane.setEnabledAt(1, true); selectedApplianceList.setEnabled(true); selectedApplianceList.setModel(selectedAppliances); // exportModelList.setEnabled(true); // exportModelList.setModel(exportModels); // tabbedPane.setEnabledAt(3, true); // Disable unnecessary buttons. disaggregateButton.setEnabled(false); createEventsButton.setEnabled(false); } finally { root.setCursor(Cursor.getDefaultCursor()); } } }); createEventsButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Create Events * button on the Data File panel of the Import Data tab. This button is * used when there is a single appliance with an known consumption model * so that the events can be extracted automatically from the data set. * Used for presentation purposes only since is depricated by the * disaggregation function. */ @Override public void actionPerformed(ActionEvent e) { Component root = SwingUtilities.getRoot((JButton) e.getSource()); try { root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); // Parse the consumption model file File file = new File(consumptionPathField.getText()); String temp = file.getName(); temp = temp.replace(".", " "); String name = temp.split(" ")[0]; Appliance appliance = null; try { int rand = (int) (Math.random() * 5); appliance = new Appliance(name, consumptionPathField.getText(), consumptionPathField.getText(), "Demo/eventsAll" + rand + ".csv", installation, activePowerRadioButton.isSelected()); } catch (IOException e1) { e1.printStackTrace(); } // Add appliance to the installation entity installation.addAppliance(appliance); // Enable all appliance/activity lists detectedAppliances.addElement(appliance.toString()); selectedAppliances.addElement(appliance.toString()); exportModels.addElement(appliance.toString()); detectedApplianceList.setEnabled(true); detectedApplianceList.setModel(detectedAppliances); detectedApplianceList.setSelectedIndex(0); tabbedPane.setEnabledAt(1, true); selectedApplianceList.setEnabled(true); selectedApplianceList.setModel(selectedAppliances); // exportModelList.setEnabled(true); // exportModelList.setModel(exportModels); // tabbedPane.setEnabledAt(3, true); // Disable unnecessary buttons. disaggregateButton.setEnabled(false); createEventsButton.setEnabled(false); } finally { root.setCursor(Cursor.getDefaultCursor()); } } }); // APPLIANCE DETECTION // detectedApplianceList.addListSelectionListener(new ListSelectionListener() { /** * This function is called when the user selects an appliance from the * list of Detected Appliances on the Disaggregation panel of the Import * Data tab. Then the corresponding consumption model is presented in the * Consumption Model Preview panel. */ @Override public void valueChanged(ListSelectionEvent e) { consumptionModelPanel.removeAll(); consumptionModelPanel.updateUI(); if (detectedAppliances.size() >= 1) { String selection = detectedApplianceList.getSelectedValue(); Appliance current = installation.findAppliance(selection); ChartPanel chartPanel = current.consumptionGraph(); consumptionModelPanel.add(chartPanel, BorderLayout.CENTER); consumptionModelPanel.validate(); } } }); // // TRAINING TAB // trainingTab.addComponentListener(new ComponentAdapter() { @Override public void componentShown(ComponentEvent arg0) { selectedApplianceList.setSelectedIndex(0); } }); trainingButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Train button on * the Training Parameters panel of the Train Activity Models tab. It * contains the procedure needed to create an activity model based on the * event set of the appliance or activity. */ @Override public void actionPerformed(ActionEvent e) { Component root = SwingUtilities.getRoot((JButton) e.getSource()); responsePanel.removeAll(); responsePanel.validate(); pricingPreviewPanel.removeAll(); pricingPreviewPanel.validate(); previewResponseButton.setEnabled(false); createResponseButton.setEnabled(false); createResponseAllButton.setEnabled(false); dailyResponseButton.setEnabled(false); startResponseButton.setEnabled(false); try { root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); // Searching for existing activity or appliance. String selection = selectedApplianceList.getSelectedValue(); ActivityTemp activity = null; if (tempActivities.size() > 0) activity = tempActivities.get(findActivity(selection)); Appliance current = installation.findAppliance(selection); String startTime, duration, dailyTimes; // Check for the selected distribution methods for training. if (timesHistogramRadioButton.isSelected()) dailyTimes = "Histogram"; else if (timesNormalRadioButton.isSelected()) dailyTimes = "Normal"; else dailyTimes = "GMM"; if (durationHistogramRadioButton.isSelected()) duration = "Histogram"; else if (durationNormalRadioButton.isSelected()) duration = "Normal"; else duration = "GMM"; if (startHistogramRadioButton.isSelected()) startTime = "Histogram"; else if (startNormalRadioButton.isSelected()) startTime = "Normal"; else startTime = "GMM"; String[] distributions = { dailyTimes, duration, startTime, "Histogram" }; // If the selected object from the list is an appliance the training // procedure for the appliance begins. if (activity == null) { try { installation.getPerson().train(current, distributions); } catch (IOException e1) { e1.printStackTrace(); } } // If the selected object from the list is an activity the training // procedure for the activity begins. else { try { installation.getPerson().train(activity, distributions); } catch (IOException e1) { e1.printStackTrace(); } } // System.out.println("Training OK!"); distributionPreviewPanel.removeAll(); distributionPreviewPanel.updateUI(); expectedPowerPanel.removeAll(); expectedPowerPanel.updateUI(); // Show the distribution created on the Distribution Preview Panel ActivityModel activityModel = installation.getPerson().findActivity(selection, true); if (activityModel == null) activityModel = installation.getPerson().findActivity(current); ChartPanel chartPanel = activityModel.createDailyTimesDistributionChart(); distributionPreviewPanel.add(chartPanel, BorderLayout.CENTER); distributionPreviewPanel.validate(); chartPanel = activityModel.createExpectedPowerChart(); expectedPowerPanel.add(chartPanel, BorderLayout.CENTER); expectedPowerPanel.validate(); // Add the Activity model to the list of trained Activity models of // the Create Response Models tab int size = activitySelectList.getModel().getSize(); if (size > 0) { activityModels = (DefaultListModel<String>) activitySelectList.getModel(); if (activityModels.contains(activityModel.getName()) == false) activityModels.addElement(activityModel.getName()); } else { activityModels = new DefaultListModel<String>(); activityModels.addElement(activityModel.getName()); activitySelectList.setEnabled(true); } activitySelectList.setModel(activityModels); // Add the trained model to the export list also. size = exportModelList.getModel().getSize(); if (size > 0) { exportModels = (DefaultListModel<String>) exportModelList.getModel(); if (exportModels.contains(activityModel.getName()) == false) exportModels.addElement(activityModel.getName()); } else { exportModels = new DefaultListModel<String>(); exportModels.addElement(activityModel.getName()); exportModelList.setEnabled(true); } // Enable some buttons necessary to show the results. dailyTimesButton.setEnabled(true); durationButton.setEnabled(true); startTimeButton.setEnabled(true); startTimeBinnedButton.setEnabled(true); exportModelList.setModel(exportModels); exportDailyButton.setEnabled(true); exportDurationButton.setEnabled(true); exportStartButton.setEnabled(true); exportStartBinnedButton.setEnabled(true); tabbedPane.setEnabledAt(2, true); } finally { root.setCursor(Cursor.getDefaultCursor()); trained = true; } } }); trainAllButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Train All button on * the Training Parameters panel of the Train Activity Models tab. It * is iterating the aforementioned training procedure to each of the * objects on the list. */ @Override public void actionPerformed(ActionEvent e) { responsePanel.removeAll(); responsePanel.validate(); pricingPreviewPanel.removeAll(); pricingPreviewPanel.validate(); previewResponseButton.setEnabled(false); createResponseButton.setEnabled(false); createResponseAllButton.setEnabled(false); dailyResponseButton.setEnabled(false); startResponseButton.setEnabled(false); for (int i = 0; i < selectedApplianceList.getModel().getSize(); i++) { selectedApplianceList.setSelectedIndex(i); trainingButton.doClick(); } } }); dailyTimesButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Daily Times button on * the Distribution Preview panel of the Train Activity Models tab. It * shows the Daily Times Distribution for the selected object from the * list if available. */ @Override public void actionPerformed(ActionEvent arg0) { distributionPreviewPanel.removeAll(); distributionPreviewPanel.updateUI(); String selection = selectedApplianceList.getSelectedValue(); Appliance current = installation.findAppliance(selection); ActivityModel activityModel = installation.getPerson().findActivity(selection, true); if (activityModel == null) activityModel = installation.getPerson().findActivity(current); ChartPanel chartPanel = activityModel.createDailyTimesDistributionChart(); distributionPreviewPanel.add(chartPanel, BorderLayout.CENTER); distributionPreviewPanel.validate(); } }); startTimeBinnedButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Start Time Binned * button on the Distribution Preview panel of the Train Activity * Models tab. It shows the Start Time Binned Distribution for the * selected object from the list if available. */ @Override public void actionPerformed(ActionEvent arg0) { distributionPreviewPanel.removeAll(); distributionPreviewPanel.updateUI(); String selection = selectedApplianceList.getSelectedValue(); Appliance current = installation.findAppliance(selection); ActivityModel activityModel = installation.getPerson().findActivity(selection, true); if (activityModel == null) activityModel = installation.getPerson().findActivity(current); ChartPanel chartPanel = activityModel.createStartTimeBinnedDistributionChart(); distributionPreviewPanel.add(chartPanel, BorderLayout.CENTER); distributionPreviewPanel.validate(); } }); startTimeButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Start Time * button on the Distribution Preview panel of the Train Activity * Models tab. It shows the Start Time Distribution for the selected * object from the list if available. */ @Override public void actionPerformed(ActionEvent arg0) { distributionPreviewPanel.removeAll(); distributionPreviewPanel.updateUI(); String selection = selectedApplianceList.getSelectedValue(); Appliance current = installation.findAppliance(selection); ActivityModel activityModel = installation.getPerson().findActivity(selection, true); if (activityModel == null) activityModel = installation.getPerson().findActivity(current); ChartPanel chartPanel = activityModel.createStartTimeDistributionChart(); distributionPreviewPanel.add(chartPanel, BorderLayout.CENTER); distributionPreviewPanel.validate(); } }); durationButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Duration * button on the Distribution Preview panel of the Train Activity * Models tab. It shows the Duration Distribution for the selected * object from the list if available. */ @Override public void actionPerformed(ActionEvent arg0) { distributionPreviewPanel.removeAll(); distributionPreviewPanel.updateUI(); String selection = selectedApplianceList.getSelectedValue(); Appliance current = installation.findAppliance(selection); ActivityModel activityModel = installation.getPerson().findActivity(selection, true); if (activityModel == null) activityModel = installation.getPerson().findActivity(current); ChartPanel chartPanel = activityModel.createDurationDistributionChart(); distributionPreviewPanel.add(chartPanel, BorderLayout.CENTER); distributionPreviewPanel.validate(); } }); selectedApplianceList.addListSelectionListener(new ListSelectionListener() { /** * This function is called when the user selects an appliance or activity * from the list of Selected Appliances on the Appliance / Activity * Selection panel of the Train Activity Models tab. Then an example * corresponding consumption model is presented in the Consumption Model * Preview panel. */ @Override public void valueChanged(ListSelectionEvent arg0) { ChartPanel chartPanel = null, chartPanel2 = null, chartPanel3 = null; expectedPowerPanel.removeAll(); expectedPowerPanel.updateUI(); distributionPreviewPanel.removeAll(); distributionPreviewPanel.updateUI(); // If there are any appliances / activities on the list if (selectedAppliances.size() >= 1) { // Find the corresponding appliance / activity and show its // consumption model String selection = selectedApplianceList.getSelectedValue(); Appliance currentAppliance = installation.findAppliance(selection); ActivityModel activityModel = installation.getPerson().findActivity(selection, true); // If there is also an Activity model trained, show the corresponding // distribution charts on the Distribution Preview panel if (currentAppliance != null) activityModel = installation.getPerson().findActivity(currentAppliance); if (activityModel == null) activityModel = installation.getPerson().findActivity(selection, true); if (activityModel != null) { dailyTimesButton.setEnabled(true); durationButton.setEnabled(true); startTimeButton.setEnabled(true); startTimeBinnedButton.setEnabled(true); chartPanel2 = activityModel.createDailyTimesDistributionChart(); distributionPreviewPanel.add(chartPanel2, BorderLayout.CENTER); distributionPreviewPanel.validate(); distributionPreviewPanel.updateUI(); chartPanel3 = activityModel.createExpectedPowerChart(); expectedPowerPanel.add(chartPanel3, BorderLayout.CENTER); expectedPowerPanel.validate(); expectedPowerPanel.updateUI(); } else { dailyTimesButton.setEnabled(false); durationButton.setEnabled(false); startTimeButton.setEnabled(false); startTimeBinnedButton.setEnabled(false); } } } }); // RESPONSE TAB // createResponseTab.addComponentListener(new ComponentAdapter() { @Override public void componentHidden(ComponentEvent arg0) { activitySelectList.setSelectedIndex(0); } @Override public void componentShown(ComponentEvent arg0) { activitySelectList.setSelectedIndex(0); } }); previewResponseButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Preview Response * button on the Response Parameters panel of the Create Response Models * tab. This button is enabled after selecting activity model, response * type and pricing for testing and presents a preview of the response * model that may be extracted. */ @Override public void actionPerformed(ActionEvent e) { Component root = SwingUtilities.getRoot((JButton) e.getSource()); try { root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); responsePanel.removeAll(); // Find the selected activity ActivityModel activity = installation.getPerson() .findActivity(activitySelectList.getSelectedValue(), false); int response = -1; // Check for the selected response type if (optimalCaseRadioButton.isSelected()) response = 0; else if (normalCaseRadioButton.isSelected()) response = 1; else response = 2; // Parse the pricing schemes double[] basicScheme = Utils.parseScheme(basicPricingSchemePane.getText()); double[] newScheme = Utils.parseScheme(newPricingSchemePane.getText()); float awareness = (float) (awarenessSlider.getValue()) / 100; float sensitivity = (float) (sensitivitySlider.getValue()) / 100; System.out.println("Awareness: " + awareness + " Sensitivity: " + sensitivity); // Create a preview chart of the response model ChartPanel chartPanel = installation.getPerson().previewResponse(activity, response, basicScheme, newScheme, awareness, sensitivity); responsePanel.add(chartPanel, BorderLayout.CENTER); responsePanel.validate(); createResponseButton.setEnabled(true); createResponseAllButton.setEnabled(true); dailyResponseButton.setEnabled(true); startResponseButton.setEnabled(true); } finally { root.setCursor(Cursor.getDefaultCursor()); } } }); createResponseButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Create Response Model * button on the Response Parameters panel of the Create Response Models * tab. This button is enabled after preview results of the selected * activity model, response type and pricing for testing and creates the * response model for the user. */ @Override public void actionPerformed(ActionEvent e) { Component root = SwingUtilities.getRoot((JButton) e.getSource()); try { root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); exportPreviewPanel.removeAll(); exportPreviewPanel.updateUI(); int responseType = -1; String responseString = ""; // Check for the selected response type if (optimalCaseRadioButton.isSelected()) { responseType = 0; responseString = "Optimal"; } else if (normalCaseRadioButton.isSelected()) { responseType = 1; responseString = "Normal"; } else if (discreteCaseRadioButton.isSelected()) { responseType = 2; responseString = "Discrete"; } // Parse the pricing schemes double[] basicScheme = Utils.parseScheme(basicPricingSchemePane.getText()); double[] newScheme = Utils.parseScheme(newPricingSchemePane.getText()); // Create the response model ActivityModel activity = installation.getPerson() .findActivity(activitySelectList.getSelectedValue(), false); String response = ""; float awareness = (float) (awarenessSlider.getValue()) / 100; float sensitivity = (float) (sensitivitySlider.getValue()) / 100; System.out.println("Awareness: " + awareness + " Sensitivity: " + sensitivity); try { response = installation.getPerson().createResponse(activity, responseType, basicScheme, newScheme, awareness, sensitivity); } catch (IOException exc) { exc.printStackTrace(); } // Add the response model extracted to the export model list. int size = exportModelList.getModel().getSize(); // System.out.println(size); if (size > 0) { exportModels = (DefaultListModel<String>) exportModelList.getModel(); String response2 = "", response3 = ""; if (responseString.equalsIgnoreCase("Optimal")) { response2 = response.replace(responseString, "Normal"); response3 = response.replace(responseString, "Discrete"); } else if (responseString.equalsIgnoreCase("Normal")) { response2 = response.replace(responseString, "Optimal"); response3 = response.replace(responseString, "Discrete"); } else { response2 = response.replace(responseString, "Optimal"); response3 = response.replace(responseString, "Normal"); } if (exportModels.contains(response2)) exportModels.removeElement(response2); if (exportModels.contains(response3)) exportModels.removeElement(response3); if (exportModels.contains(response) == false) exportModels.addElement(response); } else { exportModels = new DefaultListModel<String>(); exportModels.addElement(response); exportModelList.setEnabled(true); } exportModelList.setModel(exportModels); if (manyFlag == false) { JFrame success = new JFrame(); JOptionPane.showMessageDialog(success, "The response model " + response + " was created successfully", "Response Model Created", JOptionPane.INFORMATION_MESSAGE); } } finally { root.setCursor(Cursor.getDefaultCursor()); } } }); createResponseAllButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Create Response All * button on the Response Parameters panel of the Create Response Models * tab. This is achieved by iterating the procedure above for all the * available activity models in the list. */ @Override public void actionPerformed(ActionEvent arg0) { manyFlag = true; for (int i = 0; i < activitySelectList.getModel().getSize(); i++) { activitySelectList.setSelectedIndex(i); createResponseButton.doClick(); } JFrame success = new JFrame(); JOptionPane.showMessageDialog(success, "The response models were created successfully", "Response Models Created", JOptionPane.INFORMATION_MESSAGE); manyFlag = false; } }); newPricingSchemePane.addKeyListener(new KeyAdapter() { @Override public void keyTyped(KeyEvent arg0) { commitButton.setEnabled(true); } }); basicPricingSchemePane.addCaretListener(new CaretListener() { @Override public void caretUpdate(CaretEvent arg0) { commitButton.setEnabled(true); } }); commitButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Commit button on the * Pricing Scheme panel of the Create Response Models tab. This button is * enabled after adding the two pricing schemes that are prerequisites for * the creation of a response model. */ @Override public void actionPerformed(ActionEvent e) { Component root = SwingUtilities.getRoot((JButton) e.getSource()); try { root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); boolean basicScheme = false; boolean newScheme = false; int parseBasic = 0; int parseNew = 0; pricingPreviewPanel.removeAll(); // Check if both pricing schemes are entered if (basicPricingSchemePane.getText().equalsIgnoreCase("") == false) basicScheme = true; if (newPricingSchemePane.getText().equalsIgnoreCase("") == false) newScheme = true; // Parse the pricing schemes for errors if (basicScheme) parseBasic = Utils.parsePricingScheme(basicPricingSchemePane.getText()); if (newScheme) parseNew = Utils.parsePricingScheme(newPricingSchemePane.getText()); // If errors are found then present the line the error may be at if (parseBasic != -1) { JFrame error = new JFrame(); JOptionPane.showMessageDialog(error, "Basic Pricing Scheme is not defined correctly. Please check your input in line " + parseBasic + " and try again.", "Inane error", JOptionPane.ERROR_MESSAGE); } else if (parseNew != -1) { JFrame error = new JFrame(); JOptionPane.showMessageDialog(error, "New Pricing Scheme is not defined correctly. Please check your input in line " + parseNew + " and try again.", "Inane error", JOptionPane.ERROR_MESSAGE); } // If no errors are found make a preview chart of the two pricing // schemes else { if (basicScheme && newScheme) { ChartPanel chartPanel = ChartUtils.parsePricingScheme(basicPricingSchemePane.getText(), newPricingSchemePane.getText()); pricingPreviewPanel.add(chartPanel, BorderLayout.CENTER); pricingPreviewPanel.validate(); previewResponseButton.setEnabled(true); } else { JFrame error = new JFrame(); JOptionPane.showMessageDialog(error, "You have not defined both pricing schemes.Please check your input and try again.", "Inane error", JOptionPane.ERROR_MESSAGE); previewResponseButton.setEnabled(false); } } responsePanel.removeAll(); responsePanel.validate(); createResponseButton.setEnabled(false); createResponseAllButton.setEnabled(false); dailyResponseButton.setEnabled(false); startResponseButton.setEnabled(false); } finally { root.setCursor(Cursor.getDefaultCursor()); } } }); startResponseButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the start time button on * the Preview Response panel of the Create Response Models tab. This * button is enabled after the user has pressed the Response Preview * button in order to see the results of his pricing scheme on a activity * model. It shows the changes in the start time distribution. */ @Override public void actionPerformed(ActionEvent e) { Component root = SwingUtilities.getRoot((JButton) e.getSource()); try { root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); responsePanel.removeAll(); // Find the selected activity ActivityModel activity = installation.getPerson() .findActivity(activitySelectList.getSelectedValue(), false); int response = -1; // Check for the selected response type if (optimalCaseRadioButton.isSelected()) response = 0; else if (normalCaseRadioButton.isSelected()) response = 1; else response = 2; // Parse the pricing schemes double[] basicScheme = Utils.parseScheme(basicPricingSchemePane.getText()); double[] newScheme = Utils.parseScheme(newPricingSchemePane.getText()); float awareness = (float) (awarenessSlider.getValue()) / 100; float sensitivity = (float) (sensitivitySlider.getValue()) / 100; System.out.println("Awareness: " + awareness + " Sensitivity: " + sensitivity); // Create a preview chart of the response model ChartPanel chartPanel = installation.getPerson().previewResponse(activity, response, basicScheme, newScheme, awareness, sensitivity); responsePanel.add(chartPanel, BorderLayout.CENTER); responsePanel.validate(); createResponseButton.setEnabled(true); createResponseAllButton.setEnabled(true); dailyResponseButton.setEnabled(true); startResponseButton.setEnabled(true); } finally { root.setCursor(Cursor.getDefaultCursor()); } } }); dailyResponseButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the start time button on * the Preview Response panel of the Create Response Models tab. This * button is enabled after the user has pressed the Response Preview * button in order to see the results of his pricing scheme on a activity * model. It shows the changes in the daily times distribution. */ @Override public void actionPerformed(ActionEvent e) { Component root = SwingUtilities.getRoot((JButton) e.getSource()); try { root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); responsePanel.removeAll(); // Find the selected activity ActivityModel activity = installation.getPerson() .findActivity(activitySelectList.getSelectedValue(), false); // Parse the pricing schemes double[] basicScheme = Utils.parseScheme(basicPricingSchemePane.getText()); double[] newScheme = Utils.parseScheme(newPricingSchemePane.getText()); float awareness = (float) (awarenessSlider.getValue()) / 100; float sensitivity = (float) (sensitivitySlider.getValue()) / 100; System.out.println("Awareness: " + awareness + " Sensitivity: " + sensitivity); // Create a preview chart of the response model ChartPanel chartPanel = installation.getPerson().previewDailyResponse(activity, basicScheme, newScheme, awareness, sensitivity); responsePanel.add(chartPanel, BorderLayout.CENTER); responsePanel.validate(); createResponseButton.setEnabled(true); createResponseAllButton.setEnabled(true); dailyResponseButton.setEnabled(true); startResponseButton.setEnabled(true); } finally { root.setCursor(Cursor.getDefaultCursor()); } } }); // EXPORT TAB // exportTab.addComponentListener(new ComponentAdapter() { @Override public void componentShown(ComponentEvent arg0) { exportModelList.setSelectedIndex(0); } }); exportModelList.addListSelectionListener(new ListSelectionListener() { /** * This function is called when the user selects an entity from the * list of models on the Model Export Selection panel of the Export Models * tab. Then the corresponding preview of the entity model is presented in * the * Export Model Preview panel. */ @Override public void valueChanged(ListSelectionEvent arg0) { if (tabbedPane.getSelectedIndex() == 3) { exportPreviewPanel.removeAll(); exportPreviewPanel.updateUI(); // Checking if the list has any object if (exportModels.size() > 1) { String selection = exportModelList.getSelectedValue(); // Check to see what type of entity is selected (Installation, // Person, Appliance, Activity, Response) Appliance appliance = installation.findAppliance(selection); ActivityModel activity = installation.getPerson().findActivity(selection, false); ResponseModel response = installation.getPerson().findResponse(selection); // Create the appropriate chart for the selected entity and show it. ChartPanel chartPanel = null; if (selection.equalsIgnoreCase(installation.getName())) { try { chartPanel = installation.measurementsChart(); exportDailyButton.setEnabled(false); exportDurationButton.setEnabled(false); exportStartButton.setEnabled(false); exportStartBinnedButton.setEnabled(false); if (trained) exportExpectedPowerButton.setEnabled(true); else exportExpectedPowerButton.setEnabled(false); } catch (IOException e1) { e1.printStackTrace(); } } else if (selection.equalsIgnoreCase(installation.getPerson().getName())) { chartPanel = installation.getPerson().statisticGraphs(); exportDailyButton.setEnabled(false); exportDurationButton.setEnabled(false); exportStartButton.setEnabled(false); exportStartBinnedButton.setEnabled(false); exportExpectedPowerButton.setEnabled(false); } else if (appliance != null) { chartPanel = appliance.consumptionGraph(); exportDailyButton.setEnabled(false); exportDurationButton.setEnabled(false); exportStartButton.setEnabled(false); exportStartBinnedButton.setEnabled(false); exportExpectedPowerButton.setEnabled(false); } else if (activity != null) { chartPanel = activity.createDailyTimesDistributionChart(); activity.status(); exportDailyButton.setEnabled(true); exportDurationButton.setEnabled(true); exportStartButton.setEnabled(true); exportStartBinnedButton.setEnabled(true); exportExpectedPowerButton.setEnabled(true); } else if (response != null) { chartPanel = response.createDailyTimesDistributionChart(); exportDailyButton.setEnabled(true); exportDurationButton.setEnabled(true); exportStartButton.setEnabled(true); exportStartBinnedButton.setEnabled(true); exportExpectedPowerButton.setEnabled(true); } exportPreviewPanel.add(chartPanel, BorderLayout.CENTER); exportPreviewPanel.validate(); } } } }); exportDailyButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Daily Times * button on the Entity Preview panel of the Export Models tab. It shows * the Daily Times Distribution for the selected object from the list. */ @Override public void actionPerformed(ActionEvent arg0) { exportPreviewPanel.removeAll(); exportPreviewPanel.updateUI(); String selection = exportModelList.getSelectedValue(); ActivityModel activity = installation.getPerson().findActivity(selection, false); ResponseModel response = installation.getPerson().findResponse(selection); ChartPanel chartPanel = null; if (activity != null) chartPanel = activity.createDailyTimesDistributionChart(); else chartPanel = response.createDailyTimesDistributionChart(); exportPreviewPanel.add(chartPanel, BorderLayout.CENTER); exportPreviewPanel.validate(); } }); exportStartBinnedButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Start Time Binned * button on the Entity Preview panel of the Export Models tab. It shows * the Start Time Binned Distribution for the selected object from the * list. */ @Override public void actionPerformed(ActionEvent arg0) { exportPreviewPanel.removeAll(); exportPreviewPanel.updateUI(); String selection = exportModelList.getSelectedValue(); ActivityModel activity = installation.getPerson().findActivity(selection, false); ResponseModel response = installation.getPerson().findResponse(selection); ChartPanel chartPanel = null; if (activity != null) chartPanel = activity.createStartTimeBinnedDistributionChart(); else chartPanel = response.createStartTimeBinnedDistributionChart(); exportPreviewPanel.add(chartPanel, BorderLayout.CENTER); exportPreviewPanel.validate(); } }); exportStartButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Start Time * button on the Entity Preview panel of the Export Models tab. It shows * the Start Time Distribution for the selected object from the list. */ @Override public void actionPerformed(ActionEvent arg0) { exportPreviewPanel.removeAll(); exportPreviewPanel.updateUI(); String selection = exportModelList.getSelectedValue(); ActivityModel activity = installation.getPerson().findActivity(selection, false); ResponseModel response = installation.getPerson().findResponse(selection); ChartPanel chartPanel = null; if (activity != null) chartPanel = activity.createStartTimeDistributionChart(); else chartPanel = response.createStartTimeDistributionChart(); exportPreviewPanel.add(chartPanel, BorderLayout.CENTER); exportPreviewPanel.validate(); } }); exportDurationButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Duration * button on the Entity Preview panel of the Export Models tab. It shows * the Duration Distribution for the selected object from the list. */ @Override public void actionPerformed(ActionEvent arg0) { exportPreviewPanel.removeAll(); exportPreviewPanel.updateUI(); String selection = exportModelList.getSelectedValue(); ActivityModel activity = installation.getPerson().findActivity(selection, false); ResponseModel response = installation.getPerson().findResponse(selection); ChartPanel chartPanel = null; if (activity != null) chartPanel = activity.createDurationDistributionChart(); else chartPanel = response.createDurationDistributionChart(); exportPreviewPanel.add(chartPanel, BorderLayout.CENTER); exportPreviewPanel.validate(); } }); exportExpectedPowerButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { exportPreviewPanel.removeAll(); exportPreviewPanel.updateUI(); String selection = exportModelList.getSelectedValue(); ActivityModel activity = installation.getPerson().findActivity(selection, false); ResponseModel response = installation.getPerson().findResponse(selection); ChartPanel chartPanel = null; if (selection.equalsIgnoreCase(installation.getName())) chartPanel = installation.createExpectedPowerChart(); else if (activity != null) chartPanel = activity.createExpectedPowerChart(); else chartPanel = response.createExpectedPowerChart(); exportPreviewPanel.add(chartPanel, BorderLayout.CENTER); exportPreviewPanel.validate(); } }); connectButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Connect button on the * Connection Properties panel of the Export Models tab. It helps the user * to connect to his Cassandra Library and export the models he created * there. */ @Override public void actionPerformed(ActionEvent e) { boolean result = false; // Reads the user credentials and the server to connect to. try { APIUtilities.setUrl(urlTextField.getText()); result = APIUtilities.sendUserCredentials(usernameTextField.getText(), passwordField.getPassword()); } catch (Exception e1) { e1.printStackTrace(); } // If the use credentials are correct if (result) { exportButton.setEnabled(true); exportAllBaseButton.setEnabled(true); exportAllResponseButton.setEnabled(true); householdNameTextField.setEnabled(true); } // Else a error message appears. else { JFrame error = new JFrame(); JOptionPane.showMessageDialog(error, "User Credentials are not correct! Please try again.", "Inane error", JOptionPane.ERROR_MESSAGE); passwordField.setText(""); } } }); passwordField.addCaretListener(new CaretListener() { @Override public void caretUpdate(CaretEvent e) { String pass = String.valueOf(passwordField.getPassword()); if (pass.equals("")) { connectButton.setEnabled(false); } else connectButton.setEnabled(true); } }); exportButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Export button on the * Connection Properties panel of the Export Models tab. The entity model * selected from the list is then exported to the User Library in * Cassandra Platform. */ @Override public void actionPerformed(ActionEvent e) { Component root = SwingUtilities.getRoot((JButton) e.getSource()); try { root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); // Parsing the selected entity and find out what type of entity it is. String selection = exportModelList.getSelectedValue(); Appliance appliance = installation.findAppliance(selection); ActivityModel activity = installation.getPerson().findActivity(selection, false); ResponseModel response = installation.getPerson().findResponse(selection); // If it is installation if (selection.equalsIgnoreCase(installation.getName())) { String oldName = installation.getName(); installation.setName(householdNameTextField.getText()); try { installation.setInstallationID(APIUtilities .sendEntity(installation.toJSON(APIUtilities.getUserID()).toString(), "/inst")); } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) { e1.printStackTrace(); } installation.setName(oldName); JFrame success = new JFrame(); JOptionPane.showMessageDialog(success, "The installation model " + installation.getName() + " was exported successfully", "Installation Model Exported", JOptionPane.INFORMATION_MESSAGE); } // If it is person else if (selection.equalsIgnoreCase(installation.getPerson().getName())) { try { installation.getPerson().setPersonID(APIUtilities.sendEntity( installation.getPerson().toJSON(APIUtilities.getUserID()).toString(), "/pers")); } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) { e1.printStackTrace(); } JFrame success = new JFrame(); JOptionPane.showMessageDialog(success, "The person model " + installation.getPerson().getName() + " was exported successfully", "Person Model Exported", JOptionPane.INFORMATION_MESSAGE); } // If it is appliance else if (appliance != null) { try { appliance.setApplianceID(APIUtilities .sendEntity(appliance.toJSON(APIUtilities.getUserID()).toString(), "/app")); APIUtilities.sendEntity(appliance.powerConsumptionModelToJSON().toString(), "/consmod"); } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) { e1.printStackTrace(); } JFrame success = new JFrame(); JOptionPane.showMessageDialog(success, "The appliance model " + appliance.getName() + " was exported successfully", "Appliance Model Exported", JOptionPane.INFORMATION_MESSAGE); } // If it is activity else if (activity != null) { String[] applianceTemp = new String[activity.getAppliancesOf().length]; String activityTemp = ""; String durationTemp = ""; String dailyTemp = ""; String startTemp = ""; // For each appliance that participates in the activity for (int i = 0; i < activity.getAppliancesOf().length; i++) { Appliance activityAppliance = activity.getAppliancesOf()[i]; try { // In case the appliances contained in the Activity model are // not // in the database, we create the object there before sending // the // activity model if (activityAppliance.getApplianceID().equalsIgnoreCase("")) { activityAppliance.setApplianceID(APIUtilities.sendEntity( activityAppliance.toJSON(APIUtilities.getUserID()).toString(), "/app")); APIUtilities.sendEntity( activityAppliance.powerConsumptionModelToJSON().toString(), "/consmod"); } applianceTemp[i] = activityAppliance.getApplianceID(); } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) { e1.printStackTrace(); } } try { String[] appliancesID = applianceTemp; // Creating the JSON of the activity model activity.setActivityModelID(APIUtilities.sendEntity( activity.toJSON(appliancesID, APIUtilities.getUserID()).toString(), "/actmod")); activityTemp = activity.getActivityModelID(); // Creating the JSON of the distributions activity.getDailyTimes().setDistributionID(APIUtilities.sendEntity( activity.getDailyTimes().toJSON(activityTemp).toString(), "/distr")); activity.setDailyID(activity.getDailyTimes().getDistributionID()); dailyTemp = activity.getDailyID(); activity.getDuration().setDistributionID(APIUtilities .sendEntity(activity.getDuration().toJSON(activityTemp).toString(), "/distr")); activity.setDurationID(activity.getDuration().getDistributionID()); durationTemp = activity.getDurationID(); activity.getStartTime().setDistributionID(APIUtilities .sendEntity(activity.getStartTime().toJSON(activityTemp).toString(), "/distr")); activity.setStartID(activity.getStartTime().getDistributionID()); startTemp = activity.getStartID(); // Adding the JSON of the distributions to the activity model APIUtilities.updateEntity( activity.toJSON(appliancesID, APIUtilities.getUserID()).toString(), "/actmod", activityTemp); } catch (AuthenticationException | NoSuchAlgorithmException | IOException e1) { e1.printStackTrace(); } JFrame success = new JFrame(); JOptionPane.showMessageDialog(success, "The activity model " + activity.getName() + " was exported successfully", "Activity Model Exported", JOptionPane.INFORMATION_MESSAGE); } // If it is response else if (response != null) { String[] applianceTemp = new String[response.getAppliancesOf().length]; String responseTemp = ""; String durationTemp = ""; String dailyTemp = ""; String startTemp = ""; // For each appliance that participates in the activity for (int i = 0; i < response.getAppliancesOf().length; i++) { Appliance responseAppliance = response.getAppliancesOf()[i]; try { // In case the appliances contained in the Activity model are // not // in the database, we create the object there before sending // the // activity model if (responseAppliance.getApplianceID().equalsIgnoreCase("")) { responseAppliance.setApplianceID(APIUtilities.sendEntity( responseAppliance.toJSON(APIUtilities.getUserID()).toString(), "/app")); APIUtilities.sendEntity( responseAppliance.powerConsumptionModelToJSON().toString(), "/consmod"); } applianceTemp[i] = responseAppliance.getApplianceID(); } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) { e1.printStackTrace(); } } try { String[] appliancesID = applianceTemp; // Creating the JSON of the response response.setActivityModelID(APIUtilities.sendEntity( response.toJSON(appliancesID, APIUtilities.getUserID()).toString(), "/actmod")); responseTemp = response.getActivityModelID(); // Creating the JSON of the distributions response.getDailyTimes().setDistributionID(APIUtilities.sendEntity( response.getDailyTimes().toJSON(responseTemp).toString(), "/distr")); response.setDailyID(response.getDailyTimes().getDistributionID()); dailyTemp = response.getDailyID(); response.getDuration().setDistributionID(APIUtilities .sendEntity(response.getDuration().toJSON(responseTemp).toString(), "/distr")); response.setDurationID(response.getDuration().getDistributionID()); durationTemp = response.getDurationID(); response.getStartTime().setDistributionID(APIUtilities .sendEntity(response.getStartTime().toJSON(responseTemp).toString(), "/distr")); response.setStartID(response.getStartTime().getDistributionID()); startTemp = response.getStartID(); // Adding the JSON of the distributions to the activity model APIUtilities.updateEntity( response.toJSON(appliancesID, APIUtilities.getUserID()).toString(), "/actmod", responseTemp); } catch (AuthenticationException | NoSuchAlgorithmException | IOException e1) { e1.printStackTrace(); } JFrame success = new JFrame(); JOptionPane.showMessageDialog(success, "The response model " + response.getName() + " was exported successfully", "Response Model Exported", JOptionPane.INFORMATION_MESSAGE); } } finally { root.setCursor(Cursor.getDefaultCursor()); } } }); exportAllBaseButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Export All Base * button on the Connection Properties panel of the Export Models tab. The * export procedure above is iterated through all the entities available * on the list except for the response models. */ @Override public void actionPerformed(ActionEvent e) { Component root = SwingUtilities.getRoot((JButton) e.getSource()); try { root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); for (int i = 0; i < exportModelList.getModel().getSize(); i++) { exportModelList.setSelectedIndex(i); String selection = exportModelList.getSelectedValue(); Appliance appliance = installation.findAppliance(selection); ActivityModel activity = installation.getPerson().findActivity(selection, false); ResponseModel response = installation.getPerson().findResponse(selection); if (selection.equalsIgnoreCase(installation.getName())) { String oldName = installation.getName(); try { installation.setName(householdNameTextField.getText() + " Base"); installation.setInstallationID(APIUtilities.sendEntity( installation.toJSON(APIUtilities.getUserID()).toString(), "/inst")); installation.setName(oldName); } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) { e1.printStackTrace(); } } else if (selection.equalsIgnoreCase(installation.getPerson().getName())) { try { installation.getPerson().setPersonID(APIUtilities.sendEntity(installation .getPerson().toJSON(installation.getInstallationID()).toString(), "/pers")); } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) { e1.printStackTrace(); } } else if (appliance != null) { try { appliance.setApplianceID(APIUtilities.sendEntity( appliance.toJSON(installation.getInstallationID().toString()).toString(), "/app")); APIUtilities.sendEntity(appliance.powerConsumptionModelToJSON().toString(), "/consmod"); } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) { e1.printStackTrace(); } } else if (activity != null) { String[] applianceTemp = new String[activity.getAppliancesOf().length]; String personTemp = ""; String activityTemp = ""; String durationTemp = ""; String dailyTemp = ""; String startTemp = ""; // For each appliance that participates in the activity for (int j = 0; j < activity.getAppliancesOf().length; j++) { Appliance activityAppliance = activity.getAppliancesOf()[j]; applianceTemp[j] = activityAppliance.getApplianceID(); } personTemp = installation.getPerson().getPersonID(); try { activity.setActivityID(APIUtilities .sendEntity(activity.activityToJSON(personTemp).toString(), "/act")); String[] appliancesID = applianceTemp; activity.setActivityModelID(APIUtilities .sendEntity(activity.toJSON(appliancesID).toString(), "/actmod")); activityTemp = activity.getActivityModelID(); activity.getDailyTimes().setDistributionID(APIUtilities.sendEntity( activity.getDailyTimes().toJSON(activityTemp).toString(), "/distr")); activity.setDailyID(activity.getDailyTimes().getDistributionID()); dailyTemp = activity.getDailyID(); activity.getDuration().setDistributionID(APIUtilities.sendEntity( activity.getDuration().toJSON(activityTemp).toString(), "/distr")); activity.setDurationID(activity.getDuration().getDistributionID()); durationTemp = activity.getDurationID(); activity.getStartTime().setDistributionID(APIUtilities.sendEntity( activity.getStartTime().toJSON(activityTemp).toString(), "/distr")); activity.setStartID(activity.getStartTime().getDistributionID()); startTemp = activity.getStartID(); APIUtilities.updateEntity(activity.toJSON(appliancesID).toString(), "/actmod", activityTemp); } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) { e1.printStackTrace(); } } else if (response != null) { } } } finally { root.setCursor(Cursor.getDefaultCursor()); } JFrame success = new JFrame(); JOptionPane.showMessageDialog(success, "The installation model " + installation.getName() + " for the base pricing scheme and all the entities contained within were exported successfully", "Installation Model Exported", JOptionPane.INFORMATION_MESSAGE); } }); exportAllResponseButton.addActionListener(new ActionListener() { /** * This function is called when the user presses the Export All Base * button on the Connection Properties panel of the Export Models tab. The * export procedure above is iterated through all the entities available * on the list except for the activity models. */ @Override public void actionPerformed(ActionEvent e) { Component root = SwingUtilities.getRoot((JButton) e.getSource()); try { root.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); for (int i = 0; i < exportModelList.getModel().getSize(); i++) { exportModelList.setSelectedIndex(i); String selection = exportModelList.getSelectedValue(); Appliance appliance = installation.findAppliance(selection); ActivityModel activity = installation.getPerson().findActivity(selection, false); ResponseModel response = installation.getPerson().findResponse(selection); if (selection.equalsIgnoreCase(installation.getName())) { String oldName = installation.getName(); try { installation.setName(householdNameTextField.getText() + " Response"); installation.setInstallationID(APIUtilities.sendEntity( installation.toJSON(APIUtilities.getUserID()).toString(), "/inst")); installation.setName(oldName); } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) { e1.printStackTrace(); } } else if (selection.equalsIgnoreCase(installation.getPerson().getName())) { try { installation.getPerson().setPersonID(APIUtilities.sendEntity(installation .getPerson().toJSON(installation.getInstallationID()).toString(), "/pers")); } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) { e1.printStackTrace(); } } else if (appliance != null) { try { appliance.setApplianceID(APIUtilities.sendEntity( appliance.toJSON(installation.getInstallationID().toString()).toString(), "/app")); APIUtilities.sendEntity(appliance.powerConsumptionModelToJSON().toString(), "/consmod"); } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) { e1.printStackTrace(); } } else if (activity != null) { } else if (response != null) { String[] applianceTemp = new String[response.getAppliancesOf().length]; String personTemp = ""; String responseTemp = ""; String durationTemp = ""; String dailyTemp = ""; String startTemp = ""; // For each appliance that participates in the activity for (int j = 0; j < response.getAppliancesOf().length; j++) { Appliance responseAppliance = response.getAppliancesOf()[j]; applianceTemp[j] = responseAppliance.getApplianceID(); } personTemp = installation.getPerson().getPersonID(); try { response.setActivityID(APIUtilities .sendEntity(response.activityToJSON(personTemp).toString(), "/act")); String[] appliancesID = applianceTemp; response.setActivityModelID(APIUtilities .sendEntity(response.toJSON(appliancesID).toString(), "/actmod")); responseTemp = response.getActivityModelID(); response.getDailyTimes().setDistributionID(APIUtilities.sendEntity( response.getDailyTimes().toJSON(responseTemp).toString(), "/distr")); response.setDailyID(response.getDailyTimes().getDistributionID()); dailyTemp = response.getDailyID(); response.getDuration().setDistributionID(APIUtilities.sendEntity( response.getDuration().toJSON(responseTemp).toString(), "/distr")); response.setDurationID(response.getDuration().getDistributionID()); durationTemp = response.getDurationID(); response.getStartTime().setDistributionID(APIUtilities.sendEntity( response.getStartTime().toJSON(responseTemp).toString(), "/distr")); response.setStartID(response.getStartTime().getDistributionID()); startTemp = response.getStartID(); APIUtilities.updateEntity(response.toJSON(appliancesID).toString(), "/actmod", responseTemp); } catch (IOException | AuthenticationException | NoSuchAlgorithmException e1) { e1.printStackTrace(); } } } } finally { root.setCursor(Cursor.getDefaultCursor()); } JFrame success = new JFrame(); JOptionPane.showMessageDialog(success, "The installation model " + installation.getName() + " for the new pricing scheme and all the entities contained within were exported successfully", "Installation Model Exported", JOptionPane.INFORMATION_MESSAGE); } }); }
From source file:edu.harvard.i2b2.analysis.ui.ExplorerC.java
/** * @param args//from w w w . j a v a 2s.c o m */ @SuppressWarnings("serial") protected Control createContents(Composite parent) { log.info("Explorer plugin version 1.6.0"); GridLayout topGridLayout = new GridLayout(1, false); topGridLayout.numColumns = 1; topGridLayout.marginWidth = 2; topGridLayout.marginHeight = 2; setLayout(topGridLayout); Composite oTreeComposite = new Composite(this, SWT.NONE); oTreeComposite.setLayout(new FillLayout(SWT.VERTICAL)); GridData gridData2 = new GridData(); gridData2.horizontalAlignment = GridData.FILL; gridData2.verticalAlignment = GridData.FILL; gridData2.grabExcessHorizontalSpace = true; gridData2.grabExcessVerticalSpace = true; oTreeComposite.setLayoutData(gridData2); // the horizontal sash form SashForm horizontalForm = new SashForm(oTreeComposite, SWT.HORIZONTAL); horizontalForm.setOrientation(SWT.HORIZONTAL); horizontalForm.setLayout(new GridLayout()); if (drawLeft) { // left sash form SashForm leftVerticalForm = new SashForm(horizontalForm, SWT.VERTICAL); leftVerticalForm.setOrientation(SWT.VERTICAL); leftVerticalForm.setLayout(new GridLayout()); if (bWantStatusLine) { slm.createControl(this, SWT.NULL); } slm.setMessage("i2b2 Explorer Version 2.0"); slm.update(true); // Create the tab folder final TabFolder oTabFolder = new TabFolder(leftVerticalForm, SWT.NONE); // Create each tab and set its text, tool tip text, // image, and control TabItem oTreeTab = new TabItem(oTabFolder, SWT.NONE); oTreeTab.setText("Concept trees"); oTreeTab.setToolTipText("Hierarchically organized patient characteristics"); oTreeTab.setControl(getConceptTreeTabControl(oTabFolder)); // Select the first tab (index is zero-based) oTabFolder.setSelection(0); // Create the tab folder final TabFolder queryRunFolder = new TabFolder(leftVerticalForm, SWT.NONE); TabItem previousRunTab = new TabItem(queryRunFolder, SWT.NONE); previousRunTab.setText("Patient Sets and Previous Queries"); previousRunTab.setToolTipText("Patient Sets & Previous Queries"); final Composite runComposite = new Composite(queryRunFolder, SWT.EMBEDDED); previousRunTab.setControl(runComposite); /* Create and setting up frame */ ////for mac fix //if ( System.getProperty("os.name").toLowerCase().startsWith("mac")) //SWT_AWT.embeddedFrameClass = "sun.lwawt.macosx.CViewEmbeddedFrame"; Frame runFrame = SWT_AWT.new_Frame(runComposite); Panel runPanel = new Panel(new BorderLayout()); try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { log.debug("Error setting native LAF: " + e); } runFrame.add(runPanel); JRootPane runRoot = new JRootPane(); runPanel.add(runRoot); // Select the first tab (index is zero-based) queryRunFolder.setSelection(0); } SashForm verticalForm = new SashForm(horizontalForm, SWT.VERTICAL); verticalForm.setOrientation(SWT.VERTICAL); verticalForm.setLayout(new GridLayout()); // put a tab folder in it... tabFolder = new TabFolder(verticalForm, SWT.NONE); Composite patientNumsComposite = new Composite(verticalForm, SWT.NONE); GridData patientNumData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); patientNumData.grabExcessHorizontalSpace = true; patientNumsComposite.setLayoutData(patientNumData); patientNumsComposite.setLayout(null); Label patientset = new Label(patientNumsComposite, SWT.NONE); patientset.setText("Patient Set: "); patientset.setBounds(5, 9, 60, 22); patientSetText = new Text(patientNumsComposite, SWT.SINGLE | SWT.BORDER); patientSetText.setText(""); // patientSetText.setEditable(false); patientSetText.setBounds(70, 5, 300, 35); leftArrowButton = new Button(patientNumsComposite, SWT.PUSH); leftArrowButton.setText("<<<"); leftArrowButton.setEnabled(false); leftArrowButton.setBounds(380, 5, 38, 22); leftArrowButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { ConceptTableModel i2b2Model = (ConceptTableModel) table.getModel(); i2b2Model.fillDataFromTable(rowData); if (rowData.size() == 0) { oTheParent.getDisplay().syncExec(new Runnable() { public void run() { tabFolder.setSelection(0); } }); MessageBox mBox = new MessageBox(table.getShell(), SWT.ICON_INFORMATION | SWT.OK); mBox.setText("Please Note ..."); mBox.setMessage("The set up table is empty."); mBox.open(); return; } String patientSetStr = patientSetText.getText(); if (patientSetStr.equals("") && !isAll) { oTheParent.getDisplay().syncExec(new Runnable() { public void run() { tabFolder.setSelection(0); } }); MessageBox mBox = new MessageBox(table.getShell(), SWT.ICON_INFORMATION | SWT.OK); mBox.setText("Please Note ..."); mBox.setMessage("Please set a patient set or choose all datamart option."); mBox.open(); return; } int start = new Integer(patientMinNumText.getText()).intValue(); int inc = new Integer(patientMaxNumText.getText()).intValue(); if (start - inc - inc <= 0) { leftArrowButton.setEnabled(false); } if (start <= patientSetSize) { rightArrowButton.setEnabled(true); } else { rightArrowButton.setEnabled(false); } if ((start - inc) >= 0) { patientMinNumText.setText("" + (start - inc)); } else { patientMinNumText.setText("1"); } if (tabFolder.getSelectionIndex() == 1) { DestroyMiniVisualization(oAwtContainer); } else if (tabFolder.getSelectionIndex() == 0) { oTheParent.getDisplay().syncExec(new Runnable() { public void run() { tabFolder.setSelection(1); } }); } if (patientSetStr.equalsIgnoreCase("All")) { int minPatient = 0; try { String minText = patientMinNumText.getText(); minPatient = Integer.parseInt(minText); } catch (Exception e1) { minPatient = -1; } int maxPatient = 0; try { maxPatient = Integer.parseInt(patientMaxNumText.getText()); } catch (Exception e2) { maxPatient = -1; } PerformVisualizationQuery(oAwtContainer, "All", minPatient, maxPatient, bDisplayAllData); } else { int min = Integer.parseInt(patientMinNumText.getText()); int max = Integer.parseInt(patientMaxNumText.getText()); PerformVisualizationQuery(oAwtContainer, patientRefId, min, max, bDisplayAllData); } } }); final Label patNum1 = new Label(patientNumsComposite, SWT.NONE); patNum1.setText(" start: "); patNum1.setBounds(425, 9, 31, 20); patientMinNumText = new Text(patientNumsComposite, SWT.SINGLE | SWT.BORDER); patientMinNumText.setText("1"); patientMinNumText.setBounds(460, 5, 45, 22); final Label patNum2 = new Label(patientNumsComposite, SWT.NONE); patNum2.setText("increment:"); patNum2.setBounds(515, 9, 57, 20); patientMaxNumText = new Text(patientNumsComposite, SWT.SINGLE | SWT.BORDER); patientMaxNumText.setText("10"); patientMaxNumText.setBounds(572, 5, 45, 22); rightArrowButton = new Button(patientNumsComposite, SWT.PUSH); rightArrowButton.setText(">>>"); rightArrowButton.setEnabled(false); rightArrowButton.setBounds(626, 5, 38, 20); rightArrowButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { ConceptTableModel i2b2Model = (ConceptTableModel) table.getModel(); i2b2Model.fillDataFromTable(rowData); if (rowData.size() == 0) { oTheParent.getDisplay().syncExec(new Runnable() { public void run() { tabFolder.setSelection(0); } }); MessageBox mBox = new MessageBox(table.getShell(), SWT.ICON_INFORMATION | SWT.OK); mBox.setText("Please Note ..."); mBox.setMessage("The set up table is empty."); mBox.open(); return; } String patientSetStr = patientSetText.getText(); if (patientSetStr.equals("") && !isAll) { oTheParent.getDisplay().syncExec(new Runnable() { public void run() { tabFolder.setSelection(0); } }); MessageBox mBox = new MessageBox(table.getShell(), SWT.ICON_INFORMATION | SWT.OK); mBox.setText("Please Note ..."); mBox.setMessage("Please set a patient set or choose all datamart option."); mBox.open(); return; } int start = new Integer(patientMinNumText.getText()).intValue(); int inc = new Integer(patientMaxNumText.getText()).intValue(); if (start + inc + inc > patientSetSize) { rightArrowButton.setEnabled(false); } patientMinNumText.setText("" + (start + inc)); leftArrowButton.setEnabled(true); if (tabFolder.getSelectionIndex() == 1) { DestroyMiniVisualization(oAwtContainer); } else if (tabFolder.getSelectionIndex() == 0) { oTheParent.getDisplay().syncExec(new Runnable() { public void run() { tabFolder.setSelection(1); } }); } if (patientSetStr.equalsIgnoreCase("All")) { int minPatient = 0; try { String minText = patientMinNumText.getText(); minPatient = Integer.parseInt(minText); } catch (Exception e1) { minPatient = -1; } int maxPatient = 0; try { maxPatient = Integer.parseInt(patientMaxNumText.getText()); } catch (Exception e2) { maxPatient = -1; } PerformVisualizationQuery(oAwtContainer, "All", minPatient, maxPatient, bDisplayAllData); } else { int min = Integer.parseInt(patientMinNumText.getText()); int max = Integer.parseInt(patientMaxNumText.getText()); PerformVisualizationQuery(oAwtContainer, patientRefId, min, max, bDisplayAllData); } } }); addListener(SWT.Resize, new Listener() { public void handleEvent(Event event) { int w = getBounds().width; patientSetText.setBounds(70, 5, w - 357, 24); leftArrowButton.setBounds(w - 281, 5, 38, 24); patNum1.setBounds(w - 239, 9, 31, 24); patientMinNumText.setBounds(w - 204, 5, 45, 24); patNum2.setBounds(w - 149, 9, 57, 24); patientMaxNumText.setBounds(w - 92, 5, 45, 24); rightArrowButton.setBounds(w - 42, 5, 37, 24); } }); verticalForm.setWeights(new int[] { 25, 3 }); // Item 1: a Text Table TabItem item1 = new TabItem(tabFolder, SWT.NONE); item1.setText("Create model for Timeline"); Composite oModelComposite = new Composite(tabFolder, SWT.NONE); item1.setControl(oModelComposite); GridLayout gridLayout = new GridLayout(2, false); // gridLayout.marginHeight = 0; // gridLayout.marginWidth = 0; // gridLayout.verticalSpacing = 0; // gridLayout.horizontalSpacing = 0; gridLayout.marginTop = 2; gridLayout.marginLeft = 0; gridLayout.marginBottom = 2; gridLayout.verticalSpacing = 1; gridLayout.horizontalSpacing = 1; oModelComposite.setLayout(gridLayout); oModelQueryComposite = new FramedComposite(oModelComposite, SWT.SHADOW_NONE); // GridLayout gLq = new GridLayout(25, false); oModelQueryComposite.setLayout(new GridLayout(25, false)); oModelQueryComposite.setForeground(oTheParent.getDisplay().getSystemColor(SWT.COLOR_BLACK)); GridData oModelQueryButtonGridData = new GridData(GridData.FILL_HORIZONTAL); oModelQueryButtonGridData.grabExcessHorizontalSpace = false; oModelQueryButtonGridData.horizontalSpan = 2; oModelQueryButtonGridData.verticalAlignment = SWT.CENTER; oModelQueryButtonGridData.verticalIndent = 5; oModelQueryComposite.setLayoutData(oModelQueryButtonGridData); queryNamemrnlistText = new Label(oModelQueryComposite, SWT.NONE); queryNamemrnlistText.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); queryNamemrnlistText.setText("Query Name: "); // queryNamemrnlistText.setBounds(5, 4, 600, 20); queryNamemrnlistText.addMouseTrackListener(new MouseTrackListener() { public void mouseEnter(MouseEvent arg0) { oModelQueryComposite.setForeground(oTheParent.getDisplay().getSystemColor(SWT.COLOR_YELLOW)); } public void mouseExit(MouseEvent arg0) { oModelQueryComposite.setForeground(oTheParent.getDisplay().getSystemColor(SWT.COLOR_BLACK)); } public void mouseHover(MouseEvent arg0) { oModelQueryComposite.setForeground(oTheParent.getDisplay().getSystemColor(SWT.COLOR_YELLOW)); } }); oModelQueryComposite.addMouseMoveListener(new MouseMoveListener() { public void mouseMove(MouseEvent arg0) { // System.out.println("mouse moved"); } }); oModelQueryComposite.addDragDetectListener(new DragDetectListener() { public void dragDetected(DragDetectEvent arg0) { // System.out.println("drag moved"); } }); Composite oGroupComposite = new Composite(oModelComposite, SWT.NONE); // GridLayout gLq = new GridLayout(25, false); oGroupComposite.setLayout(gridLayout); GridData oGroupGridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL); oGroupGridData.grabExcessHorizontalSpace = true; oGroupGridData.grabExcessVerticalSpace = true; oGroupGridData.verticalIndent = 1; oGroupGridData.verticalSpan = GridData.VERTICAL_ALIGN_FILL; // oGroupGridData.verticalAlignment = GridData.VERTICAL_ALIGN_FILL; oGroupComposite.setLayoutData(oGroupGridData); oModelGroupComposite = new FramedComposite(oGroupComposite, SWT.SHADOW_NONE); // GridLayout gLq = new GridLayout(25, false); oModelGroupComposite.setLayout(new GridLayout(25, false)); GridData oModelGroupButtonGridData = new GridData(GridData.FILL_HORIZONTAL); oModelGroupButtonGridData.grabExcessHorizontalSpace = false; oModelGroupButtonGridData.horizontalSpan = 2; oModelGroupButtonGridData.verticalAlignment = SWT.CENTER; oModelGroupButtonGridData.verticalIndent = 5; oModelGroupComposite.setLayoutData(oModelGroupButtonGridData); // GridData gdAdd = new GridData(GridData.FILL_HORIZONTAL); GridData gdDel1 = new GridData(GridData.FILL_HORIZONTAL); groupNameText = new Label(oModelGroupComposite, SWT.NONE); gdDel1.horizontalSpan = 4; groupNameText.setLayoutData(gdDel1); groupNameText.setText("Panel Name: "); // groupNameText.setBounds(80, 8, 400, 24); // groupNameText.setAlignment(SWT.CENTER); // createDragSource(queryNamemrnlistText); // createDropTarget(queryNamemrnlistText); groupNameText.addMouseTrackListener(new MouseTrackListener() { public void mouseEnter(MouseEvent arg0) { oModelGroupComposite.setForeground(oTheParent.getDisplay().getSystemColor(SWT.COLOR_YELLOW)); } public void mouseExit(MouseEvent arg0) { oModelGroupComposite.setForeground(oTheParent.getDisplay().getSystemColor(SWT.COLOR_BLACK)); } public void mouseHover(MouseEvent arg0) { oModelGroupComposite.setForeground(oTheParent.getDisplay().getSystemColor(SWT.COLOR_YELLOW)); } }); // put a table in tabItem1... table = new KTable(oGroupComposite, SWT.V_SCROLL | SWT.H_SCROLL | SWT.BORDER); table.setFocus(); table.setBackground(oTheParent.getDisplay().getSystemColor(SWT.COLOR_WHITE)); GridData tableGridData = new GridData(SWT.FILL, SWT.FILL, true, true); tableGridData.verticalIndent = 5; table.setLayoutData(tableGridData); table.setRowSelectionMode(true); // table.setMultiSelectionMode(true); // table.setModel(new KTableForModel()); table.setModel(new ConceptTableModel()); // table.getModel().setColumnWidth(0, oModelComposite.getBounds().width // - 35); table.addCellSelectionListener(new KTableCellSelectionListener() { public void cellSelected(int col, int row, int statemask) { log.debug("Cell [" + col + ";" + row + "] selected."); System.out.println("Cell [" + col + ";" + row + "] selected."); table.selectedRow = row; table.selectedColumn = col; } public void fixedCellSelected(int col, int row, int statemask) { log.debug("Header [" + col + ";" + row + "] selected."); System.out.println("Header [" + col + ";" + row + "] selected."); } }); Transfer[] types = new Transfer[] { TextTransfer.getInstance() }; // create drag source /* * DragSource source = new DragSource(queryNamemrnlistText, * DND.DROP_COPY); source.setTransfer(types); source.addDragListener(new * DragSourceAdapter() { * * @Override public void dragSetData(DragSourceEvent event) { * //DragSource ds = (DragSource) event.widget; StringWriter strWriter = * new StringWriter(); DndType dndType = new DndType(); * edu.harvard.i2b2.crcxmljaxb.datavo.psm.query.ObjectFactory pdoFactory * = new edu.harvard.i2b2.crcxmljaxb.datavo.psm.query.ObjectFactory(); * PanelType panelType = new PanelType(); * * //get table rows and fill the panel object for(int i=0; i<3; i++) { * ItemType itemType = new ItemType(); * panelType.getItem().add(itemType); * * dndType.getAny().add(pdoFactory.createPanel(panelType)); * edu.harvard.i2b2.crcxmljaxb.datavo.dnd.ObjectFactory dndFactory = new * edu.harvard.i2b2.crcxmljaxb.datavo.dnd.ObjectFactory(); try { * ExplorerJAXBUtil * .getJAXBUtil().marshaller(dndFactory.createPluginDragDrop(dndType), * strWriter); } catch(JAXBUtilException e) { e.printStackTrace(); } * * //put the data into the event event.data = strWriter.toString(); } * * * }); */ Composite oModelAddDelButtonComposite = new Composite(oModelComposite, SWT.NONE); GridLayout gL = new GridLayout(25, false); oModelAddDelButtonComposite.setLayout(gL); GridData oModelAddDelButtonGridData = new GridData(GridData.FILL_HORIZONTAL);// HORIZONTAL_ALIGN_FILL);// | // GridData.VERTICAL_ALIGN_FILL); oModelAddDelButtonGridData.grabExcessHorizontalSpace = false; oModelAddDelButtonGridData.horizontalSpan = 2; oModelAddDelButtonComposite.setLayoutData(oModelAddDelButtonGridData); // GridData gdAdd = new GridData(GridData.FILL_HORIZONTAL); GridData gdDel = new GridData(GridData.FILL_HORIZONTAL); Button deleteArrowButton = new Button(oModelAddDelButtonComposite, SWT.PUSH); gdDel.horizontalSpan = 4; deleteArrowButton.setLayoutData(gdDel); deleteArrowButton.setText("Delete From List"); deleteArrowButton.addSelectionListener(new SelectionAdapter() { @SuppressWarnings("unchecked") public void widgetSelected(SelectionEvent event) { curRowNumber = 0; ConceptTableModel m_Model = (ConceptTableModel) table.getModel(); int[] selectedRow = table.getRowSelection(); m_Model.fillDataFromTable(rowData); if ((selectedRow != null) && (selectedRow.length > 0)) { String conceptName = (String) m_Model.getContentAt(1, selectedRow[0]); if (conceptName.equals("Encounter Range Line")) { } else if (conceptName.equals("Vital Status Line")) { } int rowNumber = new Integer((String) (m_Model.getContentAt(0, selectedRow[0]))).intValue(); int rid = selectedRow[0]; ArrayList list = (ArrayList) rowData.get(rowNumber - 1); for (int i = 0; i < list.size(); i++) { ConceptTableRow tr = (ConceptTableRow) list.get(i); if (tr.rowId == rid) { list.remove(i); break; } } if (list.size() == 0) { rowData.remove(rowNumber - 1); } curRowNumber = rowData.size(); resetRowNumber(); // m_Model.deleteRow(selectedRow[0]); ((ConceptTableModel) table.getModel()).deleteAllRows(); ((ConceptTableModel) table.getModel()).populateTable(rowData); /* * int newRow = 0; for(int i=0; i<rowData.size(); i++) { * ArrayList alist = (ArrayList) rowData.get(i); for(int * j=0; j<alist.size(); j++) { TableRow r = (TableRow) * alist.get(j); newRow++; r.rowId = newRow; * table.getModel().setContentAt(0, newRow, new * Integer(r.rowNumber).toString()); * table.getModel().setContentAt(1, newRow, r.conceptName); * table.getModel().setContentAt(2, newRow, r.valueType); * table.getModel().setContentAt(3, newRow, r.valueText); * table.getModel().setContentAt(4, newRow, r.height); * table.getModel().setContentAt(5, newRow, r.color); * table.getModel().setContentAt(6, newRow, r.conceptXml); } * } */ table.redraw(); } } }); Button deleteAllButton = new Button(oModelAddDelButtonComposite, SWT.PUSH); gdDel = new GridData(GridData.FILL_HORIZONTAL); gdDel.horizontalSpan = 4; deleteAllButton.setLayoutData(gdDel); deleteAllButton.setText("Delete All "); deleteAllButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { ConceptTableModel m_Model = (ConceptTableModel) table.getModel(); m_Model.deleteAllRows(); curRowNumber = 0; rowData.clear(); table.redraw(); } }); Button putInOrderButton = new Button(oModelAddDelButtonComposite, SWT.PUSH); gdDel = new GridData(GridData.FILL_HORIZONTAL); gdDel.horizontalSpan = 4; putInOrderButton.setLayoutData(gdDel); putInOrderButton.setText("Put In Order "); putInOrderButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { ConceptTableModel m_Model = (ConceptTableModel) table.getModel(); curRowNumber = 0; m_Model.fillDataFromTable(rowData); Collections.sort(rowData, new Comparator<Object>() { @SuppressWarnings("unchecked") public int compare(Object o1, Object o2) { int i1 = ((ConceptTableRow) ((ArrayList) o1).get(0)).rowNumber; int i2 = ((ConceptTableRow) ((ArrayList) o2).get(0)).rowNumber; if (i1 > i2) { return 1; } else if (i1 < i2) { return -1; } else { return 0; } } }); m_Model.deleteAllRows(); m_Model.populateTable(rowData); table.redraw(); } }); Button upArrowButton = new Button(oModelAddDelButtonComposite, SWT.PUSH); upArrowButton.setText("Move Up"); upArrowButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { ConceptTableModel m_Model = (ConceptTableModel) table.getModel(); int[] selectedRow = table.getRowSelection(); curRowNumber = 0; // KTableI2B2Model m_Model = (KTableI2B2Model) table.getModel(); // int[] selectedRow = table.getRowSelection(); m_Model.fillDataFromTable(rowData); int index = new Integer((String) (m_Model.getContentAt(0, selectedRow[0]))).intValue() - 1; if (index < 1) { return; } if ((selectedRow != null) && (selectedRow.length > 0)) { // m_Model.moveRow(selectedRow[0], selectedRow[0] -1); ArrayList<ConceptTableRow> list = rowData.get(index); rowData.remove(index); rowData.add(index - 1, list); resetRowNumber(); m_Model.populateTable(rowData); } table.setSelection(0, selectedRow[0] - 1, true); table.redraw(); } }); Button downArrowButton = new Button(oModelAddDelButtonComposite, SWT.PUSH); downArrowButton.setText("Move Down"); downArrowButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { ConceptTableModel m_Model = (ConceptTableModel) table.getModel(); int[] selectedRow = table.getRowSelection(); curRowNumber = 0; // KTableI2B2Model m_Model = (KTableI2B2Model) table.getModel(); // int[] selectedRow = table.getRowSelection(); m_Model.fillDataFromTable(rowData); int index = new Integer((String) (m_Model.getContentAt(0, selectedRow[0]))).intValue() - 1; if (index == (rowData.size() - 1)) { return; } if ((selectedRow != null) && (selectedRow.length > 0)) { // m_Model.moveRow(selectedRow[0], selectedRow[0] -1); ArrayList<ConceptTableRow> list = rowData.get(index); rowData.remove(index); rowData.add(index + 1, list); resetRowNumber(); m_Model.populateTable(rowData); } table.setSelection(0, selectedRow[0] + 1, true); table.redraw(); } }); Composite oModelCheckButtonComposite = new Composite(oModelComposite, SWT.NONE); GridLayout gL1 = new GridLayout(20, true); oModelCheckButtonComposite.setLayout(gL1); GridData oModelCheckButtonGridData = new GridData( GridData.HORIZONTAL_ALIGN_FILL | GridData.VERTICAL_ALIGN_FILL); oModelCheckButtonGridData.grabExcessHorizontalSpace = true; oModelCheckButtonGridData.horizontalSpan = 2; oModelCheckButtonComposite.setLayoutData(oModelCheckButtonGridData); Button displayOrNotButton = new Button(oModelCheckButtonComposite, SWT.CHECK); displayOrNotButton.setText("Display concepts with no data"); displayOrNotButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { // do something here- return null bDisplayAllData = !bDisplayAllData; } }); Button displayDemographicsOrNotButton = new Button(oModelCheckButtonComposite, SWT.CHECK); displayDemographicsOrNotButton.setText("Display patient demographics"); if ((System.getProperty("applicationName") != null) && System.getProperty("applicationName").equals("BIRN")) { displayDemographicsOrNotButton.setSelection(false); displayDemographicsOrNotButton.setEnabled(false); bDisplayDemographics = false; } else if ((System.getProperty("applicationName") == null) || System.getProperty("applicationName").equals("i2b2")) { displayDemographicsOrNotButton.setSelection(true); } displayDemographicsOrNotButton.addSelectionListener(new SelectionAdapter() { public void widgetSelected(SelectionEvent event) { bDisplayDemographics = !bDisplayDemographics; } }); if (UserInfoBean.getInstance().getCellDataUrl("identity") != null) { Composite oPatientSetComposite = new Composite(oModelComposite, SWT.NONE); GridData patientSetData = new GridData(GridData.HORIZONTAL_ALIGN_FILL); patientSetData.grabExcessHorizontalSpace = true; oPatientSetComposite.setLayoutData(patientSetData); oPatientSetComposite.setLayout(null); Label mrnlabel = new Label(oPatientSetComposite, SWT.NONE); mrnlabel.setText("MRN site:"); mrnlabel.setBounds(5, 9, 50, 20); final Combo siteCombo = new Combo(oPatientSetComposite, SWT.NULL); siteCombo.add("BWH"); siteCombo.add("MGH"); siteCombo.setBounds(57, 5, 60, 20); siteCombo.select(1); Label mrnNumber = new Label(oPatientSetComposite, SWT.NONE); mrnNumber.setText("number:"); mrnNumber.setBounds(121, 9, 40, 20); mrnlistText = new Text(oPatientSetComposite, SWT.SINGLE | SWT.BORDER); mrnlistText.setBounds(164, 5, 150, 20); mrnlistText.setText(""); Button runButton = new Button(oPatientSetComposite, SWT.PUSH); runButton.setText("Search By MRN"); runButton.setBounds(315, 5, 85, 23); runButton.addSelectionListener(new SelectionAdapter() { @SuppressWarnings("unchecked") public void widgetSelected(SelectionEvent event) { String mrns = mrnlistText.getText(); if (mrns.equals("")) { return; } String[] mrnArray = mrns.split(","); int[] idlist = new int[mrnArray.length]; String username = UserInfoBean.getInstance().getUserName(); String password = UserInfoBean.getInstance().getUserPassword(); // log.debug("User name: "+username+" password: "+password); String site = siteCombo.getText(); for (int i = 0; i < mrnArray.length; i++) { // String[] tmps = new String[2]; String tmp = mrnArray[i].replaceAll(" ", ""); // tmps = tmp.split(":"); String queryStr = "<?xml version=\"1.0\" standalone=\"yes\"?>\n" + "<search_by_local>" + "<match_id site=\"" + site.toUpperCase()/* EMPI */ + "\">" + tmp/* 100016900 */ + "</match_id>\n" + "</search_by_local>"; String resultStr = QueryClient.query(queryStr, username, password); log.debug(queryStr); log.debug(resultStr); SAXBuilder parser = new SAXBuilder(); String masterID = null; java.io.StringReader xmlStringReader = new java.io.StringReader(resultStr); try { org.jdom.Document tableDoc = parser.build(xmlStringReader); org.jdom.Element tableXml = tableDoc.getRootElement(); Element responseXml = (Element) tableXml.getChild("person_list"); // Element mrnXml = (Element) // responseXml.getChild("MRN"); java.util.List listChildren = responseXml.getChildren(); if (listChildren.isEmpty()) { MessageBox mBox = new MessageBox(table.getShell(), SWT.ICON_INFORMATION | SWT.OK); mBox.setText("Please Note ..."); mBox.setMessage("No master id found"); mBox.open(); return; } Element masterXml = (Element) responseXml.getChild("master_record"); masterID = masterXml.getAttributeValue("id"); log.debug("Patient id: " + masterID); idlist[i] = new Integer(masterID).intValue(); log.debug("MRN: " + site + "-" + tmp); } catch (Exception e1) { e1.printStackTrace(); } } if (tabFolder.getSelectionIndex() == 1) { DestroyMiniVisualization(oAwtContainer); } else if (tabFolder.getSelectionIndex() == 0) { oTheParent.getDisplay().syncExec(new Runnable() { public void run() { tabFolder.setSelection(1); } }); } PerformVisualizationQuery(oAwtContainer, idlist, bDisplayAllData); } }); } DropTarget targetLable = new DropTarget(oModelQueryComposite, DND.DROP_COPY); targetLable.setTransfer(types); targetLable.addDropListener(new DropTargetAdapter() { @Override public void dragLeave(DropTargetEvent event) { super.dragLeave(event); oModelQueryComposite.setForeground(oTheParent.getDisplay().getSystemColor(SWT.COLOR_BLACK)); } public void dragEnter(DropTargetEvent event) { event.detail = DND.DROP_COPY; oModelQueryComposite.setForeground(oTheParent.getDisplay().getSystemColor(SWT.COLOR_YELLOW)); } @SuppressWarnings("unchecked") public void drop(DropTargetEvent event) { if (event.data == null) { event.detail = DND.DROP_NONE; return; } try { SAXBuilder parser = new SAXBuilder(); String xmlContent = (String) event.data; java.io.StringReader xmlStringReader = new java.io.StringReader(xmlContent); org.jdom.Document tableDoc = parser.build(xmlStringReader); org.jdom.Element tableXml = tableDoc.getRootElement().getChild("concepts", Namespace.getNamespace("http://www.i2b2.org/xsd/cell/ont/1.1/")); if (tableXml != null) { MessageBox mBox = new MessageBox(table.getShell(), SWT.ICON_INFORMATION | SWT.OK); mBox.setText("Please Note ..."); mBox.setMessage("You can not drop this item here."); mBox.open(); event.detail = DND.DROP_NONE; return; } boolean isQuery = false; if (tableXml == null) { tableXml = tableDoc.getRootElement().getChild("query_master", Namespace.getNamespace("http://www.i2b2.org/xsd/cell/crc/psm/1.1/")); } if (tableXml != null) { isQuery = true; } else { MessageBox mBox = new MessageBox(table.getShell(), SWT.ICON_INFORMATION | SWT.OK); mBox.setText("Please Note ..."); mBox.setMessage("You can not drop this item here."); mBox.open(); event.detail = DND.DROP_NONE; return; } if (isQuery) { ArrayList<QueryModel> nodeXmls = new ArrayList<QueryModel>(); try { JAXBUtil jaxbUtil = AnalysisJAXBUtil.getJAXBUtil(); QueryMasterData ndata = new QueryMasterData(); ndata.name(tableXml.getChildText("name")); queryNamemrnlistText.setText("Query Name: " + ndata.name()); ndata.xmlContent(null); ndata.id(tableXml.getChildTextTrim("query_master_id")); ndata.userId(tableXml.getChildTextTrim("user_id")); String xmlcontent = null; String xmlrequest = null; xmlrequest = ndata.writeDefinitionQueryXML(); lastRequestMessage(xmlrequest); if (System.getProperty("webServiceMethod").equals("SOAP")) { xmlcontent = CRCQueryClient.sendPDQQueryRequestSOAP(xmlrequest); } else { xmlcontent = CRCQueryClient.sendPDQQueryRequestREST(xmlrequest); } lastResponseMessage(xmlcontent); if (xmlcontent == null) { return; } else { log.debug("Query content response: " + xmlcontent); ndata.xmlContent(xmlcontent); } JAXBElement jaxbElement = jaxbUtil.unMashallFromString(ndata.xmlContent()); ResponseMessageType messageType = (ResponseMessageType) jaxbElement.getValue(); BodyType bt = messageType.getMessageBody(); MasterResponseType masterResponseType = (MasterResponseType) new JAXBUnWrapHelper() .getObjectByClass(bt.getAny(), MasterResponseType.class); RequestXmlType requestXmlType = masterResponseType.getQueryMaster().get(0) .getRequestXml(); org.w3c.dom.Element element = (org.w3c.dom.Element) requestXmlType.getContent().get(0); if (element != null) { log.debug("query definition not null"); } else { log.error("query definition is null"); } String domString = edu.harvard.i2b2.common.util.xml.XMLUtil .convertDOMElementToString(element); log.debug("string output" + domString); JAXBContext jc1 = JAXBContext .newInstance(edu.harvard.i2b2.crcxmljaxb.datavo.psm.query.ObjectFactory.class); Unmarshaller unMarshaller = jc1.createUnmarshaller(); JAXBElement queryDefinitionJaxbElement = (JAXBElement) unMarshaller .unmarshal(new StringReader(domString)); QueryDefinitionType queryDefinitionType = (QueryDefinitionType) queryDefinitionJaxbElement .getValue(); int numOfPanels = queryDefinitionType.getPanel().size(); for (int i = 0; i < numOfPanels; i++) { PanelType panelType = queryDefinitionType.getPanel().get(i); for (int j = 0; j < panelType.getItem().size(); j++) { ItemType itemType = panelType.getItem().get(j); QueryModel nodedata = new QueryModel(); nodedata.name(itemType.getItemName()); nodedata.visualAttribute("FA"); nodedata.tooltip(itemType.getTooltip()); nodedata.fullname(itemType.getItemKey()); nodedata.hlevel(new Integer(itemType.getHlevel()).toString()); if (itemType.getItemShape() != null) { nodedata.tableRow().height = new String(itemType.getItemShape()); nodedata.tableRow().color = ((ConceptTableModel) table.getModel()) .getColor(itemType.getItemColor()); nodedata.tableRow().rowNumber = Integer .parseInt(itemType.getItemRowNumber()); } else { nodedata.tableRow().height = "Medium"; nodedata.tableRow().color = new RGB(0, 0, 128); nodedata.tableRow().rowNumber = j + 1; } nodedata.constrainByValue(itemType.getConstrainByValue()); if (itemType.getConstrainByValue().size() > 0) { nodedata.setValueConstrains(itemType.getConstrainByValue()); if (itemType.getConstrainByValue().size() > 0) { nodedata.setValueConstrains(itemType.getConstrainByValue()); if (nodedata.valueModel().hasEnumValue()) { if (nodedata.valueModel().useTextValue()) { ArrayList<String> results = new ArrayList<String>(); results.toArray(nodedata.valueModel().value().split(",")); nodedata.valueModel().selectedValues = results; } } } } // Handle Constrain By Dates for (int u = 0; u < itemType.getConstrainByDate().size(); u++) { nodedata.setTimeConstrain( itemType.getConstrainByDate().get(u).getDateFrom(), itemType.getConstrainByDate().get(u).getDateTo()); } String status = nodedata.setXmlContent(); if (status.equalsIgnoreCase("error")) { MessageBox mBox = new MessageBox(table.getShell(), SWT.ICON_INFORMATION | SWT.OK); mBox.setText("Please Note ..."); mBox.setMessage( "Response delivered from the remote server could not be understood,\n" + "you may wish to retry your last action."); mBox.open(); event.detail = DND.DROP_NONE; return; } nodeXmls.add(nodedata); } } populateTable(nodeXmls); // get query instance String xmlRequest = ndata.writeContentQueryXML(); lastRequestMessage(xmlRequest); String xmlResponse = CRCQueryClient.sendPDQQueryRequestREST(xmlRequest); lastResponseMessage(xmlResponse); jaxbElement = jaxbUtil.unMashallFromString(xmlResponse); messageType = (ResponseMessageType) jaxbElement.getValue(); bt = messageType.getMessageBody(); InstanceResponseType instanceResponseType = (InstanceResponseType) new JAXBUnWrapHelper() .getObjectByClass(bt.getAny(), InstanceResponseType.class); QueryInstanceData instanceData = null; XMLGregorianCalendar startDate = null; for (QueryInstanceType queryInstanceType : instanceResponseType.getQueryInstance()) { QueryInstanceData runData = new QueryInstanceData(); runData.visualAttribute("FA"); runData.tooltip("The results of the query run"); runData.id(new Integer(queryInstanceType.getQueryInstanceId()).toString()); XMLGregorianCalendar cldr = queryInstanceType.getStartDate(); runData.name("Results of " + "[" + cldr.getMonth() + "-" + cldr.getDay() + "-" + cldr.getYear() + " " + cldr.getHour() + ":" + cldr.getMinute() + ":" + cldr.getSecond() + "]"); if (instanceData == null) { startDate = cldr; instanceData = runData; } else { if (cldr.toGregorianCalendar().compareTo(startDate.toGregorianCalendar()) > 0) { startDate = cldr; instanceData = runData; } } } // get patient set if (instanceData == null) { event.detail = DND.DROP_NONE; return; } log.debug("Got query instance: " + instanceData.name()); xmlRequest = instanceData.writeContentQueryXML(); lastRequestMessage(xmlRequest); xmlResponse = CRCQueryClient.sendPDQQueryRequestREST(xmlRequest); lastResponseMessage(xmlResponse); jaxbElement = jaxbUtil.unMashallFromString(xmlResponse); messageType = (ResponseMessageType) jaxbElement.getValue(); bt = messageType.getMessageBody(); ResultResponseType resultResponseType = (ResultResponseType) new JAXBUnWrapHelper() .getObjectByClass(bt.getAny(), ResultResponseType.class); for (QueryResultInstanceType queryResultInstanceType : resultResponseType .getQueryResultInstance()) { if (!(queryResultInstanceType.getQueryResultType().getName() .equalsIgnoreCase("PATIENTSET"))) { continue; } String status = queryResultInstanceType.getQueryStatusType().getName(); if (status.equalsIgnoreCase("FINISHED")) { String setId = new Integer(queryResultInstanceType.getResultInstanceId()) .toString(); String setSize = new Integer(queryResultInstanceType.getSetSize()).toString(); patientSetText.setText("Patient Set: " + setSize + " patients"); patientRefId = new String(setId); patientMinNumText.setText("1"); leftArrowButton.setEnabled(false); int maxPatientNum = new Integer(patientMaxNumText.getText()).intValue(); patientSetSize = queryResultInstanceType.getSetSize(); if (patientSetSize > maxPatientNum) { rightArrowButton.setEnabled(true); patientMaxNumText.setText("10"); } else { rightArrowButton.setEnabled(false); if (patientSetSize > 0) { patientMaxNumText.setText(setSize); } } log.debug("Dropped set of: " + setSize + " patients"/* strs[0] */ + " with refId: " + setId/* * strs[ 1 ] */); } else { // message } } } catch (Exception e) { e.printStackTrace(); return; } } /* * else { List conceptChildren = tableXml.getChildren(); * parseDropConcepts(conceptChildren, event); * table.redraw(); } */ event.detail = DND.DROP_NONE; } catch (JDOMException e) { System.err.println(e.getMessage()); MessageBox mBox = new MessageBox(table.getShell(), SWT.ICON_INFORMATION | SWT.OK); mBox.setText("Please Note ..."); mBox.setMessage("You can not drop this item here."); mBox.open(); event.detail = DND.DROP_NONE; e.printStackTrace(); return; } catch (Exception e) { System.err.println(e.getMessage()); event.detail = DND.DROP_NONE; e.printStackTrace(); return; } } }); // create drag source DragSource source1 = new DragSource(groupNameText, DND.DROP_COPY); source1.setTransfer(types); source1.addDragListener(new DragSourceAdapter() { @Override public void dragSetData(DragSourceEvent event) { ConceptTableModel i2b2Model = (ConceptTableModel) table.getModel(); i2b2Model.fillDataFromTable(rowData); if (rowData.size() == 0) { oTheParent.getDisplay().syncExec(new Runnable() { public void run() { tabFolder.setSelection(0); } }); MessageBox mBox = new MessageBox(table.getShell(), SWT.ICON_INFORMATION | SWT.OK); mBox.setText("Please Note ..."); mBox.setMessage("The set up table is empty."); mBox.open(); return; } StringWriter strWriter = new StringWriter(); DndType dndType = new DndType(); edu.harvard.i2b2.crcxmljaxb.datavo.psm.query.ObjectFactory pdoFactory = new edu.harvard.i2b2.crcxmljaxb.datavo.psm.query.ObjectFactory(); PanelType panelType = new PanelType(); panelType.setInvert(0); PanelType.TotalItemOccurrences totalOccurrences = new PanelType.TotalItemOccurrences(); totalOccurrences.setValue(1); panelType.setTotalItemOccurrences(totalOccurrences); panelType.setPanelNumber(0 + 1); // panelType.setName(panelData.getItems().get(0).name() + "_" // + generateMessageId().substring(0, 4)); panelType.setName("Panel-1"); // TO DO: get table rows and fill the panel object for (int i = 1; i < i2b2Model.getRowCount(); i++) { QueryModel node = (QueryModel) i2b2Model.getContentAt(7, i); ItemType itemType = new ItemType(); itemType.setItemKey(node.fullname()); itemType.setItemName(node.name()); itemType.setTooltip(node.tooltip()); itemType.setHlevel(Integer.parseInt(node.hlevel())); itemType.setClazz("ENC"); itemType.setItemIcon(node.visualAttribute().trim()); itemType.setItemColor(i2b2Model.getColorString((RGB) i2b2Model.getContentAt(5, i))); itemType.setItemRowNumber((String) i2b2Model.getContentAt(0, i)); itemType.setItemShape((String) i2b2Model.getContentAt(4, i)); itemType.getConstrainByValue().add(node.valueModel().writeValueConstrain()); itemType.getConstrainByDate().add(node.writeTimeConstrain()); panelType.getItem().add(itemType); } dndType.getAny().add(pdoFactory.createPanel(panelType)); edu.harvard.i2b2.crcxmljaxb.datavo.dnd.ObjectFactory dndFactory = new edu.harvard.i2b2.crcxmljaxb.datavo.dnd.ObjectFactory(); try { AnalysisJAXBUtil.getJAXBUtil().marshaller(dndFactory.createPluginDragDrop(dndType), strWriter); } catch (JAXBUtilException e) { e.printStackTrace(); } // put the data into the event event.data = strWriter.toString(); } }); DropTarget nameTarget = new DropTarget(groupNameText, DND.DROP_COPY); nameTarget.setTransfer(types); nameTarget.addDropListener(new DropTargetAdapter() { @Override public void dragLeave(DropTargetEvent event) { super.dragLeave(event); oModelGroupComposite.setForeground(oTheParent.getDisplay().getSystemColor(SWT.COLOR_BLACK)); } @SuppressWarnings("unchecked") public void drop(DropTargetEvent event) { if (event.data == null) { event.detail = DND.DROP_NONE; return; } ArrayList<QueryModel> nodeXmls = new ArrayList<QueryModel>(); try { SAXBuilder parser = new SAXBuilder(); String xmlContent = (String) event.data; java.io.StringReader xmlStringReader = new java.io.StringReader(xmlContent); org.jdom.Document panelDoc = parser.build(xmlStringReader); org.jdom.Element panelXml = panelDoc.getRootElement().getChild("panel", Namespace.getNamespace("http://www.i2b2.org/xsd/cell/crc/psm/querydefinition/1.1/")); if (panelXml == null) { MessageBox mBox = new MessageBox(table.getShell(), SWT.ICON_INFORMATION | SWT.OK); mBox.setText("Please Note ..."); mBox.setMessage("You can not drop this item here."); mBox.open(); event.detail = DND.DROP_NONE; return; } else { String domString = (new XMLOutputter()).outputString(panelXml); JAXBContext jc1 = JAXBContext .newInstance(edu.harvard.i2b2.crcxmljaxb.datavo.psm.query.ObjectFactory.class); Unmarshaller unMarshaller = jc1.createUnmarshaller(); JAXBElement panelJaxbElement = (JAXBElement) unMarshaller .unmarshal(new StringReader(domString)); PanelType panelType = (PanelType) panelJaxbElement.getValue(); String panelname = panelType.getName(); groupNameText.setText("Panel Name: " + panelname); for (int j = 0; j < panelType.getItem().size(); j++) { ItemType itemType = panelType.getItem().get(j); QueryModel nodedata = new QueryModel(); nodedata.name(itemType.getItemName()); nodedata.visualAttribute("FA"); nodedata.tooltip(itemType.getTooltip()); nodedata.fullname(itemType.getItemKey()); nodedata.hlevel(new Integer(itemType.getHlevel()).toString()); // / need to handle query tool generated panels if (itemType.getItemShape() != null) { nodedata.tableRow().height = new String(itemType.getItemShape()); nodedata.tableRow().color = ((ConceptTableModel) table.getModel()) .getColor(itemType.getItemColor()); nodedata.tableRow().rowNumber = Integer.parseInt(itemType.getItemRowNumber()); } else { nodedata.tableRow().height = "Medium"; nodedata.tableRow().color = new RGB(0, 0, 128); nodedata.tableRow().rowNumber = j + 1; } nodedata.constrainByValue(itemType.getConstrainByValue()); if (itemType.getConstrainByValue().size() > 0) { nodedata.setValueConstrains(itemType.getConstrainByValue()); if (itemType.getConstrainByValue().size() > 0) { nodedata.setValueConstrains(itemType.getConstrainByValue()); if (nodedata.valueModel().hasEnumValue()) { if (nodedata.valueModel().useTextValue()) { ArrayList<String> results = new ArrayList<String>(); results.toArray(nodedata.valueModel().value().split(",")); nodedata.valueModel().selectedValues = results; } } } } // Handle Constrain By Dates for (int u = 0; u < itemType.getConstrainByDate().size(); u++) { nodedata.setTimeConstrain(itemType.getConstrainByDate().get(u).getDateFrom(), itemType.getConstrainByDate().get(u).getDateTo()); } String status = nodedata.setXmlContent(); if (status.equalsIgnoreCase("error")) { MessageBox mBox = new MessageBox(table.getShell(), SWT.ICON_INFORMATION | SWT.OK); mBox.setText("Please Note ..."); mBox.setMessage( "Response delivered from the remote server could not be understood,\n" + "you may wish to retry your last action."); mBox.open(); event.detail = DND.DROP_NONE; return; } nodeXmls.add(nodedata); } // event.detail = DND.DROP_NONE; } populateTable(nodeXmls); } catch (JDOMException e) { System.err.println(e.getMessage()); MessageBox mBox = new MessageBox(table.getShell(), SWT.ICON_INFORMATION | SWT.OK); mBox.setText("Please Note ..."); mBox.setMessage("You can not drop this item here."); mBox.open(); event.detail = DND.DROP_NONE; e.printStackTrace(); return; } catch (Exception e) { System.err.println(e.getMessage()); event.detail = DND.DROP_NONE; e.printStackTrace(); return; } } public void dragEnter(DropTargetEvent event) { TextTransfer textTransfer = TextTransfer.getInstance(); if (textTransfer.isSupportedType(event.currentDataType)) { event.detail = DND.DROP_COPY; } oModelGroupComposite.setForeground(oTheParent.getDisplay().getSystemColor(SWT.COLOR_YELLOW)); } }); DropTarget target = new DropTarget(table, DND.DROP_COPY); target.setTransfer(types); target.addDropListener(new DropTargetAdapter() { @SuppressWarnings("unchecked") public void drop(DropTargetEvent event) { if (event.data == null) { event.detail = DND.DROP_NONE; return; } try { SAXBuilder parser = new SAXBuilder(); String xmlContent = (String) event.data; java.io.StringReader xmlStringReader = new java.io.StringReader(xmlContent); org.jdom.Document tableDoc = parser.build(xmlStringReader); org.jdom.Element tableXml = tableDoc.getRootElement().getChild("concepts", Namespace.getNamespace("http://www.i2b2.org/xsd/cell/ont/1.1/")); boolean isQuery = false; if (tableXml == null) { MessageBox mBox = new MessageBox(table.getShell(), SWT.ICON_INFORMATION | SWT.OK); mBox.setText("Please Note ..."); mBox.setMessage("You can not drop this item here."); mBox.open(); event.detail = DND.DROP_NONE; return; } if (isQuery) { ArrayList<QueryModel> nodeXmls = new ArrayList<QueryModel>(); try { JAXBUtil jaxbUtil = AnalysisJAXBUtil.getJAXBUtil(); QueryMasterData ndata = new QueryMasterData(); ndata.name(tableXml.getChildText("name")); queryNamemrnlistText.setText(ndata.name()); ndata.xmlContent(null); ndata.id(tableXml.getChildTextTrim("query_master_id")); ndata.userId(tableXml.getChildTextTrim("user_id")); String xmlcontent = null; String xmlrequest = null; xmlrequest = ndata.writeDefinitionQueryXML(); lastRequestMessage(xmlrequest); if (System.getProperty("webServiceMethod").equals("SOAP")) { xmlcontent = CRCQueryClient.sendPDQQueryRequestSOAP(xmlrequest); } else { xmlcontent = CRCQueryClient.sendPDQQueryRequestREST(xmlrequest); } lastResponseMessage(xmlcontent); if (xmlcontent == null) { return; } else { log.debug("Query content response: " + xmlcontent); ndata.xmlContent(xmlcontent); } JAXBElement jaxbElement = jaxbUtil.unMashallFromString(ndata.xmlContent()); ResponseMessageType messageType = (ResponseMessageType) jaxbElement.getValue(); BodyType bt = messageType.getMessageBody(); MasterResponseType masterResponseType = (MasterResponseType) new JAXBUnWrapHelper() .getObjectByClass(bt.getAny(), MasterResponseType.class); RequestXmlType requestXmlType = masterResponseType.getQueryMaster().get(0) .getRequestXml(); org.w3c.dom.Element element = (org.w3c.dom.Element) requestXmlType.getContent().get(0); if (element != null) { log.debug("query definition not null"); } else { log.error("query definition is null"); } String domString = edu.harvard.i2b2.common.util.xml.XMLUtil .convertDOMElementToString(element); log.debug("string output" + domString); JAXBContext jc1 = JAXBContext .newInstance(edu.harvard.i2b2.crcxmljaxb.datavo.psm.query.ObjectFactory.class); Unmarshaller unMarshaller = jc1.createUnmarshaller(); JAXBElement queryDefinitionJaxbElement = (JAXBElement) unMarshaller .unmarshal(new StringReader(domString)); QueryDefinitionType queryDefinitionType = (QueryDefinitionType) queryDefinitionJaxbElement .getValue(); int numOfPanels = queryDefinitionType.getPanel().size(); for (int i = 0; i < numOfPanels; i++) { PanelType panelType = queryDefinitionType.getPanel().get(i); for (int j = 0; j < panelType.getItem().size(); j++) { ItemType itemType = panelType.getItem().get(j); QueryModel nodedata = new QueryModel(); nodedata.name(itemType.getItemName()); nodedata.visualAttribute("FA"); nodedata.tooltip(itemType.getTooltip()); nodedata.fullname(itemType.getItemKey()); nodedata.hlevel(new Integer(itemType.getHlevel()).toString()); String status = nodedata.setXmlContent(); if (status.equalsIgnoreCase("error")) { MessageBox mBox = new MessageBox(table.getShell(), SWT.ICON_INFORMATION | SWT.OK); mBox.setText("Please Note ..."); mBox.setMessage( "Response delivered from the remote server could not be understood,\n" + "you may wish to retry your last action."); mBox.open(); event.detail = DND.DROP_NONE; return; } nodeXmls.add(nodedata); } } populateTable(nodeXmls); // get query instance String xmlRequest = ndata.writeContentQueryXML(); lastRequestMessage(xmlRequest); // log.debug(xmlRequest); String xmlResponse = CRCQueryClient.sendPDQQueryRequestREST(xmlRequest); lastResponseMessage(xmlResponse); jaxbElement = jaxbUtil.unMashallFromString(xmlResponse); messageType = (ResponseMessageType) jaxbElement.getValue(); bt = messageType.getMessageBody(); InstanceResponseType instanceResponseType = (InstanceResponseType) new JAXBUnWrapHelper() .getObjectByClass(bt.getAny(), InstanceResponseType.class); QueryInstanceData instanceData = null; XMLGregorianCalendar startDate = null; for (QueryInstanceType queryInstanceType : instanceResponseType.getQueryInstance()) { QueryInstanceData runData = new QueryInstanceData(); runData.visualAttribute("FA"); runData.tooltip("The results of the query run"); runData.id(new Integer(queryInstanceType.getQueryInstanceId()).toString()); XMLGregorianCalendar cldr = queryInstanceType.getStartDate(); runData.name("Results of " + "[" + cldr.getMonth() + "-" + cldr.getDay() + "-" + cldr.getYear() + " " + cldr.getHour() + ":" + cldr.getMinute() + ":" + cldr.getSecond() + "]"); if (instanceData == null) { startDate = cldr; instanceData = runData; } else { if (cldr.toGregorianCalendar().compareTo(startDate.toGregorianCalendar()) > 0) { startDate = cldr; instanceData = runData; } } } // get patient set if (instanceData == null) { event.detail = DND.DROP_NONE; return; } log.debug("Got query instance: " + instanceData.name()); xmlRequest = instanceData.writeContentQueryXML(); lastRequestMessage(xmlRequest); xmlResponse = CRCQueryClient.sendPDQQueryRequestREST(xmlRequest); lastResponseMessage(xmlResponse); jaxbElement = jaxbUtil.unMashallFromString(xmlResponse); messageType = (ResponseMessageType) jaxbElement.getValue(); bt = messageType.getMessageBody(); ResultResponseType resultResponseType = (ResultResponseType) new JAXBUnWrapHelper() .getObjectByClass(bt.getAny(), ResultResponseType.class); for (QueryResultInstanceType queryResultInstanceType : resultResponseType .getQueryResultInstance()) { if (!(queryResultInstanceType.getQueryResultType().getName() .equalsIgnoreCase("PATIENTSET"))) { continue; } String status = queryResultInstanceType.getQueryStatusType().getName(); if (status.equalsIgnoreCase("FINISHED")) { // resultData.name("Patient Set - "+resultData // .patientCount()+" Patients"); // QueryResultData resultData = new // QueryResultData(); String setId = new Integer(queryResultInstanceType.getResultInstanceId()) .toString(); String setSize = new Integer(queryResultInstanceType.getSetSize()).toString(); patientSetText.setText("Patient Set: " + setSize + " patients");// strs[0]); patientRefId = new String(setId);// strs[1]); patientMinNumText.setText("1"); leftArrowButton.setEnabled(false); int maxPatientNum = new Integer(patientMaxNumText.getText()).intValue(); patientSetSize = queryResultInstanceType.getSetSize(); if (patientSetSize > maxPatientNum) { rightArrowButton.setEnabled(true); patientMaxNumText.setText("10"); } else { rightArrowButton.setEnabled(false); if (patientSetSize > 0) { patientMaxNumText.setText(setSize); } } log.debug("Dropped set of: " + setSize + " patients"/* strs[0] */ + " with refId: " + setId/* * strs[ 1 ] */); } else { // message } } } catch (Exception e) { e.printStackTrace(); return; } } else { List conceptChildren = tableXml.getChildren(); parseDropConcepts(conceptChildren, event); // System.setProperty("XMLfrommodel",(String) // event.data); table.redraw(); } event.detail = DND.DROP_NONE; } catch (JDOMException e) { System.err.println(e.getMessage()); MessageBox mBox = new MessageBox(table.getShell(), SWT.ICON_INFORMATION | SWT.OK); mBox.setText("Please Note ..."); mBox.setMessage("You can not drop this item here."); mBox.open(); event.detail = DND.DROP_NONE; e.printStackTrace(); return; } catch (Exception e) { System.err.println(e.getMessage()); event.detail = DND.DROP_NONE; e.printStackTrace(); return; } } public void dragEnter(DropTargetEvent event) { event.detail = DND.DROP_COPY; } }); DropTarget target1 = new DropTarget(patientSetText, DND.DROP_COPY); target1.setTransfer(types); target1.addDropListener(new DropTargetAdapter() { @SuppressWarnings("unchecked") public void drop(DropTargetEvent event) { if (event.data == null) { event.detail = DND.DROP_NONE; return; } String tmp = patientSetText.getText(); String dragStr = (String) event.data; String[] strs = dragStr.split(":"); if (strs[0].equalsIgnoreCase("logicquery")) { MessageBox mBox = new MessageBox(table.getShell(), SWT.ICON_INFORMATION | SWT.OK); mBox.setText("Please Note ..."); mBox.setMessage("You can not drop this item here. It accepts a patient set only."); mBox.open(); event.detail = DND.DROP_NONE; patientSetText.setText(tmp); return; } JAXBUtil jaxbUtil = AnalysisJAXBUtil.getJAXBUtil(); try { JAXBElement jaxbElement = jaxbUtil.unMashallFromString(dragStr); DndType dndType = (DndType) jaxbElement.getValue(); QueryResultInstanceType queryResultInstanceType = (QueryResultInstanceType) new JAXBUnWrapHelper() .getObjectByClass(dndType.getAny(), QueryResultInstanceType.class); if (queryResultInstanceType == null) { MessageBox mBox = new MessageBox(table.getShell(), SWT.ICON_INFORMATION | SWT.OK); mBox.setText("Please Note ..."); mBox.setMessage("You can not drop this item here. It accepts a patient set only."); mBox.open(); event.detail = DND.DROP_NONE; patientSetText.setText(tmp); return; } String resultTypeName = queryResultInstanceType.getQueryResultType().getName(); if (resultTypeName == null || !resultTypeName.equalsIgnoreCase("PATIENTSET")) { MessageBox mBox = new MessageBox(table.getShell(), SWT.ICON_INFORMATION | SWT.OK); mBox.setText("Please Note ..."); mBox.setMessage("You can not drop this item here. It accepts a patient set only."); mBox.open(); event.detail = DND.DROP_NONE; patientSetText.setText(tmp); return; } String setId = queryResultInstanceType.getResultInstanceId(); String setSize = new Integer(queryResultInstanceType.getSetSize()).toString(); patientSetText.setText("Patient Set: " + setSize + " patients");// strs[0]); patientRefId = new String(setId);// strs[1]); patientMinNumText.setText("1"); leftArrowButton.setEnabled(false); int maxPatientNum = new Integer(patientMaxNumText.getText()).intValue(); patientSetSize = queryResultInstanceType.getSetSize(); if (patientSetSize > maxPatientNum) { rightArrowButton.setEnabled(true); patientMaxNumText.setText("10"); } else { rightArrowButton.setEnabled(false); // if(patientSetSize>0) { // patientMaxNumText.setText(setSize); // } } log.debug("Dropped set of: " + setSize + " patients"/* * strs[0 * ] */ + " with refId: " + setId/* strs[1] */); } catch (Exception e) { e.printStackTrace(); event.detail = DND.DROP_NONE; return; } } public void dragEnter(DropTargetEvent event) { event.detail = DND.DROP_COPY; } }); table.addCellResizeListener(new KTableCellResizeListener() { public void columnResized(int col, int newWidth) { log.debug("Column " + col + " resized to " + newWidth); } public void rowResized(int newHeight) { log.debug("Rows resized to " + newHeight); } }); table.addListener(SWT.Resize, new Listener() { public void handleEvent(Event event) { int tableWidth = table.getBounds().width; table.getModel().setColumnWidth(1, tableWidth - 425); } }); table.addMouseTrackListener(new MouseTrackListener() { public void mouseEnter(MouseEvent arg0) { } public void mouseExit(MouseEvent arg0) { } public void mouseHover(MouseEvent arg0) { MouseEvent evt = arg0; Rectangle rect = table.getCellRect(3, getRowNumber()); Rectangle rect1 = table.getCellRect(5, 1); // System.out.println("rect X and width: "+rect.x+","+rect.width) // ; // System.out.println("mouse X and Y: "+evt.x+","+evt.y); if (evt.y < rect.y && evt.x > rect1.x && evt.x < rect1.x + rect1.width) { table.setToolTipText("Double click the cell to change color."); } else { table.setToolTipText(""); } } }); // Item 2: a Color Palette TabItem item2 = new TabItem(tabFolder, SWT.NONE); item2.setText("Render a Timeline"); final Composite comp2 = new Composite(tabFolder, SWT.NONE); item2.setControl(comp2); GridLayout oGridLayout0 = new GridLayout(); oGridLayout0.marginWidth = 1; oGridLayout0.marginHeight = 5; comp2.setLayout(oGridLayout0); if (false) { Composite composite = new Composite(comp2, SWT.NO_BACKGROUND | SWT.EMBEDDED); /* * Set a Windows specific AWT property that prevents heavyweight * components from erasing their background. Note that this is a * global property and cannot be scoped. It might not be suitable * for your application. */ try { // System.setProperty("sun.awt.noerasebackground", "true"); } catch (NoSuchMethodError error) { } /* Create and setting up frame */ ////for mac fix //if ( System.getProperty("os.name").toLowerCase().startsWith("mac")) //SWT_AWT.embeddedFrameClass = "sun.lwawt.macosx.CViewEmbeddedFrame"; Frame frame = SWT_AWT.new_Frame(composite); Panel panel = new Panel(new BorderLayout()) { public void update(java.awt.Graphics g) { /* Do not erase the background */ paint(g); } }; frame.add(panel); JRootPane root = new JRootPane(); panel.add(root); java.awt.Container contentPane = root.getContentPane(); log.debug("got to here"); record record1 = new record(); record1.start(); record1.init(); JScrollPane scrollPane = new JScrollPane(record1); contentPane.setLayout(new BorderLayout()); contentPane.add(scrollPane); } if (true) { Composite composite = new Composite(comp2, SWT.NO_BACKGROUND | SWT.EMBEDDED); GridData gridData3 = new GridData(); gridData3.horizontalIndent = 0; gridData3.verticalIndent = 0; gridData3.horizontalAlignment = GridData.FILL; gridData3.verticalAlignment = GridData.FILL; gridData3.grabExcessHorizontalSpace = true; gridData3.grabExcessVerticalSpace = true; composite.setLayoutData(gridData3); /* Create and setting up frame */ ////for mac fix //if ( System.getProperty("os.name").toLowerCase().startsWith("mac")) //SWT_AWT.embeddedFrameClass = "sun.lwawt.macosx.CViewEmbeddedFrame"; Frame frame = SWT_AWT.new_Frame(composite); Panel panel = new Panel(new BorderLayout());// { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { log.debug("Error setting native LAF: " + e); } frame.add(panel); JRootPane root = new JRootPane(); panel.add(root); oAwtContainer = root.getContentPane(); log.debug("got to here"); } tabFolder.addSelectionListener(new SelectionListener() { public void widgetSelected(SelectionEvent e) { ConceptTableModel i2b2Model = (ConceptTableModel) table.getModel(); i2b2Model.fillDataFromTable(rowData); if (rowData.size() == 0) { oTheParent.getDisplay().syncExec(new Runnable() { public void run() { tabFolder.setSelection(0); } }); MessageBox mBox = new MessageBox(table.getShell(), SWT.ICON_INFORMATION | SWT.OK); mBox.setText("Please Note ..."); mBox.setMessage("The set up table is empty."); mBox.open(); return; } String patientSetStr = patientSetText.getText(); if (patientSetStr.equals("") && !isAll) { oTheParent.getDisplay().syncExec(new Runnable() { public void run() { tabFolder.setSelection(0); } }); MessageBox mBox = new MessageBox(table.getShell(), SWT.ICON_INFORMATION | SWT.OK); mBox.setText("Please Note ..."); mBox.setMessage("Please set a patient set or choose all datamart option."); mBox.open(); return; } if (tabFolder.getSelectionIndex() == 1) { if (patientSetStr.equalsIgnoreCase("All")) { int minPatient = 0; try { String minText = patientMinNumText.getText(); minPatient = Integer.parseInt(minText); } catch (Exception e1) { minPatient = -1; } int maxPatient = 0; try { maxPatient = Integer.parseInt(patientMaxNumText.getText()); } catch (Exception e2) { maxPatient = -1; } PerformVisualizationQuery(oAwtContainer, "All", minPatient, maxPatient, bDisplayAllData); } else { int min = Integer.parseInt(patientMinNumText.getText()); int max = Integer.parseInt(patientMaxNumText.getText()); PerformVisualizationQuery(oAwtContainer, patientRefId, min, max, bDisplayAllData); } } else { DestroyMiniVisualization(oAwtContainer); } } public void widgetDefaultSelected(SelectionEvent e) { widgetSelected(e); } }); if (drawLeft) { horizontalForm.setWeights(new int[] { 30, 70 }); } return parent; }