Search in sources :

Example 46 with JToolBar

use of javax.swing.JToolBar in project airavata by apache.

the class XBayaToolBar method init.

private void init() {
    this.toolbar = new JToolBar();
    this.toolbar.setFloatable(false);
    Border border = BorderFactory.createEtchedBorder();
    this.toolbar.setBorder(border);
    JButton addNodeButton = new JButton("Add Node");
    addNodeButton.addActionListener(new AbstractAction() {

        private static final long serialVersionUID = 1L;

        public void actionPerformed(ActionEvent event) {
            try {
                XBayaToolBar.this.engine.getGUI().addNode();
            } catch (RuntimeException e) {
                XBayaToolBar.this.engine.getGUI().getErrorWindow().error(ErrorMessages.UNEXPECTED_ERROR, e);
            } catch (Error e) {
                XBayaToolBar.this.engine.getGUI().getErrorWindow().error(ErrorMessages.UNEXPECTED_ERROR, e);
            }
        }
    });
    JButton removeNodeButton = new JButton("Remove Node");
    removeNodeButton.addActionListener(new AbstractAction() {

        private static final long serialVersionUID = 1L;

        public void actionPerformed(ActionEvent event) {
            try {
                XBayaToolBar.this.engine.getGUI().getGraphCanvas().removeSelectedNode();
            } catch (GraphException e) {
                // Should not happen
                XBayaToolBar.this.engine.getGUI().getErrorWindow().error(ErrorMessages.UNEXPECTED_ERROR, e);
            } catch (RuntimeException e) {
                XBayaToolBar.this.engine.getGUI().getErrorWindow().error(ErrorMessages.UNEXPECTED_ERROR, e);
            } catch (Error e) {
                XBayaToolBar.this.engine.getGUI().getErrorWindow().error(ErrorMessages.UNEXPECTED_ERROR, e);
            }
        }
    });
    JButton connectEdgeButton = new JButton("Connect/Disconnect");
    connectEdgeButton.addActionListener(new AbstractAction() {

        private static final long serialVersionUID = 1L;

        public void actionPerformed(ActionEvent event) {
            try {
                XBayaToolBar.this.engine.getGUI().getGraphCanvas().addOrRemoveEdge();
            } catch (RuntimeException e) {
                XBayaToolBar.this.engine.getGUI().getErrorWindow().error(ErrorMessages.UNEXPECTED_ERROR, e);
            } catch (Error e) {
                XBayaToolBar.this.engine.getGUI().getErrorWindow().error(ErrorMessages.UNEXPECTED_ERROR, e);
            }
        }
    });
    this.play = new JButton();
    PAUSE_ICON = SwingUtil.createImageIcon(IMAGES_PAUSE_JPEG);
    PLAY_ICON = SwingUtil.createImageIcon(IMAGES_PLAY_JPEG);
    this.playAction = new AbstractAction(null, PAUSE_ICON) {

        /**
         * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
         */
        public void actionPerformed(ActionEvent e1) {
            try {
                Workflow workflow = engine.getGUI().getWorkflow();
                WorkflowExecutionState executionState = workflow.getExecutionState();
                if (executionState == WorkflowExecutionState.RUNNING || executionState == WorkflowExecutionState.STEP) {
                    workflow.setExecutionState(WorkflowExecutionState.PAUSED);
                    play.setIcon(PLAY_ICON);
                } else if (executionState == WorkflowExecutionState.PAUSED) {
                    workflow.setExecutionState(WorkflowExecutionState.RUNNING);
                    play.setIcon(PAUSE_ICON);
                } else {
                    throw new IllegalStateException("Unknown state :" + executionState);
                }
            } catch (RuntimeException e) {
                XBayaToolBar.this.engine.getGUI().getErrorWindow().error(ErrorMessages.UNEXPECTED_ERROR, e);
            } catch (Error e) {
                XBayaToolBar.this.engine.getGUI().getErrorWindow().error(ErrorMessages.UNEXPECTED_ERROR, e);
            }
        }
    };
    this.play.setAction(this.playAction);
    this.step = new JButton();
    this.stepAction = new AbstractAction(null, SwingUtil.createImageIcon(IMAGES_STEP_JPEG)) {

        /**
         * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
         */
        public void actionPerformed(ActionEvent e2) {
            try {
                if (engine.getGUI().getWorkflow().getExecutionState() == WorkflowExecutionState.PAUSED) {
                    engine.getGUI().getWorkflow().setExecutionState(WorkflowExecutionState.STEP);
                } else {
                    throw new IllegalStateException("Unknown state :" + engine.getGUI().getWorkflow().getExecutionState());
                }
            } catch (RuntimeException e) {
                XBayaToolBar.this.engine.getGUI().getErrorWindow().error(ErrorMessages.UNEXPECTED_ERROR, e);
            } catch (Error e) {
                XBayaToolBar.this.engine.getGUI().getErrorWindow().error(ErrorMessages.UNEXPECTED_ERROR, e);
            }
        }
    };
    this.step.setAction(stepAction);
    this.stop = new JButton();
    this.stopAction = new AbstractAction(null, SwingUtil.createImageIcon(IMAGES_STOP_JPEG)) {

        /**
         * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
         */
        public void actionPerformed(ActionEvent e1) {
            try {
                if (engine.getGUI().getWorkflow().getExecutionState() != WorkflowExecutionState.NONE || engine.getGUI().getWorkflow().getExecutionState() != WorkflowExecutionState.STOPPED) {
                    engine.getGUI().getWorkflow().setExecutionState(WorkflowExecutionState.STOPPED);
                } else {
                    throw new IllegalStateException("Unknown state :" + engine.getGUI().getWorkflow().getExecutionState());
                }
            } catch (RuntimeException e) {
                XBayaToolBar.this.engine.getGUI().getErrorWindow().error(ErrorMessages.UNEXPECTED_ERROR, e);
            } catch (Error e) {
                XBayaToolBar.this.engine.getGUI().getErrorWindow().error(ErrorMessages.UNEXPECTED_ERROR, e);
            }
        }
    };
    this.stop.setAction(stopAction);
// this.toolbar.add(addNodeButton);
// this.toolbar.add(removeNodeButton);
// this.toolbar.addSeparator();
// this.toolbar.add(connectEdgeButton);
}
Also used : GraphException(org.apache.airavata.workflow.model.graph.GraphException) WorkflowExecutionState(org.apache.airavata.workflow.model.wf.WorkflowExecutionState) ActionEvent(java.awt.event.ActionEvent) JButton(javax.swing.JButton) Workflow(org.apache.airavata.workflow.model.wf.Workflow) JToolBar(javax.swing.JToolBar) Border(javax.swing.border.Border) AbstractAction(javax.swing.AbstractAction)

Example 47 with JToolBar

use of javax.swing.JToolBar in project org.alloytools.alloy by AlloyTools.

the class SimpleGUI method finishInit.

private void finishInit(String[] args, int width) {
    // Add the listeners
    try {
        wrap = true;
        frame.addWindowListener(doQuit());
    } finally {
        wrap = false;
    }
    frame.addComponentListener(this);
    // initialize the "allowed memory sizes" array
    // allowedMemorySizes = new
    // ArrayList<Integer>(initialAllowedMemorySizes);
    // int newmem = SubMemory.get();
    // if (!allowedMemorySizes.contains(newmem)) {
    // int newmemlen = allowedMemorySizes.size();
    // if (allowedMemorySizes.contains(768) || newmemlen==0)
    // SubMemory.set(768); // a nice default value
    // else
    // SubMemory.set(allowedMemorySizes.get(newmemlen-1));
    // }
    // Choose the appropriate font
    int fontSize = FontSize.get();
    String fontName = OurDialog.getProperFontName(FontName.get(), "Courier New", "Lucidia", "Courier", "Monospaced");
    FontName.set(fontName);
    // Copy required files from the JAR
    copyFromJAR();
    final String binary = alloyHome() + fs + "binary";
    // Create the menu bar
    JMenuBar bar = new JMenuBar();
    try {
        wrap = true;
        filemenu = menu(bar, "&File", doRefreshFile());
        editmenu = menu(bar, "&Edit", doRefreshEdit());
        runmenu = menu(bar, "E&xecute", doRefreshRun());
        optmenu = menu(bar, "&Options", doRefreshOption());
        windowmenu = menu(bar, "&Window", doRefreshWindow(false));
        windowmenu2 = menu(null, "&Window", doRefreshWindow(true));
        helpmenu = menu(bar, "&Help", null);
        if (!Util.onMac())
            menuItem(helpmenu, "About Alloy...", 'A', doAbout());
        menuItem(helpmenu, "Quick Guide", 'Q', doHelp());
        menuItem(helpmenu, "See the Copyright Notices...", 'L', doLicense());
    } finally {
        wrap = false;
    }
    // Pre-load the visualizer
    viz = new VizGUI(false, "", windowmenu2, enumerator, evaluator);
    viz.doSetFontSize(FontSize.get());
    // Create the toolbar
    try {
        wrap = true;
        toolbar = new JToolBar();
        toolbar.setFloatable(false);
        if (!Util.onMac())
            toolbar.setBackground(background);
        toolbar.add(OurUtil.button("New", "Starts a new blank model", "images/24_new.gif", doNew()));
        toolbar.add(OurUtil.button("Open", "Opens an existing model", "images/24_open.gif", doOpen()));
        toolbar.add(OurUtil.button("Reload", "Reload all the models from disk", "images/24_reload.gif", doReloadAll()));
        toolbar.add(OurUtil.button("Save", "Saves the current model", "images/24_save.gif", doSave()));
        toolbar.add(runbutton = OurUtil.button("Execute", "Executes the latest command", "images/24_execute.gif", doExecuteLatest()));
        toolbar.add(stopbutton = OurUtil.button("Stop", "Stops the current analysis", "images/24_execute_abort2.gif", doStop(2)));
        stopbutton.setVisible(false);
        toolbar.add(showbutton = OurUtil.button("Show", "Shows the latest instance", "images/24_graph.gif", doShowLatest()));
        toolbar.add(Box.createHorizontalGlue());
        toolbar.setBorder(new OurBorder(false, false, false, false));
    } finally {
        wrap = false;
    }
    // Choose the antiAlias setting
    OurAntiAlias.enableAntiAlias(AntiAlias.get());
    // Create the message area
    logpane = OurUtil.scrollpane(null);
    log = new SwingLogPanel(logpane, fontName, fontSize, background, Color.BLACK, new Color(.7f, .2f, .2f), this);
    // Create loggers for preference changes
    PreferencesDialog.logOnChange(log, A4Preferences.allUserPrefs().toArray(new Pref<?>[0]));
    // Create the text area
    text = new OurTabbedSyntaxWidget(fontName, fontSize, TabSize.get());
    text.listeners.add(this);
    text.enableSyntax(!SyntaxDisabled.get());
    // Add everything to the frame, then display the frame
    Container all = frame.getContentPane();
    all.setLayout(new BorderLayout());
    all.removeAll();
    JPanel lefthalf = new JPanel();
    lefthalf.setLayout(new BorderLayout());
    lefthalf.add(toolbar, BorderLayout.NORTH);
    text.addTo(lefthalf, BorderLayout.CENTER);
    splitpane = OurUtil.splitpane(JSplitPane.HORIZONTAL_SPLIT, lefthalf, logpane, width / 2);
    splitpane.setResizeWeight(0.5D);
    status = OurUtil.make(OurAntiAlias.label(" "), new Font(fontName, Font.PLAIN, fontSize), Color.BLACK, background);
    status.setBorder(new OurBorder(true, false, false, false));
    all.add(splitpane, BorderLayout.CENTER);
    all.add(status, BorderLayout.SOUTH);
    // Generate some informative log messages
    log.logBold("Alloy Analyzer " + Version.version() + " (build date: " + Version.buildDate() + " git " + Version.commit + ")\n\n");
    // If on Mac, then register an application listener
    try {
        wrap = true;
        if (Util.onMac()) {
            macUtil.registerApplicationListener(doShow(), doAbout(), doOpenFile(""), doQuit());
        }
    } catch (Throwable t) {
        System.out.println("Mac classes not there");
    } finally {
        wrap = false;
    }
    // Add the new JNI location to the java.library.path
    try {
        System.setProperty("java.library.path", binary);
        // The above line is actually useless on Sun JDK/JRE (see Sun's bug
        // ID 4280189)
        // The following 4 lines should work for Sun's JDK/JRE (though they
        // probably won't work for others)
        String[] newarray = new String[] { binary };
        java.lang.reflect.Field old = ClassLoader.class.getDeclaredField("usr_paths");
        old.setAccessible(true);
        old.set(null, newarray);
    } catch (Throwable ex) {
    }
    // Pre-load the preferences dialog
    prefDialog = new PreferencesDialog(log, binary);
    prefDialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    try {
        wrap = true;
        prefDialog.addChangeListener(wrapToChangeListener(doOptRefreshFont()), FontName, FontSize, TabSize);
        prefDialog.addChangeListener(wrapToChangeListener(doOptAntiAlias()), AntiAlias);
        prefDialog.addChangeListener(wrapToChangeListener(doOptSyntaxHighlighting()), SyntaxDisabled);
        prefDialog.addChangeListener(wrapToChangeListener(doLookAndFeel()), LAF);
    } finally {
        wrap = false;
    }
    // If the temporary directory has become too big, then tell the user
    // they can "clear temporary directory".
    long space = computeTemporarySpaceUsed();
    if (space < 0 || space >= 20 * 1024768) {
        if (space < 0)
            log.logBold("Warning: Alloy4's temporary directory has exceeded 1024M.\n");
        else
            log.logBold("Warning: Alloy4's temporary directory now uses " + (space / 1024768) + "M.\n");
        log.log("To clear the temporary directory,\n" + "go to the File menu and click \"Clear Temporary Directory\"\n");
        log.logDivider();
        log.flush();
    }
    // Refreshes all the menu items
    doRefreshFile();
    OurUtil.enableAll(filemenu);
    doRefreshEdit();
    OurUtil.enableAll(editmenu);
    doRefreshRun();
    OurUtil.enableAll(runmenu);
    doRefreshOption();
    doRefreshWindow(false);
    OurUtil.enableAll(windowmenu);
    frame.setJMenuBar(bar);
    // Open the given file, if a filename is given in the command line
    for (String f : args) if (f.toLowerCase(Locale.US).endsWith(".als")) {
        File file = new File(f);
        if (file.exists() && file.isFile())
            doOpenFile(file.getPath());
    }
    // Update the title and status bar
    notifyChange();
    text.get().requestFocusInWindow();
    // Launch the welcome screen if needed
    if (!AlloyCore.isDebug() && Welcome.get()) {
        JCheckBox again = new JCheckBox("Show this message every time you start the Alloy Analyzer");
        again.setSelected(true);
        OurDialog.showmsg("Welcome", "Thank you for using the Alloy Analyzer " + Version.version(), " ", "Version 4 of the Alloy Analyzer is a complete rewrite,", "offering improvements in robustness, performance and usability.", "Models written in Alloy 3 will require some small alterations to run in Alloy 4.", " ", "Here are some quick tips:", " ", "* Function calls now use [ ] instead of ( )", "  For more details, please see http://alloy.mit.edu/alloy4/quickguide/", " ", "* The Execute button always executes the latest command.", "  To choose which command to execute, go to the Execute menu.", " ", "* The Alloy Analyzer comes with a variety of sample models.", "  To see them, go to the File menu and click Open Sample Models.", " ", again);
        doShow();
        Welcome.set(again.isSelected());
    }
    // Periodically ask the MailBug thread to see if there is a newer
    // version or not
    final long now = System.currentTimeMillis();
    final Timer t = new Timer(800, null);
    t.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            int n = MailBug.latestBuildNumber();
            // message may run into other user messages
            if (System.currentTimeMillis() - now >= 3000 || n <= Version.buildNumber()) {
                t.stop();
                return;
            }
            latestAlloyVersion = n;
            latestAlloyVersionName = MailBug.latestBuildName();
            log.logBold("An updated version of the Alloy Analyzer has been released.\n");
            log.log("Please visit alloy.mit.edu to download the latest version:\nVersion " + latestAlloyVersionName + "\n");
            log.logDivider();
            log.flush();
            t.stop();
        }
    });
    t.start();
}
Also used : JPanel(javax.swing.JPanel) ActionEvent(java.awt.event.ActionEvent) OurBorder(edu.mit.csail.sdg.alloy4.OurBorder) OurTabbedSyntaxWidget(edu.mit.csail.sdg.alloy4.OurTabbedSyntaxWidget) Font(java.awt.Font) Container(java.awt.Container) BorderLayout(java.awt.BorderLayout) BooleanPref(edu.mit.csail.sdg.alloy4.A4Preferences.BooleanPref) Pref(edu.mit.csail.sdg.alloy4.A4Preferences.Pref) StringPref(edu.mit.csail.sdg.alloy4.A4Preferences.StringPref) VerbosityPref(edu.mit.csail.sdg.alloy4.A4Preferences.VerbosityPref) ChoicePref(edu.mit.csail.sdg.alloy4.A4Preferences.ChoicePref) Color(java.awt.Color) JToolBar(javax.swing.JToolBar) JCheckBox(javax.swing.JCheckBox) VizGUI(edu.mit.csail.sdg.alloy4viz.VizGUI) Timer(javax.swing.Timer) ActionListener(java.awt.event.ActionListener) File(java.io.File) JMenuBar(javax.swing.JMenuBar)

Example 48 with JToolBar

use of javax.swing.JToolBar in project bundle-app-ui by astrapi69.

the class MainFrame method onInitializeComponents.

@Override
protected void onInitializeComponents() {
    super.onInitializeComponents();
    // create the tool bar
    toolbar = new JToolBar();
    setJMenuBar(menubar);
    setToolBar(toolbar);
    desktopPane = SingletonDesktopPane.getInstance();
    currentLookAndFeels = LookAndFeels.SYSTEM;
    getContentPane().add(desktopPane);
    try {
        final String iconPath = Messages.getString("global.icon.app.path");
        final BufferedImage appIcon = ImageIO.read(ClassExtensions.getResourceAsStream(iconPath));
        setIconImage(appIcon);
    } catch (final IOException e) {
        log.error("Icon file could not be readed.", e);
    }
    final ApplicationContext applicationContext = SpringApplicationContext.getInstance().getApplicationContext();
    final BundleApplicationsService bundleApplicationsService = (BundleApplicationsService) applicationContext.getBean("bundleApplicationsService");
    final Model<MainDashboardBean> model = BaseModel.<MainDashboardBean>of(MainDashboardBean.builder().bundleApplications(bundleApplicationsService.findAll()).build());
    setModel(model);
    final MainDashboardPanel mainDashboardPanel = new MainDashboardPanel(PropertyModel.<MainDashboardBean>of(this, "model.object"));
    replaceInternalFrame("Main dashboard", mainDashboardPanel);
}
Also used : BundleApplicationsService(de.alpharogroup.db.resource.bundles.service.api.BundleApplicationsService) SpringApplicationContext(de.alpharogroup.bundle.app.spring.SpringApplicationContext) ApplicationContext(org.springframework.context.ApplicationContext) MainDashboardPanel(de.alpharogroup.bundle.app.panels.dashboard.mainapp.MainDashboardPanel) MainDashboardBean(de.alpharogroup.bundle.app.panels.dashboard.mainapp.MainDashboardBean) JToolBar(javax.swing.JToolBar) IOException(java.io.IOException) BufferedImage(java.awt.image.BufferedImage)

Example 49 with JToolBar

use of javax.swing.JToolBar in project gitblit by gitblit.

the class GitblitAuthority method getUI.

private Container getUI() {
    userCertificatePanel = new UserCertificatePanel(this) {

        private static final long serialVersionUID = 1L;

        @Override
        public Insets getInsets() {
            return Utils.INSETS;
        }

        @Override
        public boolean isAllowEmail() {
            return mail.isReady();
        }

        @Override
        public Date getDefaultExpiration() {
            Calendar c = Calendar.getInstance();
            c.add(Calendar.DATE, defaultDuration);
            c.set(Calendar.HOUR_OF_DAY, 0);
            c.set(Calendar.MINUTE, 0);
            c.set(Calendar.SECOND, 0);
            c.set(Calendar.MILLISECOND, 0);
            return c.getTime();
        }

        @Override
        public boolean saveUser(String username, UserCertificateModel ucm) {
            return userService.updateUserModel(username, ucm.user);
        }

        @Override
        public boolean newCertificate(UserCertificateModel ucm, X509Metadata metadata, boolean sendEmail) {
            if (!prepareX509Infrastructure()) {
                return false;
            }
            Date notAfter = metadata.notAfter;
            setMetadataDefaults(metadata);
            metadata.notAfter = notAfter;
            // set user's specified OID values
            UserModel user = ucm.user;
            if (!StringUtils.isEmpty(user.organizationalUnit)) {
                metadata.oids.put("OU", user.organizationalUnit);
            }
            if (!StringUtils.isEmpty(user.organization)) {
                metadata.oids.put("O", user.organization);
            }
            if (!StringUtils.isEmpty(user.locality)) {
                metadata.oids.put("L", user.locality);
            }
            if (!StringUtils.isEmpty(user.stateProvince)) {
                metadata.oids.put("ST", user.stateProvince);
            }
            if (!StringUtils.isEmpty(user.countryCode)) {
                metadata.oids.put("C", user.countryCode);
            }
            File caKeystoreFile = new File(folder, X509Utils.CA_KEY_STORE);
            File zip = X509Utils.newClientBundle(user, metadata, caKeystoreFile, caKeystorePassword, GitblitAuthority.this);
            // save latest expiration date
            if (ucm.expires == null || metadata.notAfter.before(ucm.expires)) {
                ucm.expires = metadata.notAfter;
            }
            updateAuthorityConfig(ucm);
            // refresh user
            ucm.certs = null;
            int selectedIndex = table.getSelectedRow();
            tableModel.fireTableDataChanged();
            table.getSelectionModel().setSelectionInterval(selectedIndex, selectedIndex);
            if (sendEmail) {
                sendEmail(user, metadata, zip);
            }
            return true;
        }

        @Override
        public boolean revoke(UserCertificateModel ucm, X509Certificate cert, RevocationReason reason) {
            if (!prepareX509Infrastructure()) {
                return false;
            }
            File caRevocationList = new File(folder, X509Utils.CA_REVOCATION_LIST);
            File caKeystoreFile = new File(folder, X509Utils.CA_KEY_STORE);
            if (X509Utils.revoke(cert, reason, caRevocationList, caKeystoreFile, caKeystorePassword, GitblitAuthority.this)) {
                File certificatesConfigFile = new File(folder, X509Utils.CA_CONFIG);
                FileBasedConfig config = new FileBasedConfig(certificatesConfigFile, FS.detect());
                if (certificatesConfigFile.exists()) {
                    try {
                        config.load();
                    } catch (Exception e) {
                        Utils.showException(GitblitAuthority.this, e);
                    }
                }
                // add serial to revoked list
                ucm.revoke(cert.getSerialNumber(), reason);
                ucm.update(config);
                try {
                    config.save();
                } catch (Exception e) {
                    Utils.showException(GitblitAuthority.this, e);
                }
                // refresh user
                ucm.certs = null;
                int modelIndex = table.convertRowIndexToModel(table.getSelectedRow());
                tableModel.fireTableDataChanged();
                table.getSelectionModel().setSelectionInterval(modelIndex, modelIndex);
                return true;
            }
            return false;
        }
    };
    table = Utils.newTable(tableModel, Utils.DATE_FORMAT);
    table.setRowSorter(defaultSorter);
    table.setDefaultRenderer(CertificateStatus.class, new CertificateStatusRenderer());
    table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

        @Override
        public void valueChanged(ListSelectionEvent e) {
            if (e.getValueIsAdjusting()) {
                return;
            }
            int row = table.getSelectedRow();
            if (row < 0) {
                return;
            }
            int modelIndex = table.convertRowIndexToModel(row);
            UserCertificateModel ucm = tableModel.get(modelIndex);
            if (ucm.certs == null) {
                ucm.certs = findCerts(folder, ucm.user.username);
            }
            userCertificatePanel.setUserCertificateModel(ucm);
        }
    });
    JPanel usersPanel = new JPanel(new BorderLayout()) {

        private static final long serialVersionUID = 1L;

        @Override
        public Insets getInsets() {
            return Utils.INSETS;
        }
    };
    usersPanel.add(new HeaderPanel(Translation.get("gb.users"), "users_16x16.png"), BorderLayout.NORTH);
    usersPanel.add(new JScrollPane(table), BorderLayout.CENTER);
    usersPanel.setMinimumSize(new Dimension(400, 10));
    certificateDefaultsButton = new JButton(new ImageIcon(getClass().getResource("/settings_16x16.png")));
    certificateDefaultsButton.setFocusable(false);
    certificateDefaultsButton.setToolTipText(Translation.get("gb.newCertificateDefaults"));
    certificateDefaultsButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            X509Metadata metadata = new X509Metadata("whocares", "whocares");
            File certificatesConfigFile = new File(folder, X509Utils.CA_CONFIG);
            FileBasedConfig config = new FileBasedConfig(certificatesConfigFile, FS.detect());
            NewCertificateConfig certificateConfig = null;
            if (certificatesConfigFile.exists()) {
                try {
                    config.load();
                } catch (Exception x) {
                    Utils.showException(GitblitAuthority.this, x);
                }
                certificateConfig = NewCertificateConfig.KEY.parse(config);
                certificateConfig.update(metadata);
            }
            InputVerifier verifier = new InputVerifier() {

                @Override
                public boolean verify(JComponent comp) {
                    boolean returnValue;
                    JTextField textField = (JTextField) comp;
                    try {
                        Integer.parseInt(textField.getText());
                        returnValue = true;
                    } catch (NumberFormatException e) {
                        returnValue = false;
                    }
                    return returnValue;
                }
            };
            JTextField siteNameTF = new JTextField(20);
            siteNameTF.setText(gitblitSettings.getString(Keys.web.siteName, "Gitblit"));
            JPanel siteNamePanel = Utils.newFieldPanel(Translation.get("gb.siteName"), siteNameTF, Translation.get("gb.siteNameDescription"));
            JTextField validityTF = new JTextField(4);
            validityTF.setInputVerifier(verifier);
            validityTF.setVerifyInputWhenFocusTarget(true);
            validityTF.setText("" + certificateConfig.duration);
            JPanel validityPanel = Utils.newFieldPanel(Translation.get("gb.validity"), validityTF, Translation.get("gb.duration.days").replace("{0}", "").trim());
            JPanel p1 = new JPanel(new GridLayout(0, 1, 5, 2));
            p1.add(siteNamePanel);
            p1.add(validityPanel);
            DefaultOidsPanel oids = new DefaultOidsPanel(metadata);
            JPanel panel = new JPanel(new BorderLayout());
            panel.add(p1, BorderLayout.NORTH);
            panel.add(oids, BorderLayout.CENTER);
            int result = JOptionPane.showConfirmDialog(GitblitAuthority.this, panel, Translation.get("gb.newCertificateDefaults"), JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE, new ImageIcon(getClass().getResource("/settings_32x32.png")));
            if (result == JOptionPane.OK_OPTION) {
                try {
                    oids.update(metadata);
                    certificateConfig.duration = Integer.parseInt(validityTF.getText());
                    certificateConfig.store(config, metadata);
                    config.save();
                    Map<String, String> updates = new HashMap<String, String>();
                    updates.put(Keys.web.siteName, siteNameTF.getText());
                    gitblitSettings.saveSettings(updates);
                } catch (Exception e1) {
                    Utils.showException(GitblitAuthority.this, e1);
                }
            }
        }
    });
    newSSLCertificate = new JButton(new ImageIcon(getClass().getResource("/rosette_16x16.png")));
    newSSLCertificate.setFocusable(false);
    newSSLCertificate.setToolTipText(Translation.get("gb.newSSLCertificate"));
    newSSLCertificate.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            Date defaultExpiration = new Date(System.currentTimeMillis() + 10 * TimeUtils.ONEYEAR);
            NewSSLCertificateDialog dialog = new NewSSLCertificateDialog(GitblitAuthority.this, defaultExpiration);
            dialog.setModal(true);
            dialog.setVisible(true);
            if (dialog.isCanceled()) {
                return;
            }
            final Date expires = dialog.getExpiration();
            final String hostname = dialog.getHostname();
            final boolean serveCertificate = dialog.isServeCertificate();
            AuthorityWorker worker = new AuthorityWorker(GitblitAuthority.this) {

                @Override
                protected Boolean doRequest() throws IOException {
                    if (!prepareX509Infrastructure()) {
                        return false;
                    }
                    // read CA private key and certificate
                    File caKeystoreFile = new File(folder, X509Utils.CA_KEY_STORE);
                    PrivateKey caPrivateKey = X509Utils.getPrivateKey(X509Utils.CA_ALIAS, caKeystoreFile, caKeystorePassword);
                    X509Certificate caCert = X509Utils.getCertificate(X509Utils.CA_ALIAS, caKeystoreFile, caKeystorePassword);
                    // generate new SSL certificate
                    X509Metadata metadata = new X509Metadata(hostname, caKeystorePassword);
                    setMetadataDefaults(metadata);
                    metadata.notAfter = expires;
                    File serverKeystoreFile = new File(folder, X509Utils.SERVER_KEY_STORE);
                    X509Certificate cert = X509Utils.newSSLCertificate(metadata, caPrivateKey, caCert, serverKeystoreFile, GitblitAuthority.this);
                    boolean hasCert = cert != null;
                    if (hasCert && serveCertificate) {
                        // update Gitblit https connector alias
                        Map<String, String> updates = new HashMap<String, String>();
                        updates.put(Keys.server.certificateAlias, metadata.commonName);
                        gitblitSettings.saveSettings(updates);
                    }
                    return hasCert;
                }

                @Override
                protected void onSuccess() {
                    if (serveCertificate) {
                        JOptionPane.showMessageDialog(GitblitAuthority.this, MessageFormat.format(Translation.get("gb.sslCertificateGeneratedRestart"), hostname), Translation.get("gb.newSSLCertificate"), JOptionPane.INFORMATION_MESSAGE);
                    } else {
                        JOptionPane.showMessageDialog(GitblitAuthority.this, MessageFormat.format(Translation.get("gb.sslCertificateGenerated"), hostname), Translation.get("gb.newSSLCertificate"), JOptionPane.INFORMATION_MESSAGE);
                    }
                }
            };
            worker.execute();
        }
    });
    JButton emailBundle = new JButton(new ImageIcon(getClass().getResource("/mail_16x16.png")));
    emailBundle.setFocusable(false);
    emailBundle.setToolTipText(Translation.get("gb.emailCertificateBundle"));
    emailBundle.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            int row = table.getSelectedRow();
            if (row < 0) {
                return;
            }
            int modelIndex = table.convertRowIndexToModel(row);
            final UserCertificateModel ucm = tableModel.get(modelIndex);
            if (ArrayUtils.isEmpty(ucm.certs)) {
                JOptionPane.showMessageDialog(GitblitAuthority.this, MessageFormat.format(Translation.get("gb.pleaseGenerateClientCertificate"), ucm.user.getDisplayName()));
            }
            final File zip = new File(folder, X509Utils.CERTS + File.separator + ucm.user.username + File.separator + ucm.user.username + ".zip");
            if (!zip.exists()) {
                return;
            }
            AuthorityWorker worker = new AuthorityWorker(GitblitAuthority.this) {

                @Override
                protected Boolean doRequest() throws IOException {
                    X509Metadata metadata = new X509Metadata(ucm.user.username, "whocares");
                    metadata.serverHostname = gitblitSettings.getString(Keys.web.siteName, Constants.NAME);
                    if (StringUtils.isEmpty(metadata.serverHostname)) {
                        metadata.serverHostname = Constants.NAME;
                    }
                    metadata.userDisplayname = ucm.user.getDisplayName();
                    return sendEmail(ucm.user, metadata, zip);
                }

                @Override
                protected void onSuccess() {
                    JOptionPane.showMessageDialog(GitblitAuthority.this, MessageFormat.format(Translation.get("gb.clientCertificateBundleSent"), ucm.user.getDisplayName()));
                }
            };
            worker.execute();
        }
    });
    JButton logButton = new JButton(new ImageIcon(getClass().getResource("/script_16x16.png")));
    logButton.setFocusable(false);
    logButton.setToolTipText(Translation.get("gb.log"));
    logButton.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            File log = new File(folder, X509Utils.CERTS + File.separator + "log.txt");
            if (log.exists()) {
                String content = FileUtils.readContent(log, "\n");
                JTextArea textarea = new JTextArea(content);
                JScrollPane scrollPane = new JScrollPane(textarea);
                scrollPane.setPreferredSize(new Dimension(700, 400));
                JOptionPane.showMessageDialog(GitblitAuthority.this, scrollPane, log.getAbsolutePath(), JOptionPane.INFORMATION_MESSAGE);
            }
        }
    });
    final JTextField filterTextfield = new JTextField(15);
    filterTextfield.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            filterUsers(filterTextfield.getText());
        }
    });
    filterTextfield.addKeyListener(new KeyAdapter() {

        @Override
        public void keyReleased(KeyEvent e) {
            filterUsers(filterTextfield.getText());
        }
    });
    JToolBar buttonControls = new JToolBar(JToolBar.HORIZONTAL);
    buttonControls.setFloatable(false);
    buttonControls.add(certificateDefaultsButton);
    buttonControls.add(newSSLCertificate);
    buttonControls.add(emailBundle);
    buttonControls.add(logButton);
    JPanel userControls = new JPanel(new FlowLayout(FlowLayout.RIGHT, Utils.MARGIN, Utils.MARGIN));
    userControls.add(new JLabel(Translation.get("gb.filter")));
    userControls.add(filterTextfield);
    JPanel topPanel = new JPanel(new BorderLayout(0, 0));
    topPanel.add(buttonControls, BorderLayout.WEST);
    topPanel.add(userControls, BorderLayout.EAST);
    JPanel leftPanel = new JPanel(new BorderLayout());
    leftPanel.add(topPanel, BorderLayout.NORTH);
    leftPanel.add(usersPanel, BorderLayout.CENTER);
    userCertificatePanel.setMinimumSize(new Dimension(375, 10));
    JLabel statusLabel = new JLabel();
    statusLabel.setHorizontalAlignment(SwingConstants.RIGHT);
    if (X509Utils.unlimitedStrength) {
        statusLabel.setText("JCE Unlimited Strength Jurisdiction Policy");
    } else {
        statusLabel.setText("JCE Standard Encryption Policy");
    }
    JPanel root = new JPanel(new BorderLayout()) {

        private static final long serialVersionUID = 1L;

        @Override
        public Insets getInsets() {
            return Utils.INSETS;
        }
    };
    JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftPanel, userCertificatePanel);
    splitPane.setDividerLocation(1d);
    root.add(splitPane, BorderLayout.CENTER);
    root.add(statusLabel, BorderLayout.SOUTH);
    return root;
}
Also used : JPanel(javax.swing.JPanel) PrivateKey(java.security.PrivateKey) JTextArea(javax.swing.JTextArea) X509Metadata(com.gitblit.utils.X509Utils.X509Metadata) ActionEvent(java.awt.event.ActionEvent) KeyAdapter(java.awt.event.KeyAdapter) BorderLayout(java.awt.BorderLayout) X509Certificate(java.security.cert.X509Certificate) ListSelectionListener(javax.swing.event.ListSelectionListener) ActionListener(java.awt.event.ActionListener) JSplitPane(javax.swing.JSplitPane) File(java.io.File) Map(java.util.Map) HashMap(java.util.HashMap) ImageIcon(javax.swing.ImageIcon) Insets(java.awt.Insets) FlowLayout(java.awt.FlowLayout) ListSelectionEvent(javax.swing.event.ListSelectionEvent) JButton(javax.swing.JButton) JTextField(javax.swing.JTextField) UserModel(com.gitblit.models.UserModel) KeyEvent(java.awt.event.KeyEvent) GridLayout(java.awt.GridLayout) FileBasedConfig(org.eclipse.jgit.storage.file.FileBasedConfig) RevocationReason(com.gitblit.utils.X509Utils.RevocationReason) JScrollPane(javax.swing.JScrollPane) Calendar(java.util.Calendar) JComponent(javax.swing.JComponent) JLabel(javax.swing.JLabel) Dimension(java.awt.Dimension) IOException(java.io.IOException) JToolBar(javax.swing.JToolBar) InputVerifier(javax.swing.InputVerifier) Date(java.util.Date) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) IOException(java.io.IOException) HeaderPanel(com.gitblit.client.HeaderPanel)

Example 50 with JToolBar

use of javax.swing.JToolBar in project zaproxy by zaproxy.

the class HttpPanel method initUi.

private void initUi() {
    allOptions = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
    componentOptions = new JPanel(new BorderLayout(0, 0));
    moreOptionsComponent = new JPanel(new BorderLayout(0, 0));
    toolBarComponents = new JToolBar();
    toolBarComponents.setFloatable(false);
    toolBarComponents.setBorder(BorderFactory.createEmptyBorder());
    toolBarComponents.setRollover(true);
    toolBarMoreOptions = new JToolBar();
    toolBarMoreOptions.setFloatable(false);
    toolBarMoreOptions.setBorder(BorderFactory.createEmptyBorder());
    toolBarMoreOptions.setRollover(true);
    toolBarMoreOptions.getActionMap().put("findAction", getFindAction());
    toolBarMoreOptions.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ExtensionEdit.getFindDefaultKeyStroke(), "findAction");
    endAllOptions = new JPanel();
    JPanel panel1 = new JPanel(new BorderLayout(0, 0));
    JPanel panelFlow = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
    panelFlow.add(allOptions);
    panelFlow.add(componentOptions);
    panelFlow.add(toolBarComponents);
    panelFlow.add(moreOptionsComponent);
    panelFlow.add(toolBarMoreOptions);
    panel1.add(panelFlow, BorderLayout.WEST);
    panelFlow = new JPanel(new FlowLayout(FlowLayout.CENTER, 0, 0));
    panelFlow.add(endAllOptions);
    panel1.add(panelFlow, BorderLayout.EAST);
    panelHeader.add(panel1, BorderLayout.NORTH);
    // getPanelContent().add(new EmptyComponent(), "");
    initComponents();
    setMessage(null);
}
Also used : JPanel(javax.swing.JPanel) FlowLayout(java.awt.FlowLayout) BorderLayout(java.awt.BorderLayout) JToolBar(javax.swing.JToolBar)

Aggregations

JToolBar (javax.swing.JToolBar)124 JButton (javax.swing.JButton)51 BorderLayout (java.awt.BorderLayout)45 JPanel (javax.swing.JPanel)37 JScrollPane (javax.swing.JScrollPane)30 Dimension (java.awt.Dimension)25 Insets (java.awt.Insets)25 ActionEvent (java.awt.event.ActionEvent)24 JLabel (javax.swing.JLabel)23 ActionListener (java.awt.event.ActionListener)19 ImageIcon (javax.swing.ImageIcon)17 Component (java.awt.Component)14 JSplitPane (javax.swing.JSplitPane)14 JTable (javax.swing.JTable)14 JTextField (javax.swing.JTextField)14 JPopupMenu (javax.swing.JPopupMenu)13 JToggleButton (javax.swing.JToggleButton)12 GridBagConstraints (java.awt.GridBagConstraints)10 GridBagLayout (java.awt.GridBagLayout)10 JComponent (javax.swing.JComponent)10