org.netbeans.modules.php.fuel.options.FuelPhpOptionsPanel.java Source code

Java tutorial

Introduction

Here is the source code for org.netbeans.modules.php.fuel.options.FuelPhpOptionsPanel.java

Source

/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright 2013 Oracle and/or its affiliates. All rights reserved.
 *
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
 * Other names may be trademarks of their respective owners.
 *
 * The contents of this file are subject to the terms of either the GNU
 * General Public License Version 2 only ("GPL") or the Common
 * Development and Distribution License("CDDL") (collectively, the
 * "License"). You may not use this file except in compliance with the
 * License. You can obtain a copy of the License at
 * http://www.netbeans.org/cddl-gplv2.html
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
 * specific language governing permissions and limitations under the
 * License.  When distributing the software, include this License Header
 * Notice in each file and include the License file at
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the GPL Version 2 section of the License file that
 * accompanied this code. If applicable, add the following below the
 * License Header, with the fields enclosed by brackets [] replaced by
 * your own identifying information:
 * "Portions Copyrighted [year] [name of copyright owner]"
 *
 * If you wish your version of this file to be governed by only the CDDL
 * or only the GPL Version 2, indicate your decision by adding
 * "[Contributor] elects to include this software in this distribution
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
 * single choice of license, a recipient has the option to distribute
 * your version of this file under either the CDDL, the GPL Version 2 or
 * to extend the choice of license to its licensees as provided above.
 * However, if you add GPL Version 2 code and therefore, elected the GPL
 * Version 2 license, then the option applies only if the new code is
 * made subject to such option by the copyright holder.
 *
 * Contributor(s):
 *
 * Portions Copyrighted 2013 Sun Microsystems, Inc.
 */
package org.netbeans.modules.php.fuel.options;

import java.beans.PropertyChangeEvent;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultListModel;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.netbeans.api.project.Project;
import org.netbeans.api.project.ui.OpenProjects;
import org.netbeans.modules.php.api.phpmodule.PhpModule;
import org.netbeans.modules.php.fuel.FuelPhp;
import org.netbeans.modules.php.fuel.modules.FuelPhpModule;
import org.netbeans.modules.php.fuel.util.FuelUtils;

final class FuelPhpOptionsPanel extends javax.swing.JPanel {

    private static final String GITHUB_API_REPOS_BRANCHES = "https://api.github.com/repos/fuel/fuel/branches"; // NOI18N
    private static final long serialVersionUID = -297941163558564802L;
    private final FuelPhpOptionsPanelController controller;
    private static final Logger LOGGER = Logger.getLogger(FuelPhpOptionsPanel.class.getName());
    private boolean isNetworkError;

    FuelPhpOptionsPanel(FuelPhpOptionsPanelController controller) {
        this.controller = controller;
        initComponents();
    }

    private void setNotifyAutodetection() {
        notifyAutodetectionCheckBox.setSelected(FuelPhpOptions.getInstance().isNotifyAutodetection());
    }

    private void setBranches() {
        // branchesComboBox.add
        FuelPhpOptions options = FuelPhpOptions.getInstance();
        branchesComboBox.removeAllItems();
        branchesComboBox.addItem(options.getGitBranchName());
        branchesComboBox.setEnabled(!isNetworkError);
    }

    private void setDefaultConfig() {
        // default config
        FuelPhpOptions options = FuelPhpOptions.getInstance();
        defaultConfigCheckBox.setSelected(options.isDefaultConfig());
        defaultConfigEditorPane.setText(options.getDefaultConfig());
    }

    private void setAvailableNodes() {
        DefaultListModel<String> defaultListModel = new DefaultListModel<String>();
        for (String node : FuelPhp.CUSTOM_NODES) {
            defaultListModel.addElement(node);
        }
        nodeList.setModel(defaultListModel);
        List<String> availableNodes = FuelPhpOptions.getInstance().getAvailableNodes();
        for (String node : availableNodes) {
            int indexOf = defaultListModel.indexOf(node);
            nodeList.addSelectionInterval(indexOf, indexOf);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        branchesLabel = new javax.swing.JLabel();
        branchesComboBox = new javax.swing.JComboBox<String>();
        defaultConfigCheckBox = new javax.swing.JCheckBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        defaultConfigEditorPane = new javax.swing.JEditorPane();
        reloadButton = new javax.swing.JButton();
        jScrollPane2 = new javax.swing.JScrollPane();
        nodeList = new javax.swing.JList<String>();
        availableNodesLabel = new javax.swing.JLabel();
        notifyAutodetectionCheckBox = new javax.swing.JCheckBox();

        org.openide.awt.Mnemonics.setLocalizedText(branchesLabel, org.openide.util.NbBundle
                .getMessage(FuelPhpOptionsPanel.class, "FuelPhpOptionsPanel.branchesLabel.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(defaultConfigCheckBox, org.openide.util.NbBundle
                .getMessage(FuelPhpOptionsPanel.class, "FuelPhpOptionsPanel.defaultConfigCheckBox.text")); // NOI18N

        defaultConfigEditorPane.setContentType("text/x-php5"); // NOI18N
        jScrollPane1.setViewportView(defaultConfigEditorPane);
        defaultConfigEditorPane.getAccessibleContext()
                .setAccessibleDescription(org.openide.util.NbBundle.getMessage(FuelPhpOptionsPanel.class,
                        "FuelPhpOptionsPanel.defaultConfigEditorPane.AccessibleContext.accessibleDescription")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(reloadButton, org.openide.util.NbBundle
                .getMessage(FuelPhpOptionsPanel.class, "FuelPhpOptionsPanel.reloadButton.text")); // NOI18N
        reloadButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                reloadButtonActionPerformed(evt);
            }
        });

        jScrollPane2.setViewportView(nodeList);

        org.openide.awt.Mnemonics.setLocalizedText(availableNodesLabel, org.openide.util.NbBundle
                .getMessage(FuelPhpOptionsPanel.class, "FuelPhpOptionsPanel.availableNodesLabel.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(notifyAutodetectionCheckBox, org.openide.util.NbBundle
                .getMessage(FuelPhpOptionsPanel.class, "FuelPhpOptionsPanel.notifyAutodetectionCheckBox.text")); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addContainerGap().addGroup(layout
                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup().addGroup(layout
                                .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jScrollPane1)
                                .addGroup(layout.createSequentialGroup().addGroup(layout
                                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(branchesLabel)
                                        .addGroup(layout.createSequentialGroup()
                                                .addComponent(branchesComboBox,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE, 200,
                                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                                .addComponent(reloadButton))
                                        .addComponent(defaultConfigCheckBox)).addGap(0, 0, Short.MAX_VALUE)))
                                .addGap(18, 18, 18)
                                .addGroup(layout
                                        .createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(availableNodesLabel, javax.swing.GroupLayout.DEFAULT_SIZE,
                                                javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(jScrollPane2)))
                        .addGroup(layout.createSequentialGroup().addComponent(notifyAutodetectionCheckBox).addGap(0,
                                0, Short.MAX_VALUE)))
                        .addContainerGap()));
        layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup().addContainerGap().addComponent(notifyAutodetectionCheckBox)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(branchesLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(branchesComboBox, javax.swing.GroupLayout.PREFERRED_SIZE,
                                        javax.swing.GroupLayout.DEFAULT_SIZE,
                                        javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(reloadButton))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(defaultConfigCheckBox).addComponent(availableNodesLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jScrollPane2).addComponent(jScrollPane1,
                                        javax.swing.GroupLayout.DEFAULT_SIZE, 136, Short.MAX_VALUE))
                        .addContainerGap()));
    }// </editor-fold>//GEN-END:initComponents

    private void reloadButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_reloadButtonActionPerformed
        branchesComboBox.removeAllItems();
        branchesComboBox.addItem(""); // NOI18N
        for (String branch : getBranches()) {
            branchesComboBox.addItem(branch);
        }
        FuelPhpOptions options = FuelPhpOptions.getInstance();
        branchesComboBox.setSelectedItem(options.getGitBranchName());
        branchesComboBox.setEnabled(!isNetworkError);
    }//GEN-LAST:event_reloadButtonActionPerformed

    void load() {
        setBranches();
        setDefaultConfig();
        setAvailableNodes();
        setNotifyAutodetection();
    }

    void store() {
        FuelPhpOptions options = FuelPhpOptions.getInstance();
        // notify autodetection
        options.setNotifyAutodetection(notifyAutodetectionCheckBox.isSelected());
        // default config
        options.setDefaultConfig(defaultConfigCheckBox.isSelected());
        options.setDefaultConfig(defaultConfigEditorPane.getText());

        if (isNetworkError) {
            return;
        }

        // branch
        String selectedItem = (String) branchesComboBox.getSelectedItem();
        if (selectedItem != null) {
            options.setGitBranchName(selectedItem);
        }

        // nodes
        List<String> selectedNodes = nodeList.getSelectedValuesList();
        options.setAvailableNodes(selectedNodes);
        Project[] openProjects = OpenProjects.getDefault().getOpenProjects();
        for (Project project : openProjects) {
            PhpModule phpModule = PhpModule.Factory.lookupPhpModule(project);
            if (phpModule != null) {
                if (FuelUtils.isFuelPHP(phpModule)) {
                    FuelPhpModule fuelModule = FuelPhpModule.forPhpModule(phpModule);
                    fuelModule.notifyPropertyChanged(
                            new PropertyChangeEvent(this, FuelPhpModule.PROPERTY_CHANGE_FUEL, null, null));
                }
            }
        }
    }

    boolean valid() {
        // TODO check whether form is consistent and complete
        return true;
    }

    private List<String> getBranches() {
        List<String> branches = new ArrayList<String>();
        isNetworkError = false;
        try {
            // Get JSON
            URL branchesJson = new URL(GITHUB_API_REPOS_BRANCHES);
            BufferedReader reader = new BufferedReader(new InputStreamReader(branchesJson.openStream(), "UTF-8")); // NOI18N
            StringBuilder contents = new StringBuilder();
            String str;
            while ((str = reader.readLine()) != null) {
                contents.append(str);
            }

            JSONArray json = new JSONArray(contents.toString());
            branches = new ArrayList<String>(json.length());
            for (int i = 0; i < json.length(); i++) {
                JSONObject jObject = (JSONObject) json.get(i);
                branches.add(jObject.getString("name")); // NOI18N
            }
        } catch (JSONException ex) {
            LOGGER.log(Level.WARNING, null, ex);
        } catch (IOException ex) {
            isNetworkError = true;
            LOGGER.log(Level.WARNING, "Can not connect to Internet.");
        }
        return branches;
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel availableNodesLabel;
    private javax.swing.JComboBox<String> branchesComboBox;
    private javax.swing.JLabel branchesLabel;
    private javax.swing.JCheckBox defaultConfigCheckBox;
    private javax.swing.JEditorPane defaultConfigEditorPane;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JList<String> nodeList;
    private javax.swing.JCheckBox notifyAutodetectionCheckBox;
    private javax.swing.JButton reloadButton;
    // End of variables declaration//GEN-END:variables
}