/*
 * Copyright (C) 2005 - 2011 Jaspersoft Corporation. All rights reserved.
 * http://www.jaspersoft.com.
 *
 * Unless you have purchased  a commercial license agreement from Jaspersoft,
 * the following license terms  apply:
 *
 * This program is free software: you can redistribute it and/or  modify
 * it under the terms of the GNU Affero General Public License  as
 * published by the Free Software Foundation, either version 3 of  the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero  General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public  License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package com.jaspersoft.jasperserver.irplugin.gui;

import com.jaspersoft.jasperserver.irplugin.ControlsSet;
import com.jaspersoft.jasperserver.irplugin.IRPlugin;
import com.jaspersoft.jasperserver.irplugin.JServer;
import com.jaspersoft.jasperserver.irplugin.ReportRunner;
import com.jaspersoft.jasperserver.irplugin.RepositoryFolder;
import com.jaspersoft.jasperserver.irplugin.RepositoryJrxmlFile;
import com.jaspersoft.jasperserver.irplugin.RepositoryReportUnit;
import com.jaspersoft.jasperserver.irplugin.ResourcesSet;
import com.jaspersoft.jasperserver.irplugin.gui.explorer.ResourceChooser;
import com.jaspersoft.jasperserver.irplugin.gui.wizard.NewReportUnitWizard;

import com.jaspersoft.jasperserver.irplugin.wsclient.WSClient;

import com.jaspersoft.jasperserver.api.metadata.xml.domain.impl.*;
import com.jaspersoft.jasperserver.irplugin.RepositoryFile;
import com.jaspersoft.jasperserver.irplugin.gui.inputcontrols.BasicInputControl;
import it.businesslogic.ireport.IRFont;
import it.businesslogic.ireport.gui.logpane.LogTextArea;
import it.businesslogic.ireport.util.I18n;
import it.businesslogic.ireport.util.LanguageChangedEvent;
import it.businesslogic.ireport.util.LanguageChangedListener;
import it.businesslogic.ireport.util.Misc;

import java.awt.Cursor;
import java.awt.dnd.DropTarget;
import java.io.File;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.DefaultTreeSelectionModel;
import javax.swing.tree.TreePath;
import it.businesslogic.ireport.gui.MainFrame;
import java.io.StringWriter;
import javax.swing.JFileChooser;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JExcelApiExporterParameter;
import net.sf.jasperreports.engine.export.JRCsvExporterParameter;
import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
import net.sf.jasperreports.engine.export.JRPdfExporterParameter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import net.sf.jasperreports.view.JasperViewer;

import com.jaspersoft.jasperserver.ws.xml.Marshaller;
import com.jaspersoft.jasperserver.ws.xml.Unmarshaller;
import java.util.HashMap;

/**
 *
 * @author  gtoffoli
 */
public class RepositoryExplorer extends javax.swing.JPanel {
    
    private IRPlugin plugin = null;
    private boolean treeEnabled = true;
    
    
    /** Creates new form RepositoryExplorer */
    public RepositoryExplorer(IRPlugin plugin) {
        initComponents();
        
        jTreeRepository.setDragEnabled(true);
        jTreeRepository.setTransferHandler(new ReportElementTransferHandler());

        jTreeRepository.setDropTarget( new DropTarget(jTreeRepository, new it.businesslogic.ireport.gui.docking.GenericDragTargetListener()));
        this.setPlugin(plugin);
        jTreeRepository.setCellRenderer( new RepositoryTreeCellRenderer() );
        jTreeRepository.getSelectionModel().setSelectionMode( DefaultTreeSelectionModel.SINGLE_TREE_SELECTION );
        // load configuration
        loadServerList();
        
        I18n.addOnLanguageChangedListener( new LanguageChangedListener() {
            public void languageChanged(LanguageChangedEvent languageChangedEvent) {
                applyI18n();
                jTreeRepository.updateUI();
            }
        });
        
        applyI18n();
    }
    
    
    public void applyI18n()
    {
        jButtonAddServer.setToolTipText( IRPlugin.getString("tooltip.newserver", "Add new server") );
        jButtonNewReportUnit.setToolTipText( IRPlugin.getString("tooltip.newreportunit", "Create a new Report Unit") );
        jButtonSaveJrxml.setToolTipText( IRPlugin.getString("tooltip.savejrxml", "Save jrxml") );
        jButtonRunReport.setToolTipText( IRPlugin.getString("tooltip.runreportunit", "Run Report Unit") );
        
        jMenuAdd.setText( IRPlugin.getString("menu.add", "Add") );
        jMenuItemBundle.setText( IRPlugin.getString("menu.bundle", "Resource bundle") );
        jMenuItemConnection.setText( IRPlugin.getString("menu.connection", "Import JDBC connection definition") );
        jMenuItemDataType.setText( IRPlugin.getString("menu.dataType", "Datatype") );
        jMenuItemDatasource.setText( IRPlugin.getString("menu.datasource", "Datasource") );
        jMenuItemXMLADatasource.setText( IRPlugin.getString("menu.xmlaConnection", "XMLA Connection") );
        jMenuItemDelete.setText( IRPlugin.getString("menu.delete", "Delete") );
        jMenuItemEditJRXML.setText( IRPlugin.getString("menu.editJRXML", "Edit JRXML") );
        jMenuItemExplore.setText( IRPlugin.getString("menu.explore", "Explore") );
        jMenuItemFolder.setText( IRPlugin.getString("menu.folder", "Folder") );
        jMenuItemFont.setText( IRPlugin.getString("menu.font", "Font file") );
        jMenuItemGet.setText( IRPlugin.getString("menu.get", "Export file") );
        jMenuItemImage.setText( IRPlugin.getString("menu.image", "Image") );
        jMenuItemImportFont.setText( IRPlugin.getString("menu.importFont", "Add this font to the font list") );
        jMenuItemInputControl.setText( IRPlugin.getString("menu.inputControl", "Input control") );
        jMenuItemJar.setText( IRPlugin.getString("menu.jar", "Jar archive") );
        jMenuItemJrxml.setText( IRPlugin.getString("menu.Jrxml", "JRXML document") );
        jMenuItemLinkInputControl.setText( IRPlugin.getString("menu.linkInputControl", "Link an existing input control") );
        jMenuItemListOfValues.setText( IRPlugin.getString("menu.listOfValues", "List of values") );
        jMenuItemLocalInputControl.setText( IRPlugin.getString("menu.localInputControl", "Create a local input control") );
        jMenuItemLogin.setText( IRPlugin.getString("menu.login", "Login") );
        jMenuItemNewServer.setText( IRPlugin.getString("menu.newServer", "New server") );
        jMenuItemProperties.setText( IRPlugin.getString("menu.properties", "Properties") );
        jMenuItemQuery.setText( IRPlugin.getString("menu.query", "Query") );
        jMenuItemReference.setText( IRPlugin.getString("menu.reference", "Reference") );
        jMenuItemRefresh.setText( IRPlugin.getString("menu.refresh", "Refresh") );
        jMenuItemRefreshContent.setText( IRPlugin.getString("menu.refreshContent", "Refresh content") );
        jMenuItemReportUnit.setText( IRPlugin.getString("menu.reportUnit", "Report Unit") );
        jMenuItemRunRU.setText( IRPlugin.getString("menu.runReportUnit", "Run Report Unit") );
        jMenuItemServerDelete.setText( IRPlugin.getString("menu.serverDelete", "Delete server") );
        jMenuItemServerSettings.setText( IRPlugin.getString("menu.serverSettings", "Server settings") );
         
    }
    /**
     * Load the plugin configuration file stored in the .ireport directory
     * in the user home....
     * In the configuration file are sotred all server configurations...
     */
    public void loadServerList()
    {
        //
        jTreeRepository.removeAll();
        DefaultMutableTreeNode rootNode= new DefaultMutableTreeNode();
        ((DefaultTreeModel)jTreeRepository.getModel()).setRoot(rootNode);
        
        for (int i=0; i < this.getPlugin().getJServers().size(); ++i)
        {
            JServer server = (JServer)this.getPlugin().getJServers().get(i);            
            DefaultMutableTreeNode serverNode= new DefaultMutableTreeNode(server);
            rootNode.add( serverNode );
        }
        
        //jButtonNewReportUnit.setEnabled(this.getPlugin().getJServers().size() > 0);      
        
        jTreeRepository.updateUI();
    }
    
    public IRPlugin getPlugin() {
        return plugin;
    }

    public void setPlugin(IRPlugin plugin) {
        this.plugin = plugin;
    }
    
    /**
     * Update the toolbar status buttons based on the selection.
     *
     */
    public void updateToolBar()
    {
        TreePath path = jTreeRepository.getSelectionPath();
        if (path == null) return;
        
        jButtonSaveJrxml.setEnabled(false);
        jButtonNewReportUnit.setEnabled(false);
        jButtonRunReport.setEnabled(false);
        
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
        
        
        
        if ( selectedNode.getUserObject() instanceof RepositoryJrxmlFile )
        {
            RepositoryJrxmlFile rf = (RepositoryJrxmlFile)selectedNode.getUserObject();
            if (rf.getReportFrame() != null)
            {
                jButtonSaveJrxml.setEnabled(true);
            }
        }
        
        if ( selectedNode.getUserObject() instanceof RepositoryFolder )
        {
            RepositoryFolder rf = (RepositoryFolder)selectedNode.getUserObject();
            if (rf.getDescriptor().getWsType().equals(ResourceDescriptor.TYPE_FOLDER))
            {
                
                jButtonNewReportUnit.setEnabled(true);
            }
            
            if (rf.getDescriptor().getWsType().equals("ReportOptionsResource"))
            {
                jButtonRunReport.setEnabled(true);
            }
        }
        
        if ( getParentReportUnit(selectedNode) != null)
        {
            jButtonRunReport.setEnabled(true);
        }
        
        else if ( selectedNode.getUserObject() instanceof JServer )
        {
            jButtonNewReportUnit.setEnabled(true);
        }
    }
    
    /** 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() {

        jPopupMenuServer = new javax.swing.JPopupMenu();
        jMenuItemRunRU = new javax.swing.JMenuItem();
        jMenuItemEditJRXML = new javax.swing.JMenuItem();
        jMenuItemConnection = new javax.swing.JMenuItem();
        jMenuItemImportFont = new javax.swing.JMenuItem();
        jMenuItemExplore = new javax.swing.JMenuItem();
        jMenuItemGet = new javax.swing.JMenuItem();
        jMenuItemDelete = new javax.swing.JMenuItem();
        jSeparator3 = new javax.swing.JSeparator();
        jMenuAdd = new javax.swing.JMenu();
        jMenuItemReportUnit = new javax.swing.JMenuItem();
        jSeparator5 = new javax.swing.JSeparator();
        jMenuItemFolder = new javax.swing.JMenuItem();
        jMenuItemReference = new javax.swing.JMenuItem();
        jSeparator4 = new javax.swing.JSeparator();
        jMenuItemImage = new javax.swing.JMenuItem();
        jMenuItemBundle = new javax.swing.JMenuItem();
        jMenuItemJrxml = new javax.swing.JMenuItem();
        jMenuItemJar = new javax.swing.JMenuItem();
        jMenuItemFont = new javax.swing.JMenuItem();
        jSeparator6 = new javax.swing.JSeparator();
        jMenuItemDatasource = new javax.swing.JMenuItem();
        jMenuItemXMLADatasource = new javax.swing.JMenuItem();
        jSeparator7 = new javax.swing.JSeparator();
        jMenuItemDataType = new javax.swing.JMenuItem();
        jMenuItemListOfValues = new javax.swing.JMenuItem();
        jMenuItemQuery = new javax.swing.JMenuItem();
        jMenuItemInputControl = new javax.swing.JMenuItem();
        jSeparator1 = new javax.swing.JSeparator();
        jMenuItemLogin = new javax.swing.JMenuItem();
        jMenuItemNewServer = new javax.swing.JMenuItem();
        jMenuItemServerSettings = new javax.swing.JMenuItem();
        jMenuItemServerDelete = new javax.swing.JMenuItem();
        jSeparator2 = new javax.swing.JSeparator();
        jMenuItemRefresh = new javax.swing.JMenuItem();
        jMenuItemRefreshContent = new javax.swing.JMenuItem();
        jMenuItemProperties = new javax.swing.JMenuItem();
        jPopupMenuRUInputControls = new javax.swing.JPopupMenu();
        jMenuItemLocalInputControl = new javax.swing.JMenuItem();
        jMenuItemLinkInputControl = new javax.swing.JMenuItem();
        jToolBar1 = new javax.swing.JToolBar();
        jButtonAddServer = new javax.swing.JButton();
        jButtonNewReportUnit = new javax.swing.JButton();
        jButtonSaveJrxml = new javax.swing.JButton();
        jButtonRunReport = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTreeRepository = new javax.swing.JTree();

        jPopupMenuServer.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jPopupMenuServerMouseClicked(evt);
            }
        });

        jMenuItemRunRU.setText("Run Report Unit");
        jMenuItemRunRU.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemRunRUActionPerformed(evt);
            }
        });
        jPopupMenuServer.add(jMenuItemRunRU);

        jMenuItemEditJRXML.setText("Edit JRXML");
        jMenuItemEditJRXML.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemEditJRXMLActionPerformed(evt);
            }
        });
        jPopupMenuServer.add(jMenuItemEditJRXML);

        jMenuItemConnection.setText("Import JDBC connection definition");
        jMenuItemConnection.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemConnectionActionPerformed(evt);
            }
        });
        jPopupMenuServer.add(jMenuItemConnection);

        jMenuItemImportFont.setText("Add this font to the font list");
        jMenuItemImportFont.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemImportFontActionPerformed(evt);
            }
        });
        jPopupMenuServer.add(jMenuItemImportFont);

        jMenuItemExplore.setText("Explore");
        jMenuItemExplore.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemExploreActionPerformed(evt);
            }
        });
        jPopupMenuServer.add(jMenuItemExplore);

        jMenuItemGet.setText("Export file");
        jMenuItemGet.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemGetActionPerformed(evt);
            }
        });
        jPopupMenuServer.add(jMenuItemGet);

        jMenuItemDelete.setText("Delete");
        jMenuItemDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemDeleteActionPerformed(evt);
            }
        });
        jPopupMenuServer.add(jMenuItemDelete);
        jPopupMenuServer.add(jSeparator3);

        jMenuAdd.setText("Add");

        jMenuItemReportUnit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jaspersoft/jasperserver/irplugin/res/reportunit.png"))); // NOI18N
        jMenuItemReportUnit.setText("Report Unit");
        jMenuItemReportUnit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemReportUnitActionPerformed(evt);
            }
        });
        jMenuAdd.add(jMenuItemReportUnit);
        jMenuAdd.add(jSeparator5);

        jMenuItemFolder.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jaspersoft/jasperserver/irplugin/res/folder.png"))); // NOI18N
        jMenuItemFolder.setText("Folder");
        jMenuItemFolder.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemFolderActionPerformed(evt);
            }
        });
        jMenuAdd.add(jMenuItemFolder);

        jMenuItemReference.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jaspersoft/jasperserver/irplugin/res/link.png"))); // NOI18N
        jMenuItemReference.setText("Reference");
        jMenuItemReference.setEnabled(false);
        jMenuItemReference.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemReferenceActionPerformed(evt);
            }
        });
        jMenuAdd.add(jMenuItemReference);
        jMenuAdd.add(jSeparator4);

        jMenuItemImage.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jaspersoft/jasperserver/irplugin/res/picture.png"))); // NOI18N
        jMenuItemImage.setText("Image");
        jMenuItemImage.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemImageActionPerformed(evt);
            }
        });
        jMenuAdd.add(jMenuItemImage);

        jMenuItemBundle.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jaspersoft/jasperserver/irplugin/res/bundle.png"))); // NOI18N
        jMenuItemBundle.setText("Resource bundle");
        jMenuItemBundle.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemBundleActionPerformed(evt);
            }
        });
        jMenuAdd.add(jMenuItemBundle);

        jMenuItemJrxml.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jaspersoft/jasperserver/irplugin/res/jrxml_file.png"))); // NOI18N
        jMenuItemJrxml.setText("JRXML document");
        jMenuItemJrxml.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemJrxmlActionPerformed(evt);
            }
        });
        jMenuAdd.add(jMenuItemJrxml);

        jMenuItemJar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jaspersoft/jasperserver/irplugin/res/jar.png"))); // NOI18N
        jMenuItemJar.setText("Jar archive");
        jMenuItemJar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemJarActionPerformed(evt);
            }
        });
        jMenuAdd.add(jMenuItemJar);

        jMenuItemFont.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jaspersoft/jasperserver/irplugin/res/font.png"))); // NOI18N
        jMenuItemFont.setText("Font file");
        jMenuItemFont.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemFontActionPerformed(evt);
            }
        });
        jMenuAdd.add(jMenuItemFont);
        jMenuAdd.add(jSeparator6);

        jMenuItemDatasource.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jaspersoft/jasperserver/irplugin/res/datasource.png"))); // NOI18N
        jMenuItemDatasource.setText("Datasource");
        jMenuItemDatasource.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemDataSourceActionPerformed(evt);
            }
        });
        jMenuAdd.add(jMenuItemDatasource);

        jMenuItemXMLADatasource.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jaspersoft/jasperserver/irplugin/res/datasource.png"))); // NOI18N
        jMenuItemXMLADatasource.setText("XMLA Connection");
        jMenuItemXMLADatasource.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemDatasourcejMenuItemDataSourceActionPerformed1(evt);
            }
        });
        jMenuAdd.add(jMenuItemXMLADatasource);
        jMenuAdd.add(jSeparator7);

        jMenuItemDataType.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jaspersoft/jasperserver/irplugin/res/datatype.png"))); // NOI18N
        jMenuItemDataType.setText("Datatype");
        jMenuItemDataType.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemDatasourcejMenuItemDataSourceActionPerformed(evt);
            }
        });
        jMenuAdd.add(jMenuItemDataType);

        jMenuItemListOfValues.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jaspersoft/jasperserver/irplugin/res/lov.png"))); // NOI18N
        jMenuItemListOfValues.setText("List of values");
        jMenuItemListOfValues.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemDataTypejMenuItemDatasourcejMenuItemDataSourceActionPerformed(evt);
            }
        });
        jMenuAdd.add(jMenuItemListOfValues);

        jMenuItemQuery.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jaspersoft/jasperserver/irplugin/res/query.png"))); // NOI18N
        jMenuItemQuery.setText("Query");
        jMenuItemQuery.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemQueryActionPerformed(evt);
            }
        });
        jMenuAdd.add(jMenuItemQuery);

        jMenuItemInputControl.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jaspersoft/jasperserver/irplugin/res/inputcontrol.png"))); // NOI18N
        jMenuItemInputControl.setText("Input control");
        jMenuItemInputControl.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemInputControlActionPerformed(evt);
            }
        });
        jMenuAdd.add(jMenuItemInputControl);

        jPopupMenuServer.add(jMenuAdd);
        jPopupMenuServer.add(jSeparator1);

        jMenuItemLogin.setText("Login");
        jMenuItemLogin.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemLoginActionPerformed(evt);
            }
        });
        jPopupMenuServer.add(jMenuItemLogin);

        jMenuItemNewServer.setText("New server");
        jMenuItemNewServer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemNewServerActionPerformed(evt);
            }
        });
        jPopupMenuServer.add(jMenuItemNewServer);

        jMenuItemServerSettings.setText("Server settings");
        jMenuItemServerSettings.setEnabled(false);
        jMenuItemServerSettings.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemServerSettingsActionPerformed(evt);
            }
        });
        jPopupMenuServer.add(jMenuItemServerSettings);

        jMenuItemServerDelete.setText("Delete server");
        jMenuItemServerDelete.setEnabled(false);
        jMenuItemServerDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemServerDeleteActionPerformed(evt);
            }
        });
        jPopupMenuServer.add(jMenuItemServerDelete);
        jPopupMenuServer.add(jSeparator2);

        jMenuItemRefresh.setText("Refresh");
        jMenuItemRefresh.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemRefreshActionPerformed(evt);
            }
        });
        jPopupMenuServer.add(jMenuItemRefresh);

        jMenuItemRefreshContent.setText("Refresh content");
        jMenuItemRefreshContent.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemRefreshContentActionPerformed(evt);
            }
        });
        jPopupMenuServer.add(jMenuItemRefreshContent);

        jMenuItemProperties.setText("Properties");
        jMenuItemProperties.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemPropertiesActionPerformed(evt);
            }
        });
        jPopupMenuServer.add(jMenuItemProperties);

        jMenuItemLocalInputControl.setText("Create a local input control");
        jMenuItemLocalInputControl.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemLocalInputControlActionPerformed(evt);
            }
        });
        jPopupMenuRUInputControls.add(jMenuItemLocalInputControl);

        jMenuItemLinkInputControl.setText("Link an existing input control");
        jMenuItemLinkInputControl.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jMenuItemLinkInputControlActionPerformed(evt);
            }
        });
        jPopupMenuRUInputControls.add(jMenuItemLinkInputControl);

        setLayout(new java.awt.BorderLayout());

        jButtonAddServer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jaspersoft/jasperserver/irplugin/res/server_add.png"))); // NOI18N
        jButtonAddServer.setText("\n");
        jButtonAddServer.setToolTipText("Add new server");
        jButtonAddServer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAddServerActionPerformed(evt);
            }
        });
        jToolBar1.add(jButtonAddServer);

        jButtonNewReportUnit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jaspersoft/jasperserver/irplugin/res/publish.png"))); // NOI18N
        jButtonNewReportUnit.setToolTipText("Create a new Report Unit");
        jButtonNewReportUnit.setEnabled(false);
        jButtonNewReportUnit.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonPublishReportActionPerformed1(evt);
            }
        });
        jToolBar1.add(jButtonNewReportUnit);

        jButtonSaveJrxml.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jaspersoft/jasperserver/irplugin/res/upload_jrxml.png"))); // NOI18N
        jButtonSaveJrxml.setToolTipText("Save jrxml");
        jButtonSaveJrxml.setEnabled(false);
        jButtonSaveJrxml.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSaveJrxmlActionPerformed(evt);
            }
        });
        jToolBar1.add(jButtonSaveJrxml);

        jButtonRunReport.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/jaspersoft/jasperserver/irplugin/res/run_report.png"))); // NOI18N
        jButtonRunReport.setToolTipText("Run Report Unit");
        jButtonRunReport.setEnabled(false);
        jButtonRunReport.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonRunReportActionPerformed(evt);
            }
        });
        jToolBar1.add(jButtonRunReport);

        add(jToolBar1, java.awt.BorderLayout.NORTH);

        jTreeRepository.setRootVisible(false);
        jTreeRepository.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTreeRepositoryMouseClicked(evt);
            }
            public void mousePressed(java.awt.event.MouseEvent evt) {
                jTreeRepositoryMousePressed(evt);
            }
            public void mouseReleased(java.awt.event.MouseEvent evt) {
                jTreeRepositoryMouseReleased(evt);
            }
        });
        jTreeRepository.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
            public void valueChanged(javax.swing.event.TreeSelectionEvent evt) {
                jTreeRepositoryValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(jTreeRepository);

        add(jScrollPane1, java.awt.BorderLayout.CENTER);
    }// </editor-fold>//GEN-END:initComponents

    private void jMenuItemDatasourcejMenuItemDataSourceActionPerformed1(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemDatasourcejMenuItemDataSourceActionPerformed1
        newResource(ResourceDescriptor.TYPE_OLAP_XMLA_CONNECTION);
    }//GEN-LAST:event_jMenuItemDatasourcejMenuItemDataSourceActionPerformed1

    private void jMenuItemQueryActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemQueryActionPerformed
        newResource(ResourceDescriptor.TYPE_QUERY);
    }//GEN-LAST:event_jMenuItemQueryActionPerformed

    private void jMenuItemRunRUActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemRunRUActionPerformed

        jButtonRunReportActionPerformed(evt);
    }//GEN-LAST:event_jMenuItemRunRUActionPerformed

    private void jButtonRunReportActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonRunReportActionPerformed

         TreePath path = jTreeRepository.getSelectionPath();
         if (path == null) return;
         DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
         
         RepositoryReportUnit reportUnit = null;
         ResourceDescriptor optionsRd = null;
         HashMap defaultValues = new HashMap();
         if (selectedNode.getUserObject() instanceof RepositoryFolder)
         {
            if (((RepositoryFolder)selectedNode.getUserObject()).getDescriptor().getWsType().equals("ReportOptionsResource"))
            {
                try {
                    optionsRd = ((com.jaspersoft.jasperserver.irplugin.RepositoryFolder) selectedNode.getUserObject()).getDescriptor();
                    java.lang.String ruURI = optionsRd.getResourcePropertyValue("PROP_RU_URI");
                    com.jaspersoft.jasperserver.api.metadata.xml.domain.impl.ResourceDescriptor reportRd = new com.jaspersoft.jasperserver.api.metadata.xml.domain.impl.ResourceDescriptor();
                    reportRd.setUriString(ruURI);
                    reportRd = ((com.jaspersoft.jasperserver.irplugin.RepositoryFolder) selectedNode.getUserObject()).getServer().getWSClient().get(reportRd, null);
                    reportUnit = new com.jaspersoft.jasperserver.irplugin.RepositoryReportUnit(((com.jaspersoft.jasperserver.irplugin.RepositoryFolder) selectedNode.getUserObject()).getServer(), reportRd);
                    reportUnit.setLoaded(false);
                    
                    // get the default values...
                    ResourceProperty rp = optionsRd.getResourceProperty("PROP_VALUES");
        
                    List list = rp.getProperties();
                    if (list != null)
                    {
                        for (int i=0; i<list.size(); ++i)
                        {
                           ResourceProperty li = (ResourceProperty)list.get(i);
                           String value = (li.getValue() == null) ? "" : li.getValue();
                           if (li.getProperties().size() > 0) // it is a list....
                           {
                                java.util.ArrayList listVal = new java.util.ArrayList();
                                for (int k=0; k<li.getProperties().size(); ++k)
                                {
                                    ResourceProperty sli = (ResourceProperty)li.getProperties().get(k);
                                    listVal.add(sli.getValue());
                                }
                                
                                defaultValues.put(li.getName(), (Object)listVal);
                           }
                           else
                           {
                                defaultValues.put(li.getName(), value);
                           }
                        }
                    }
                    
                    
                    
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
         }
         
         
         if (reportUnit == null)
         {
             reportUnit = getParentReportUnit(selectedNode);
         }
            
         if ( reportUnit != null)
         {
             JServer server = reportUnit.getServer();
             LogTextArea lta = MainFrame.getMainInstance().getLogPane().createNewLog();
             lta.setTitle( IRPlugin.getFormattedString("repositoryExplorer.message.runningReport", "Running {0}", new Object[]{reportUnit.getDescriptor().getName()}) );
             MainFrame.getMainInstance().getLogPane().setActiveLog( lta );
             
             try {

                List list = server.getWSClient().list( reportUnit.getDescriptor() );

                String dsUri = null;
                
                List inputcontrols = new java.util.ArrayList();
                // get input controls...
                for (int i=0; i<list.size(); ++i)
                {
                    ResourceDescriptor sub_rd = (ResourceDescriptor)list.get(i);
                    if (sub_rd.getWsType().equals( ResourceDescriptor.TYPE_INPUT_CONTROL))
                    {
                        inputcontrols.add(sub_rd);
                    }
                    else if (sub_rd.getWsType().equals(ResourceDescriptor.TYPE_DATASOURCE))
                    {
                            dsUri = sub_rd.getReferenceUri();
                    }
                    else if ( RepositoryExplorer.isDataSource( sub_rd))
                    {
                            dsUri = sub_rd.getUriString();
                    }
                }
                
               
                
                for (int i=0; i<inputcontrols.size(); ++i)
                {
                        ResourceDescriptor ic = (ResourceDescriptor)inputcontrols.get(i);
                
                        //System.out.println("Got:  " + ic.getName() + " " + ic.getControlType());
                        if (ic.getControlType() == ResourceDescriptor.IC_TYPE_SINGLE_SELECT_QUERY ||
                            ic.getControlType() == ResourceDescriptor.IC_TYPE_SINGLE_SELECT_QUERY_RADIO ||
                            ic.getControlType() == ResourceDescriptor.IC_TYPE_MULTI_SELECT_QUERY ||
                            ic.getControlType() == ResourceDescriptor.IC_TYPE_MULTI_SELECT_QUERY_CHECKBOX)
                        {
                            String dsUriQuery = null;
                            inputcontrols.remove(ic);
                            
                            System.out.println("Looking for the right ds...");
                            // Ask to add values to the control....
                            java.util.List args = new java.util.ArrayList();
                            // reset query data...
                            // Look if this query has a specific datasource...
                            for (int k=0; dsUriQuery == null && k<ic.getChildren().size(); ++k)
                            {
                                ResourceDescriptor sub_ic = (ResourceDescriptor)ic.getChildren().get(k);
                                System.out.println("Found child..." + sub_ic.getName() + " (" + sub_ic.getWsType() +")");
                                if (sub_ic.getWsType().equals(ResourceDescriptor.TYPE_QUERY) )
                                {
                                    System.out.println("Found the query child...");
                                    // Look in the query detail
                                    for (int k2=0; k2<sub_ic.getChildren().size(); ++k2)
                                    {
                                        ResourceDescriptor sub_sub_ic = (ResourceDescriptor)sub_ic.getChildren().get(k2);
                                        if (RepositoryExplorer.isDataSource( sub_sub_ic) )
                                        {
                                            System.out.println("Found the ds child...");
                                            dsUriQuery = sub_sub_ic.getUriString();
                                            
                                            break;
                                        }
                                    }
                                }
                            }
                            if (dsUriQuery == null) dsUriQuery = dsUri;
                            System.out.println("Using..." + dsUriQuery);
                            ic.setResourceProperty(ic.PROP_QUERY_DATA, null);
                            args.add(new Argument( Argument.IC_GET_QUERY_DATA, dsUriQuery));
                            ic = server.getWSClient().get(ic, null, args);
                            
                            inputcontrols.add(i, ic);
                        }
                }
                java.util.Map map = null;
                if (inputcontrols.size() > 0)
                {
                    ReportUnitRunDialog rurd = new ReportUnitRunDialog(MainFrame.getMainInstance(), true);
                    rurd.setServer(server);
                    rurd.setInputControls( inputcontrols, defaultValues);

                    rurd.setVisible(true);
                    if (rurd.getDialogResult() == JOptionPane.OK_OPTION)
                    {
                        map = rurd.getParametersValues();
                    }
                    else
                    {
                        return;
                    }
                }
                else
                {
                    map = new java.util.HashMap();
                }
                
                
                ReportRunner rr = new ReportRunner();
                rr.setLta( lta );
                rr.setMap( map );
                rr.setReportUnit( reportUnit );
                rr.setServer( server );
                
                Thread t = new Thread(rr);
                t.start();
                
             } catch (Exception ex)
             {
                //JOptionPane.showMessageDialog(getPlugin().getMainFrame(),IRPlugin.getFormattedString("messages.error.3", "Error:\n {0}", new Object[] {ex.getMessage()}));
                StringWriter sw = new StringWriter();
                ex.printStackTrace(new java.io.PrintWriter( sw ));
                sw.flush();
                lta.logOnConsole( sw.toString(), false);
                ex.printStackTrace();
             }
             finally
             {
                 lta.setRemovable(true);
             }
         
         }
    }//GEN-LAST:event_jButtonRunReportActionPerformed

    private void jMenuItemLinkInputControlActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemLinkInputControlActionPerformed

        // In this case we choose an input control from the repository....
        ResourceChooser rc = new ResourceChooser();
        
        TreePath path = jTreeRepository.getSelectionPath();
        if (path == null) return;
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
        
        //selectedNode.removeAllChildren();
        JServer server = null;
        
        String reportUnitUri = null;
        
        if ( selectedNode.getUserObject() instanceof ControlsSet)
        {
            RepositoryFolder rf = ((ControlsSet)selectedNode.getUserObject()).getReportUnit();
            rc.setServer( rf.getServer() );
            reportUnitUri = rf.getDescriptor().getUriString();
            
            if (rc.showDialog(this, null) == JOptionPane.OK_OPTION)
            {
                ResourceDescriptor rd = rc.getSelectedDescriptor();
                if (rd == null || rd.getUriString() == null) 
                {
                    return;
                }
                
                if (!rd.getWsType().equals( ResourceDescriptor.TYPE_INPUT_CONTROL))
                {
                    JOptionPane.showMessageDialog(getPlugin().getMainFrame(),
                            IRPlugin.getFormattedString("repositoryExplorer.message.invalidInputControl","{0} is not an Input Control!",new Object[]{rd.getName()}),
                                 "",JOptionPane.ERROR_MESSAGE);
                    return;
                }
                
                ResourceDescriptor newRd = new ResourceDescriptor();
                newRd.setWsType( ResourceDescriptor.TYPE_INPUT_CONTROL);
                newRd.setIsReference(true);
                newRd.setReferenceUri( rd.getUriString() );
                newRd.setIsNew(true);
                newRd.setUriString(reportUnitUri+"/<cotnrols>");
                try {
                    newRd = rf.getServer().getWSClient().modifyReportUnitResource(reportUnitUri, newRd, null);
                    
                    addChild(selectedNode, rf.getServer(), newRd);
                     
                    if (!jTreeRepository.isExpanded(path))
                    {
                        jTreeRepository.expandPath(path);
                    }
                    jTreeRepository.updateUI();
                } catch (Exception ex)
                {
                    JOptionPane.showMessageDialog(getPlugin().getMainFrame(),IRPlugin.getFormattedString("messages.error.3", "Error:\n {0}", new Object[] {ex.getMessage()}));
                    ex.printStackTrace();
                }
            }

        }
        
    }//GEN-LAST:event_jMenuItemLinkInputControlActionPerformed

    private void jMenuItemLocalInputControlActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemLocalInputControlActionPerformed

         newResource( ResourceDescriptor.TYPE_INPUT_CONTROL);
        
    }//GEN-LAST:event_jMenuItemLocalInputControlActionPerformed

    private void jMenuItemInputControlActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemInputControlActionPerformed
        newResource(ResourceDescriptor.TYPE_INPUT_CONTROL);
    }//GEN-LAST:event_jMenuItemInputControlActionPerformed

    private void jMenuItemDataTypejMenuItemDatasourcejMenuItemDataSourceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemDataTypejMenuItemDatasourcejMenuItemDataSourceActionPerformed
        newResource(ResourceDescriptor.TYPE_LOV);
    }//GEN-LAST:event_jMenuItemDataTypejMenuItemDatasourcejMenuItemDataSourceActionPerformed

    private void jMenuItemDatasourcejMenuItemDataSourceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemDatasourcejMenuItemDataSourceActionPerformed
        newResource(ResourceDescriptor.TYPE_DATA_TYPE);
    }//GEN-LAST:event_jMenuItemDatasourcejMenuItemDataSourceActionPerformed

    private void jMenuItemReferenceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemReferenceActionPerformed

        newResource(ResourceDescriptor.TYPE_REFERENCE);
        
    }//GEN-LAST:event_jMenuItemReferenceActionPerformed

    private void jMenuItemDataSourceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemDataSourceActionPerformed

        newResource(ResourceDescriptor.TYPE_DATASOURCE);
        
    }//GEN-LAST:event_jMenuItemDataSourceActionPerformed

    private void jMenuItemImportFontActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemImportFontActionPerformed

         TreePath path = jTreeRepository.getSelectionPath();
         if (path == null) return;
         DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
        
         if ( selectedNode.getUserObject() instanceof RepositoryFile )
         {
            RepositoryFile repoFile = (RepositoryFile)selectedNode.getUserObject();
            if (repoFile.getDescriptor().getWsType().equals(ResourceDescriptor.TYPE_FONT ))
            {
                Vector currentFonts = MainFrame.getMainInstance().getTtfFonts();
                for (int i=0; i<currentFonts.size(); ++i)
                {
                    IRFont irfont = (IRFont)currentFonts.elementAt(i);
                    if ( (irfont.getFile()+"").equals("repo:" + repoFile.getDescriptor().getUriString()) )
                    {
                        return; // Font already present...
                    }
                }
                
                // Font not yet present...
                try {
                    String fontFile = repoFile.getFile();
                    if (fontFile != null)
                    {

                            IRFont newFont = new IRFont( it.businesslogic.ireport.FontListLoader.loadFont(fontFile), "repo:" + repoFile.getDescriptor().getUriString());
                            MainFrame.getMainInstance().getTtfFonts().add(newFont);
                            MainFrame.getMainInstance().updateFontsLists();

                    }
                } catch (Exception ex)
                    {
                        JOptionPane.showMessageDialog(getPlugin().getMainFrame(),IRPlugin.getFormattedString("messages.error.3", "Error:\n {0}", new Object[] {ex.getMessage()}));
                        ex.printStackTrace();
                    }
            }
         }
        
    }//GEN-LAST:event_jMenuItemImportFontActionPerformed

    private void jMenuItemConnectionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemConnectionActionPerformed

        TreePath path = jTreeRepository.getSelectionPath();
         if (path == null) return;
         DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
        
         if ( selectedNode.getUserObject() instanceof RepositoryFile )
         {
             RepositoryFile rf = (RepositoryFile)selectedNode.getUserObject();
             if (rf.getDescriptor().getWsType().equals( ResourceDescriptor.TYPE_DATASOURCE_JDBC))
             {
                 Vector v = MainFrame.getMainInstance().getConnections();
                 
                 int index = -1;
                 for (int i=0; i<v.size(); ++i)
                 {
                     it.businesslogic.ireport.IReportConnection con = (it.businesslogic.ireport.IReportConnection)v.elementAt(i);
                     if (con.getName().equals( rf.getDescriptor().getLabel() ))
                     {
                         if (JOptionPane.showConfirmDialog(this,
                                 IRPlugin.getFormattedString("repositoryExplorer.message.duplicatedConnectionName",
                                 "A connection named {0} is already present.\nWould you like to replace the existing connection?",
                                 new Object[]{rf.getDescriptor().getLabel()})) != JOptionPane.OK_OPTION)
                         {
                             return;
                         }
                         else
                         {
                             index = i;
                             break;
                         }
                     }
                 }

                 it.businesslogic.ireport.connection.JDBCConnection jdbcConnection = new it.businesslogic.ireport.connection.JDBCConnection();
                 jdbcConnection.setName(rf.getDescriptor().getLabel() );
                 jdbcConnection.setUrl( rf.getDescriptor().getConnectionUrl() );
                 jdbcConnection.setJDBCDriver( rf.getDescriptor().getDriverClass() );
                 jdbcConnection.setUsername( rf.getDescriptor().getUsername() );
                 jdbcConnection.setPassword( rf.getDescriptor().getPassword() );

                 if (index >= 0)
                 {
                     MainFrame.getMainInstance().getConnections().setElementAt(jdbcConnection, index);
                 }
                 else
                 {
                    MainFrame.getMainInstance().getConnections().add(jdbcConnection);
                 }
                 MainFrame.getMainInstance().setActiveConnection( jdbcConnection );
             }
         }
        
    }//GEN-LAST:event_jMenuItemConnectionActionPerformed

    private void jMenuItemReportUnitActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemReportUnitActionPerformed
            jButtonPublishReportActionPerformed1(evt);
    }//GEN-LAST:event_jMenuItemReportUnitActionPerformed

    private void jMenuItemDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemDeleteActionPerformed

        //1. Check if the selected element is a jrxml...
         TreePath path = jTreeRepository.getSelectionPath();
         if (path == null) return;
         DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
        
         if ( selectedNode.getUserObject() instanceof RepositoryFolder )
         {
             RepositoryFolder rf = (RepositoryFolder)selectedNode.getUserObject();
             
             String reportUnitUri = null;
                     
             String msg = IRPlugin.getFormattedString("repositoryExplorer.message.confirmDeleteFolder", "Are you sure you want to remove the folder {0}\n and all its contents?", new Object[] {rf.getDescriptor().getLabel()});
             
             // Check if we are inside a report unit...
            RepositoryReportUnit reportUnit = null;
            for (int i=path.getPathCount()-2; i>0; --i)
            {
                DefaultMutableTreeNode ancestorNode = (DefaultMutableTreeNode)path.getPath()[i];
                if (ancestorNode.getUserObject() instanceof RepositoryReportUnit)
                {
                    reportUnit = (RepositoryReportUnit)ancestorNode.getUserObject();
                    break;
                }
            }
                    
            if (reportUnit != null)
            {
                reportUnitUri = reportUnit.getDescriptor().getUriString();
            }
             
             
             if (rf.getDescriptor().getWsType().equals(ResourceDescriptor.TYPE_FOLDER))
             {
                msg = IRPlugin.getFormattedString("repositoryExplorer.message.confirmDeleteFolder", "Are you sure you want to remove the folder {0}\n and all its contents?", new Object[] {rf.getDescriptor().getLabel()});
             }
             else if (rf.getDescriptor().getWsType().equals(ResourceDescriptor.TYPE_REPORTUNIT))
             {
                msg = IRPlugin.getFormattedString("repositoryExplorer.message.confirmDeleteReportUnit", "Are you sure you want to remove the report unit {0}\n and all its contents?", new Object[] {rf.getDescriptor().getLabel()});
             }
            
            System.out.println( rf.getDescriptor().getWsType() );
             if ( isDataSource(  rf.getDescriptor() ) )
             {
                if ( ((DefaultMutableTreeNode)selectedNode.getParent()).getUserObject() instanceof ResourcesSet)
                {
                    JOptionPane.showMessageDialog(MainFrame.getMainInstance(),
                            IRPlugin.getString("repositoryExplorer.message.cannotDeleteRUDatasource",                            
                            "You can not delete the report datasource.\nUse Report Unit properties menu item to modify the datasource type."),
                            "",JOptionPane.ERROR_MESSAGE);
                    return;
                }
             }
             else
             {
                  msg = IRPlugin.getFormattedString("repositoryExplorer.message.confirmDeleteResource", "Are you sure you want to remove the resource {0} ?", new Object[] {rf.getDescriptor().getLabel()});
             }
             
             if (JOptionPane.showConfirmDialog(this,msg) == JOptionPane.YES_OPTION)
             {
                 try {
                        
                        rf.getServer().getWSClient().delete(rf.getDescriptor(), reportUnitUri); 
                    
                        DefaultMutableTreeNode parent = (DefaultMutableTreeNode)selectedNode.getParent();
                        if (parent != null)
                        {
                            parent.remove(selectedNode);
                            jTreeRepository.updateUI();
                        }
                        
                } catch (Exception ex)
                {
                    String errorMessage = ex.getMessage();
                    if (errorMessage == null) errorMessage = "No reason reported.";
                    if (errorMessage.length() > 120)
                    {
                        String emsg = "";
                        while (errorMessage.length() > 120)
                        {
                            if (emsg.length() > 0)
                            {
                                emsg += "\n";
                            }
                            emsg += errorMessage.substring(0, 120);
                            errorMessage = errorMessage.substring(120);
                            if (errorMessage.length() <= 120)
                            {
                                emsg += "\n" + errorMessage;
                                break;
                            }
                        }
                        
                        System.out.println("Message: " + emsg);
                        errorMessage = emsg;
                    }
                    JOptionPane.showMessageDialog(getPlugin().getMainFrame(),IRPlugin.getFormattedString("messages.error.3", "Error:\n {0}", new Object[] {errorMessage}));
                    ex.printStackTrace();
                }
             }
         }
    }//GEN-LAST:event_jMenuItemDeleteActionPerformed

    private void jMenuItemFontActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemFontActionPerformed
        newResource(ResourceDescriptor.TYPE_FONT);
    }//GEN-LAST:event_jMenuItemFontActionPerformed

    private void jMenuItemJarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemJarActionPerformed
        newResource(ResourceDescriptor.TYPE_CLASS_JAR);
    }//GEN-LAST:event_jMenuItemJarActionPerformed

    private void jMenuItemJrxmlActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemJrxmlActionPerformed
        newResource(ResourceDescriptor.TYPE_JRXML);
    }//GEN-LAST:event_jMenuItemJrxmlActionPerformed

    private void jMenuItemBundleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemBundleActionPerformed
        newResource(ResourceDescriptor.TYPE_RESOURCE_BUNDLE);
    }//GEN-LAST:event_jMenuItemBundleActionPerformed

    private void jMenuItemImageActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemImageActionPerformed
        newResource(ResourceDescriptor.TYPE_IMAGE);
    }//GEN-LAST:event_jMenuItemImageActionPerformed

    private void jMenuItemFolderActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemFolderActionPerformed

        newResource(ResourceDescriptor.TYPE_FOLDER);
        
    }//GEN-LAST:event_jMenuItemFolderActionPerformed

    private void jButtonPublishReportActionPerformed1(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonPublishReportActionPerformed1

        //1. Check if the selected element is a jrxml...
         TreePath path = jTreeRepository.getSelectionPath();
         if (path == null) return;
         DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
        
         String parentFolder = "/";
         JServer server = null;
         if ( selectedNode.getUserObject() instanceof JServer )
         {
             server = (JServer)selectedNode.getUserObject();
         }
         else if ( selectedNode.getUserObject() instanceof RepositoryFolder )
         {
             RepositoryFolder rf = (RepositoryFolder)selectedNode.getUserObject();
             parentFolder = rf.getDescriptor().getUriString();
             server = rf.getServer();
         }
         
         
         
         
         List datasources = null;
         
         if (IRPlugin.getMainInstance().getBrandingProperties().getProperty("ireport.manage.datasources.enabled", "true").equals("true"))
         {
             try {
                   datasources = server.getWSClient().listDatasources(); 
             } catch (Exception ex)
             {
                JOptionPane.showMessageDialog(getPlugin().getMainFrame(),
                        IRPlugin.getFormattedString("repositoryExplorer.message.errorListingDatasources", "Error getting the list of available datasources:\n{0}", new Object[] {ex.getMessage()}));
                ex.printStackTrace();
                return;
             }
             
             if (datasources == null || datasources.size() == 0)
             {
                 JOptionPane.showMessageDialog(getPlugin().getMainFrame(),
                         IRPlugin.getString("repositoryExplorer.message.noDatasourceFound",
                         "No datasources was found on the server.\nPlease create a new datasource on the server before create a report unit.")) ;
                 return;
             }
         }
         else
         {
             datasources = new java.util.ArrayList();
         }
         
         NewReportUnitWizard sr = new NewReportUnitWizard();
         sr.setParentFolder(parentFolder);
         sr.setDatasources(datasources);
         sr.setServer(server);
         sr.startWizard();
         
         ResourceDescriptor rd = sr.getNewResourceDescriptor();
         if (rd != null)
         {
             addChild(selectedNode, server, rd);
             jTreeRepository.updateUI();
         }
         
         /*
         ReportUnitDialog nrud = new ReportUnitDialog(MainFrame.getMainInstance(), true);
         nrud.setParentFolder(parentFolder);
         nrud.setDatasources(datasources);
         nrud.setServer(server);
         nrud.setVisible(true);
         
         if (nrud.getDialogResult() == JOptionPane.OK_OPTION)
         {
             addChild(selectedNode, server, nrud.getNewResourceDescriptor());
             jTreeRepository.updateUI();
         }
         */
         
    }//GEN-LAST:event_jButtonPublishReportActionPerformed1

    private void jButtonSaveJrxmlActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSaveJrxmlActionPerformed

        //1. Check if the selected element is a jrxml...
         TreePath path = jTreeRepository.getSelectionPath();
         if (path == null) return;
         DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
        
         if ( selectedNode.getUserObject() instanceof RepositoryJrxmlFile )
         {
            RepositoryJrxmlFile rf = (RepositoryJrxmlFile)selectedNode.getUserObject();
            
            if (rf.getReportFrame() != null)
            {
                if (MainFrame.getMainInstance().getActiveReportFrame() != rf.getReportFrame())
                {
                    MainFrame.getMainInstance().setActiveReportForm(rf.getReportFrame());
                }
                
                MainFrame.getMainInstance().jMenuItemSaveActionPerformed(new java.awt.event.ActionEvent(this,0,"Save"));
                
                String fileToUpdate = rf.getReportFrame().getReport().getFilename();
                try {
                    
                    // Check if we are inside a report unit...
                    RepositoryReportUnit reportUnit = null;
                    for (int i=path.getPathCount()-1; i>0; --i)
                    {
                        DefaultMutableTreeNode ancestorNode = (DefaultMutableTreeNode)path.getPath()[i];
                        if (ancestorNode.getUserObject() instanceof RepositoryReportUnit)
                        {
                            reportUnit = (RepositoryReportUnit)ancestorNode.getUserObject();
                            break;
                        }
                    }
                    
                    if (reportUnit != null)
                    {
                        if (rf.validateUrls(reportUnit.getServer(), reportUnit))
                        {
                            rf.getServer().getWSClient().modifyReportUnitResource(reportUnit.getDescriptor().getUriString(), rf.getDescriptor(), new File(fileToUpdate) ); 
                        }
                        else
                        {
                            JOptionPane.showMessageDialog(getPlugin().getMainFrame(),
                                    IRPlugin.getString("repositoryExplorer.message.operationCanceledByUser", "Operation canceled by the user"),
                                    IRPlugin.getString("repositoryExplorer.message.operationResult", "Operation result"), JOptionPane.WARNING_MESSAGE);
                            return;
                        }
                    }
                    else
                    {
                        rf.getServer().getWSClient().modifyReportUnitResource( null, rf.getDescriptor(), new File(fileToUpdate) ); 
                    }
                    JOptionPane.showMessageDialog(getPlugin().getMainFrame(),
                            IRPlugin.getString("repositoryExplorer.message.jrxmlUpdated", "Jrxml file succesfully updated."),
                            IRPlugin.getString("repositoryExplorer.message.operationResult", "Operation result"), JOptionPane.INFORMATION_MESSAGE);
                } catch (Exception ex)
                {
                    JOptionPane.showMessageDialog(getPlugin().getMainFrame(),IRPlugin.getFormattedString("messages.error.3", "Error:\n {0}", new Object[] {ex.getMessage()}),"Operation result", JOptionPane.ERROR_MESSAGE);
                    ex.printStackTrace();
                }
                
            }
         
         
         } 
        
    }//GEN-LAST:event_jButtonSaveJrxmlActionPerformed

    private void jTreeRepositoryValueChanged(javax.swing.event.TreeSelectionEvent evt) {//GEN-FIRST:event_jTreeRepositoryValueChanged
        updateToolBar();
    }//GEN-LAST:event_jTreeRepositoryValueChanged

    private void jMenuItemEditJRXMLActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemEditJRXMLActionPerformed

        TreePath path = jTreeRepository.getSelectionPath();
        if (path == null) return;
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
        
        if ( selectedNode.getUserObject() instanceof RepositoryJrxmlFile )
        {
            RepositoryJrxmlFile rf = (RepositoryJrxmlFile)selectedNode.getUserObject();
            
            try {
               rf.editFile();
               jButtonSaveJrxml.setEnabled(true);
            } catch (Exception ex)
            {
                JOptionPane.showMessageDialog(getPlugin().getMainFrame(),IRPlugin.getFormattedString("messages.error.3", "Error:\n {0}", new Object[] {ex.getMessage()}));
                ex.printStackTrace();
            }
        }
        
    }//GEN-LAST:event_jMenuItemEditJRXMLActionPerformed

    private void jMenuItemGetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemGetActionPerformed

        TreePath path = jTreeRepository.getSelectionPath();
        if (path == null) return;
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
        
        if ( selectedNode.getUserObject() instanceof RepositoryFile )
        {
            RepositoryFile rf = (RepositoryFile)selectedNode.getUserObject();
            JFileChooser jfc = new JFileChooser();          
            jfc.setSelectedFile(new File( rf.getDescriptor().getName()));
	    
            if (jfc.showSaveDialog(this) == JFileChooser.APPROVE_OPTION)
            {
                try {
                    rf.getServer().getWSClient().get( rf.getDescriptor(), jfc.getSelectedFile() ); 
                } catch (Exception ex)
                {
                    JOptionPane.showMessageDialog(getPlugin().getMainFrame(),IRPlugin.getFormattedString("messages.error.3", "Error:\n {0}", new Object[] {ex.getMessage()}));
                    ex.printStackTrace();
                }
            }
        }
    }//GEN-LAST:event_jMenuItemGetActionPerformed

    public void refreshContentNode(DefaultMutableTreeNode selectedNode)
    {
        if (selectedNode == null) return;
        TreePath path = new TreePath( selectedNode.getPath() );
        boolean isLoaded = false;
        String uri = "/";
        
        Object obj = selectedNode.getUserObject();
        if (obj == null) return;
        
        JServer server = null;
        if (obj instanceof JServer)
        {
            server = (JServer)obj;
            isLoaded = server.isLoaded();
        }
        else if ( obj instanceof RepositoryFolder)
        {
            RepositoryFolder rf = (RepositoryFolder)obj;
            isLoaded = rf.isLoaded();
            uri = rf.getDescriptor().getUriString();
            server = rf.getServer();
        }
        
        if (!isLoaded)
        {
            selectedNode.removeAllChildren();
            jMenuItemExploreActionPerformed(null);
        }
        else
        {
            try {
                // Check child by child...
                ResourceDescriptor descriptor = new ResourceDescriptor();
                descriptor.setWsType( descriptor.TYPE_FOLDER);
                descriptor.setUriString(uri);

                if ( selectedNode.getUserObject() instanceof RepositoryReportUnit)
                {
                    descriptor.setWsType( descriptor.TYPE_REPORTUNIT );
                }
                
                List list = server.getWSClient().list( descriptor);

                //addChilds(selectedNode, server, list);
                    
                if (descriptor.getWsType().equals( descriptor.TYPE_REPORTUNIT ))
                {
                    updateReportUnitNodeContent(selectedNode, list);
                }
                else
                {
                    List updatedNodes = new java.util.ArrayList();
                    for (int i=0; i<list.size(); ++i)
                    {
                        ResourceDescriptor rd = (ResourceDescriptor)list.get(i);

                        // Look for this rd in the node children
                        boolean found = false;
                        for (int j=0; j<selectedNode.getChildCount(); ++j)
                        {
                            RepositoryFolder rf = (RepositoryFolder)((DefaultMutableTreeNode)selectedNode.getChildAt(j)).getUserObject();
                            if (rf.getDescriptor().getUriString().equals(rd.getUriString()))
                            {
                                rf.setDescriptor(rd);
                                updatedNodes.add(selectedNode.getChildAt(j));
                                found = true;
                                break;
                            }
                        }

                        if (!found)
                        {
                            DefaultMutableTreeNode newNode = addChild(selectedNode, server, rd);
                            updatedNodes.add( newNode );
                        }
                    }
                    

                    // Remove children that no longer exist
                    for (int j=0; j<selectedNode.getChildCount(); ++j)
                    {
                        if (!updatedNodes.contains(selectedNode.getChildAt(j)))
                        {
                            selectedNode.remove(j);
                            j--;
                        }
                    }
                }
                
                if (list.size() > 0)
                {
                    if (!jTreeRepository.isExpanded(path))
                    {
                        jTreeRepository.expandPath(path);
                    }
                }
                jTreeRepository.updateUI();
                
            } catch (Exception ex)
                {
                    JOptionPane.showMessageDialog(getPlugin().getMainFrame(),IRPlugin.getFormattedString("messages.error.3", "Error:\n {0}", new Object[] {ex.getMessage()}));
                    ex.printStackTrace();
                }
            
        }
        
    }
    
    public void refreshContentNodeObject(Object obj)
    {
        // Find the node that holds a particular object...
        refreshContentNode( Misc.findNodeWithUserObject(obj, (DefaultMutableTreeNode)jTreeRepository.getModel().getRoot()) );
        
    }
    
    private void jMenuItemRefreshContentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemRefreshContentActionPerformed
        
        TreePath path = jTreeRepository.getSelectionPath();
        if (path == null) return;
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
        
        refreshContentNode(selectedNode);
        
    }//GEN-LAST:event_jMenuItemRefreshContentActionPerformed

    private void jMenuItemRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemRefreshActionPerformed

        TreePath path = jTreeRepository.getSelectionPath();
        if (path == null) return;
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
       
        if ( selectedNode.getUserObject() instanceof JServer)
        {
            return;
        }
        else if ( selectedNode.getUserObject() instanceof RepositoryFolder)
        {
            SwingUtilities.invokeLater(new Runnable() {
            public void run() {

                try {
                    Thread.currentThread().setContextClassLoader( MainFrame.getMainInstance().getReportClassLoader());
                    jTreeRepository.setCursor( new Cursor(Cursor.WAIT_CURSOR) );

                    TreePath path = jTreeRepository.getSelectionPath();
                    DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
                    
                    
        
                    if ( selectedNode.getUserObject() instanceof RepositoryFolder)
                    {
                        RepositoryFolder rf = (RepositoryFolder)selectedNode.getUserObject();
                        JServer server = rf.getServer();
                        WSClient wsclient = server.getWSClient();
                        ResourceDescriptor rd = wsclient.get(rf.getDescriptor(), null );
                        rf.setDescriptor(rd);
                        jTreeRepository.updateUI();
                    }
                    
                } catch (Exception ex)
                {
                    JOptionPane.showMessageDialog(getPlugin().getMainFrame(),IRPlugin.getFormattedString("messages.error.3", "Error:\n {0}", new Object[] {ex.getMessage()}));
                    ex.printStackTrace();
                }
                finally
                {
                    jTreeRepository.setCursor(null);
                }
            }
        }); 
        }
        
        
    }//GEN-LAST:event_jMenuItemRefreshActionPerformed

    private void jMenuItemPropertiesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemPropertiesActionPerformed

        TreePath path = jTreeRepository.getSelectionPath();
        if (path == null) return;
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
       
        if ( selectedNode.getUserObject() instanceof JServer)
        {
            jMenuItemServerSettingsActionPerformed(evt);    
        }
        else if (selectedNode.getUserObject() instanceof RepositoryReportUnit)
        {
            RepositoryReportUnit rf = (RepositoryReportUnit)selectedNode.getUserObject();
            ReportUnitDialog rrd = new ReportUnitDialog(MainFrame.getMainInstance(), true);
            rrd.setParentFolder( rf.getDescriptor().getParentFolder() );
            rrd.setServer(rf.getServer());
            
            rrd.setControlsSupportActive(false);
            rrd.setResourcesSupportActive(false);
            
            List datasources = null;
            if (IRPlugin.getMainInstance().getBrandingProperties().getProperty("ireport.manage.datasources.enabled", "true").equals("true"))
            {
                try {
                       datasources = rf.getServer().getWSClient().listDatasources(); 
                       rrd.setDatasources(datasources);
                } catch (Exception ex)
                {

                   JOptionPane.showMessageDialog(getPlugin().getMainFrame(),
                           IRPlugin.getFormattedString("repositoryExplorer.message.errorListingDatasources", "Error getting the list of available datasources:\n{0}", new Object[] {ex.getMessage()}));
                   ex.printStackTrace();
                }
            }

            rrd.setResource(rf);
            rrd.setVisible( true );

            if (rrd.getDialogResult() == JOptionPane.OK_OPTION)
            {
                // Update the selected node...
                refreshContentNode(selectedNode);
                jTreeRepository.updateUI();
            }
        }
        else if ( selectedNode.getUserObject() instanceof RepositoryFolder)
        {
            RepositoryFolder rf = (RepositoryFolder)selectedNode.getUserObject();
            
            if (rf.getDescriptor().getWsType().equals( ResourceDescriptor.TYPE_DATASOURCE_JDBC) ||
                rf.getDescriptor().getWsType().equals( ResourceDescriptor.TYPE_DATASOURCE_JNDI) ||
                rf.getDescriptor().getWsType().equals( ResourceDescriptor.TYPE_DATASOURCE_BEAN))
            {
                DataSourceDialog dsd = new DataSourceDialog(MainFrame.getMainInstance(), true);
                dsd.setParentFolder( rf.getDescriptor().getParentFolder() );
                dsd.setServer(rf.getServer());
                dsd.setResource(rf);
                dsd.setVisible( true );

                if (dsd.getDialogResult() == JOptionPane.OK_OPTION)
                {
                    jTreeRepository.updateUI();
                }

            }
            else if (rf.getDescriptor().getWsType().equals( ResourceDescriptor.TYPE_OLAP_XMLA_CONNECTION))
            {
                XMLAConnectionDialog dsd = new XMLAConnectionDialog(MainFrame.getMainInstance(), true);
                dsd.setParentFolder( rf.getDescriptor().getParentFolder() );
                dsd.setServer(rf.getServer());
                dsd.setResource(rf);
                dsd.setVisible( true );

                if (dsd.getDialogResult() == JOptionPane.OK_OPTION)
                {
                    jTreeRepository.updateUI();
                }

            }
            else if (rf.getDescriptor().getWsType().equals( ResourceDescriptor.TYPE_REFERENCE))
            {
                ResourceReferenceDialog rrd = new ResourceReferenceDialog(MainFrame.getMainInstance(), true);
                rrd.setParentFolder( rf.getDescriptor().getParentFolder() );
                rrd.setServer(rf.getServer());
                rrd.setResource(rf);
                rrd.setVisible( true );

                if (rrd.getDialogResult() == JOptionPane.OK_OPTION)
                {
                    jTreeRepository.updateUI();
                }
            }
            else if (rf.getDescriptor().getWsType().equals( ResourceDescriptor.TYPE_DATA_TYPE))
            {
                DataTypeDialog rrd = new DataTypeDialog(MainFrame.getMainInstance(), true);
                rrd.setParentFolder( rf.getDescriptor().getParentFolder() );
                rrd.setServer(rf.getServer());
                rrd.setResource(rf);
                rrd.setVisible( true );

                if (rrd.getDialogResult() == JOptionPane.OK_OPTION)
                {
                    jTreeRepository.updateUI();
                }
            }
            else if (rf.getDescriptor().getWsType().equals( ResourceDescriptor.TYPE_LOV))
            {
                ListOfValuesDialog rrd = new ListOfValuesDialog(MainFrame.getMainInstance(), true);
                rrd.setParentFolder( rf.getDescriptor().getParentFolder() );
                rrd.setServer(rf.getServer());
                rrd.setResource(rf);
                rrd.setVisible( true );

                if (rrd.getDialogResult() == JOptionPane.OK_OPTION)
                {
                    jTreeRepository.updateUI();
                }
            }
            else if (rf.getDescriptor().getWsType().equals( ResourceDescriptor.TYPE_QUERY))
            {
                QueryDialog rrd = new QueryDialog(MainFrame.getMainInstance(), true);
                rrd.setParentFolder( rf.getDescriptor().getParentFolder());
                rrd.setServer(rf.getServer());
                
                List datasources = null;
                if (IRPlugin.getMainInstance().getBrandingProperties().getProperty("ireport.manage.datasources.enabled", "true").equals("true"))
                {
                    try {
                           datasources = rf.getServer().getWSClient().listDatasources(); 
                           rrd.setDatasources(datasources);
                    } catch (Exception ex)
                    {

                       JOptionPane.showMessageDialog(MainFrame.getMainInstance(),
                               IRPlugin.getFormattedString("repositoryExplorer.message.errorListingDatasources", "Error getting the list of available datasources:\n{0}", new Object[] {ex.getMessage()}));
                       ex.printStackTrace();
                    }
                }
                rrd.setResource(rf);
                rrd.setVisible( true );

                if (rrd.getDialogResult() == JOptionPane.OK_OPTION)
                {
                    jTreeRepository.updateUI();
                }
            }
            else if (rf.getDescriptor().getWsType().equals( ResourceDescriptor.TYPE_INPUT_CONTROL))
            {
                InputControlDialog rrd = new InputControlDialog(MainFrame.getMainInstance(), true);
                rrd.setParentFolder( rf.getDescriptor().getParentFolder() );
                rrd.setServer(rf.getServer());
                rrd.setResource(rf);
                rrd.setVisible( true );

                if (rrd.getDialogResult() == JOptionPane.OK_OPTION)
                {
                    jTreeRepository.updateUI();
                }
            }
            else if (rf.getDescriptor().getWsType().equals( "ReportOptionsResource"))
            {
                ReportOptionsDialog rrd = new ReportOptionsDialog(MainFrame.getMainInstance(), true);
                rrd.setParentFolder( rf.getDescriptor().getParentFolder() );
                rrd.setServer(rf.getServer());
                rrd.setResource(rf);
                rrd.setVisible( true );

                if (rrd.getDialogResult() == JOptionPane.OK_OPTION)
                {
                    jTreeRepository.updateUI();
                }
            }
            else
            {
               ObjectPropertiesDialog opd = new ObjectPropertiesDialog(MainFrame.getMainInstance(), true);
                opd.setResource( rf  );
                opd.setVisible( true );

                if (opd.getDialogResult() == JOptionPane.OK_OPTION)
                {
                    jTreeRepository.updateUI();
                }
            }
        }

    }//GEN-LAST:event_jMenuItemPropertiesActionPerformed

    private void jMenuItemLoginActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemLoginActionPerformed

        // Explore...
        TreePath path = jTreeRepository.getSelectionPath();
        if (path == null) return;
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
        JServer server = null;
        
        if ( selectedNode.getUserObject() instanceof JServer)
        {
            server = (JServer)selectedNode.getUserObject();               
        }
        else if ( selectedNode.getUserObject() instanceof RepositoryFolder)
        {
            server = ((RepositoryFolder)selectedNode.getUserObject()).getServer();
        }
            
        if (server == null) return;
        
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {

                try {
                    Thread.currentThread().setContextClassLoader( MainFrame.getMainInstance().getReportClassLoader());
                    jTreeRepository.setCursor( new Cursor(Cursor.WAIT_CURSOR) );

                    TreePath path = jTreeRepository.getSelectionPath();
                    DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
                    
                    JServer server = null;
        
                    if ( selectedNode.getUserObject() instanceof JServer)
                    {
                        server = (JServer)selectedNode.getUserObject();               
                    }
                    else if ( selectedNode.getUserObject() instanceof RepositoryFolder)
                    {
                        server = ((RepositoryFolder)selectedNode.getUserObject()).getServer();
                    }
                    
                    WSClient wsclient = server.getWSClient();

                    //wsclient.login(server.getUsername(), server.getPassword() );

                } catch (Exception ex)
                {
                    JOptionPane.showMessageDialog(getPlugin().getMainFrame(),IRPlugin.getFormattedString("messages.error.3", "Error:\n {0}", new Object[] {ex.getMessage()}));
                    ex.printStackTrace();
                }
                finally
                {
                    jTreeRepository.setCursor(null);
                }
            }
        }); 
    }//GEN-LAST:event_jMenuItemLoginActionPerformed

    int nFont = 0;
    
    private void exploreSelectedNode()
    {
        // Explore...
        final TreePath path = jTreeRepository.getSelectionPath();
        if (path == null) return;
        final DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
        
        if ( selectedNode.getUserObject() instanceof JServer)
        {
            final JServer server = (JServer)selectedNode.getUserObject();
            if (!server.isLoaded())
            {
                //SwingUtilities.invokeLater(new Runnable() {
                //    public void run() {

                        try {
                            
                            
                            //Thread.currentThread().setContextClassLoader( MainFrame.getMainInstance().getReportClassLoader());
                            setTreeEnabled(false);
                            
                            Runnable r = new Runnable()
                            {
                                public void run()
                                {
                                    server.setLoading(true);
                                    jTreeRepository.updateUI();
                                    jTreeRepository.setCursor( new Cursor(Cursor.WAIT_CURSOR) );
                                }
                            };
                            
                            if (SwingUtilities.isEventDispatchThread())
                            {
                                r.run();
                            }
                            else
                            {
                                try { 
                                    SwingUtilities.invokeLater(r);
                                } catch (Exception ex){}
                            }
                            //TreePath path = jTreeRepository.getSelectionPath();
                            //DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
                            //JServer server = (JServer)selectedNode.getUserObject();
  
                            System.out.println("Getting ws client...." + new java.util.Date());
                            System.out.flush();
                            WSClient wsclient = server.getWSClient();
                            
                            System.out.println("Getting version...." + new java.util.Date());
                            System.out.flush();
                            String v = wsclient.getVersion();
                            
                            if (v==null || v.compareTo( IRPlugin.REQUIRED_VERSION)<0)
                            {
                                showMessageFromWorker(
                                        IRPlugin.getFormattedString("repositoryExplorer.message.notSupportedServer", "Server not supported.\nMinimum version required: {0}\nFound version: {1}", new Object[] {IRPlugin.REQUIRED_VERSION, v}));
                                return;
                            }
                                
                            //wsclient.login(server.getUsername(), server.getPassword() );
                            
                            ResourceDescriptor descriptor = new ResourceDescriptor();
                            descriptor.setWsType( descriptor.TYPE_FOLDER);
                            descriptor.setUriString("/");
                            
                            
                            final List list = wsclient.list( descriptor);
                            
                            final javax.swing.JTree jTree = jTreeRepository;
                            r = new Runnable()
                            {
                                public void run()
                                {
                                    addChilds(selectedNode, server, list);
                                    if (list.size() > 0)
                                    {
                                        if (!jTree.isExpanded(path))
                                        {
                                            jTree.expandPath(path);
                                        }
                                        jTree.updateUI();
                                    }
                                    server.setLoaded(true);
                                }
                            };
                            
                            if (SwingUtilities.isEventDispatchThread())
                            {
                                r.run();
                            }
                            else
                            {
                                try { 
                                    SwingUtilities.invokeLater(r);
                                } catch (Exception ex){}
                            }
                            
                            
                        } catch (Exception ex)
                        {
                            showMessageFromWorker(IRPlugin.getFormattedString("messages.error.3", "Error:\n {0}", new Object[] {ex.getMessage()}));
                            ex.printStackTrace();
                        }
                        finally
                        {
                            Runnable r = new Runnable()
                            {
                                public void run()
                                {
                                    server.setLoading(false);
                                    jTreeRepository.updateUI();
                                    jTreeRepository.setCursor( null );
                                }
                            };
                            
                            if (SwingUtilities.isEventDispatchThread())
                            {
                                r.run();
                            }
                            else
                            {
                                try { 
                                    SwingUtilities.invokeLater(r);
                                } catch (Exception ex){}
                            }
                            setTreeEnabled(true);
                        }
              //      }
              //  });
            
            }
            
            
        }
        if ( selectedNode.getUserObject() instanceof RepositoryReportUnit)
        {
            RepositoryReportUnit reportUnit = (RepositoryReportUnit)selectedNode.getUserObject();
            if (!reportUnit.isLoaded())
            {
            
                SwingUtilities.invokeLater(new Runnable() {
                    public void run() {

                        try {
                            Thread.currentThread().setContextClassLoader( MainFrame.getMainInstance().getReportClassLoader());
                            jTreeRepository.setCursor( new Cursor(Cursor.WAIT_CURSOR) );
                            
                            TreePath path = jTreeRepository.getSelectionPath();
                            DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
                            RepositoryReportUnit reportUnit = (RepositoryReportUnit)selectedNode.getUserObject();
                            JServer server = reportUnit.getServer();

                            WSClient wsclient = server.getWSClient();
                            ResourceDescriptor descriptor = new ResourceDescriptor();
                            descriptor.setWsType( descriptor.TYPE_REPORTUNIT);
                            descriptor.setUriString(reportUnit.getDescriptor().getUriString());
                            Request req = new Request();
                            req.setOperationName( req.OPERATION_LIST);
                            req.setResourceDescriptor( descriptor);
                            
                            StringWriter xmlStringWriter = new StringWriter();
                            Marshaller.marshal(req, xmlStringWriter);
                            
                            List list = wsclient.list(xmlStringWriter.toString());

                            //1. Find the datasource
                            //2. Fing the main JRXML
                            //3. Add controls... (exploded)
                            //4. All reamining resources... (exploded)
                            updateReportUnitNodeContent(selectedNode, list);
                            
                            
                            //addChilds(selectedNode, server, list);
                            
                            if (list.size() > 0)
                            {
                                if (!jTreeRepository.isExpanded(path))
                                {
                                    jTreeRepository.expandPath(path);
                                }
                                jTreeRepository.updateUI();
                            }

                            reportUnit.setLoaded(true);
                        } catch (Exception ex)
                        {
                            JOptionPane.showMessageDialog(getPlugin().getMainFrame(),IRPlugin.getFormattedString("messages.error.3", "Error:\n {0}", new Object[] {ex.getMessage()}));
                            ex.printStackTrace();
                        }
                        finally
                        {
                            jTreeRepository.setCursor(null);
                        }
                    }
                });
            
            }
        }
        else if ( selectedNode.getUserObject() instanceof RepositoryFolder)
        {
            // Identify the server....
            RepositoryFolder folder = (RepositoryFolder)selectedNode.getUserObject();
            if (!folder.isLoaded())
            {
                 SwingUtilities.invokeLater(new Runnable() {
                    public void run() {

                        try {
                            Thread.currentThread().setContextClassLoader( MainFrame.getMainInstance().getReportClassLoader());
                            jTreeRepository.setCursor( new Cursor(Cursor.WAIT_CURSOR) );
                            
                            TreePath path = jTreeRepository.getSelectionPath();
                            DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
                            RepositoryFolder folder = (RepositoryFolder)selectedNode.getUserObject();
                            
                            JServer server = folder.getServer();
                            
                            WSClient wsclient = server.getWSClient();
                            ResourceDescriptor descriptor = new ResourceDescriptor();
                            descriptor.setWsType( descriptor.TYPE_FOLDER);
                            descriptor.setUriString(folder.getDescriptor().getUriString());
                            Request req = new Request();
                            req.setOperationName( req.OPERATION_LIST);
                            req.setResourceDescriptor( descriptor);
                            
                            StringWriter xmlStringWriter = new StringWriter();
                            Marshaller.marshal(req, xmlStringWriter);
                            
                            List list = wsclient.list(xmlStringWriter.toString());

                            addChilds(selectedNode, server, list);
                            
                            if (list.size() > 0)
                            {
                                if (!jTreeRepository.isExpanded(path))
                                {
                                    jTreeRepository.expandPath(path);
                                }
                                jTreeRepository.updateUI();
                            }

                            folder.setLoaded(true);
                        } catch (Exception ex)
                        {
                            JOptionPane.showMessageDialog(getPlugin().getMainFrame(),IRPlugin.getFormattedString("messages.error.3", "Error:\n {0}", new Object[] {ex.getMessage()}));
                            ex.printStackTrace();
                        }
                        finally
                        {
                            jTreeRepository.setCursor(null);
                        }
                    }
                });
            }
        }
    }
    
    private void jMenuItemExploreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemExploreActionPerformed

        if (!isTreeEnabled()) return;
        Runnable r = new Runnable(){
           
            public void run()
            {
                exploreSelectedNode();
            }
            
        };
        
        TreePath path = jTreeRepository.getSelectionPath();
        if (path == null) return;
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
        
        if ( selectedNode.getUserObject() instanceof JServer)
        {
            Thread t = new Thread(r);
            t.start();
        }
        else
        {
            r.run();
        }
        
        
    }//GEN-LAST:event_jMenuItemExploreActionPerformed

    private void jMenuItemNewServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemNewServerActionPerformed

        jButtonAddServerActionPerformed(null);
        
    }//GEN-LAST:event_jMenuItemNewServerActionPerformed

    private void jMenuItemServerDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemServerDeleteActionPerformed
        
        TreePath path = jTreeRepository.getSelectionPath();
        if (path == null) return;
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
        JServer server = null;
        
        if ( selectedNode.getUserObject() instanceof JServer)
        {
            server = (JServer)selectedNode.getUserObject();               
        }
        else if ( selectedNode.getUserObject() instanceof RepositoryFolder)
        {
            server = ((RepositoryFolder)selectedNode.getUserObject()).getServer();
        }
            
        if (server == null) return;
        
        if (JOptionPane.showConfirmDialog(getPlugin().getMainFrame(), 
                "Are you sure you want to delete the server '" + server + "' ?",
                "Deleting server",
                JOptionPane.YES_NO_CANCEL_OPTION,
                JOptionPane.WARNING_MESSAGE
                ) == JOptionPane.YES_OPTION)
        {
            getPlugin().getJServers().remove( selectedNode.getUserObject() );
            getPlugin().saveConfiguration();
            ((DefaultMutableTreeNode)jTreeRepository.getModel().getRoot()).remove( selectedNode );
            jTreeRepository.updateUI();
            //jButtonNewReportUnit.setEnabled(this.getPlugin().getJServers().size() > 0); 
        }        
        
    }//GEN-LAST:event_jMenuItemServerDeleteActionPerformed

    private void jMenuItemServerSettingsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItemServerSettingsActionPerformed

        TreePath path = jTreeRepository.getSelectionPath();
        if (path == null) return;
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
        JServer server = null;
        
        if ( selectedNode.getUserObject() instanceof JServer)
        {
            server = (JServer)selectedNode.getUserObject();               
        }
        else if ( selectedNode.getUserObject() instanceof RepositoryFolder)
        {
            server = ((RepositoryFolder)selectedNode.getUserObject()).getServer();
        }
            
        if (server == null) return;
        
        ServerDialog sd = new ServerDialog(getPlugin().getMainFrame(), true);
        sd.setJServer( server );
        sd.setVisible(true);
        if (sd.getDialogResult() == JOptionPane.OK_OPTION)
        {
            server.setName( sd.getJServer().getName());
            server.setUsername( sd.getJServer().getUsername() );
            server.setPassword( sd.getJServer().getPassword() );
            server.setUrl( sd.getJServer().getUrl() );

            getPlugin().saveConfiguration();
            jTreeRepository.updateUI();
        }
        
    }//GEN-LAST:event_jMenuItemServerSettingsActionPerformed

    private void jTreeRepositoryMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTreeRepositoryMouseClicked

        if (!isTreeEnabled()) return;
        if (evt.getClickCount() == 2 && evt.getButton() == evt.BUTTON1)
        {
            //TreePath path = jTreeRepository.getPathForLocation(evt.getX(), evt.getY() );
            //if (path == null) return;
            //jTreeRepository.setSelectionPath( path );
            TreePath path = jTreeRepository.getSelectionPath();
            DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
            
            if ( selectedNode.getUserObject() instanceof JServer)
            {
                jMenuItemExploreActionPerformed(null);        
            } 
            else if ( selectedNode.getUserObject() instanceof RepositoryJrxmlFile)
            {
                jMenuItemEditJRXMLActionPerformed(null);
            }
            else if ( selectedNode.getUserObject() instanceof RepositoryFile)
            {
                jMenuItemPropertiesActionPerformed(null);
            }
            else if ( selectedNode.getUserObject() instanceof RepositoryFolder)
            {
                jMenuItemExploreActionPerformed(null);
            }
        }
        
    }//GEN-LAST:event_jTreeRepositoryMouseClicked

    private void jPopupMenuServerMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jPopupMenuServerMouseClicked

        
        
    }//GEN-LAST:event_jPopupMenuServerMouseClicked

    private void jButtonAddServerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAddServerActionPerformed

        ServerDialog sd = new ServerDialog(getPlugin().getMainFrame(), true);
        sd.setVisible(true);
        if (sd.getDialogResult() == JOptionPane.OK_OPTION)
        {
            IRPlugin.getMainInstance().getJServers().add(sd.getJServer());
            IRPlugin.getMainInstance().saveConfiguration();
            ((DefaultMutableTreeNode)this.jTreeRepository.getModel().getRoot()).add(new DefaultMutableTreeNode(sd.getJServer()));
            this.jTreeRepository.updateUI();
        }
        
    }//GEN-LAST:event_jButtonAddServerActionPerformed

    private void jTreeRepositoryMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTreeRepositoryMousePressed
        if (!isTreeEnabled()) return;
        if (evt.getClickCount() == 1 && evt.getButton() == evt.BUTTON3)
        {
            jTreeRepository.setSelectionPath( jTreeRepository.getPathForLocation(evt.getX(), evt.getY() ) );
        }
    }//GEN-LAST:event_jTreeRepositoryMousePressed

    private void jTreeRepositoryMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTreeRepositoryMouseReleased
        
        if (evt.getClickCount() == 1 && evt.getButton() == evt.BUTTON3)
        {
            TreePath path = jTreeRepository.getSelectionPath();
            
            if (!IRPlugin.getMainInstance().getBrandingProperties().getProperty("ireport.manage.datasources.enabled", "true").equals("true"))
            {
                jMenuItemDatasource.setVisible(false);
                jMenuItemXMLADatasource.setVisible(false);
                jSeparator7.setVisible(false);
            }
            
            
            if (path == null)
            {
                jMenuItemEditJRXML.setVisible(false);
                jMenuItemExplore.setVisible(false);
                jMenuItemGet.setVisible(false); 
                jMenuItemServerDelete.setEnabled(false);
                jMenuItemServerSettings.setEnabled(false);
                jMenuItemProperties.setEnabled(false);
                jMenuItemRefresh.setVisible(false);
                jMenuItemRefreshContent.setVisible(false);
                jMenuAdd.setVisible(false);
                jMenuItemConnection.setVisible(false);
                jMenuItemImportFont.setVisible(false);
                jMenuItemRunRU.setVisible(false);
                
                jPopupMenuServer.show(jTreeRepository,evt.getX(), evt.getY());
                return;
            }

            jMenuItemServerDelete.setEnabled(true);
            jMenuItemServerSettings.setEnabled(true);
            jMenuItemProperties.setEnabled(true);
            jMenuItemRefresh.setVisible(true);
            jMenuItemRefreshContent.setVisible(true);
            jMenuItemFolder.setEnabled(true);
            jMenuItemReportUnit.setEnabled(true);
            jMenuAdd.setVisible(true);
            jMenuItemConnection.setVisible(false);
            jMenuItemImportFont.setVisible(false);
            jMenuItemReference.setEnabled(false);
            jMenuItemDataType.setEnabled(true);
            jMenuItemListOfValues.setEnabled(true);
            jMenuItemRunRU.setVisible(false);
                
            DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
            
            
            if ( selectedNode.getUserObject() instanceof JServer)
            {
                jMenuItemEditJRXML.setVisible(false);
                jMenuItemExplore.setVisible(true);
                jMenuItemGet.setVisible(false);        
                jMenuAdd.setEnabled(true);
                jMenuItemDelete.setVisible(false);
            }
            else if ( selectedNode.getUserObject() instanceof RepositoryJrxmlFile)
            {
                jMenuItemEditJRXML.setVisible(true);
                jMenuItemExplore.setVisible(false);
                jMenuItemGet.setVisible(false);
                jMenuAdd.setEnabled(false);
                jMenuItemDelete.setVisible(true);
            }
            else if ( selectedNode.getUserObject() instanceof RepositoryFile)
            {
                jMenuItemEditJRXML.setVisible(false);
                jMenuItemExplore.setVisible(false);
                jMenuItemGet.setVisible(false);
                jMenuAdd.setEnabled(false);
                jMenuItemDelete.setVisible(true);

                String resType = ((RepositoryFile)selectedNode.getUserObject()).getDescriptor().getWsType();
                
                if (resType.equals( ResourceDescriptor.TYPE_DATASOURCE_JDBC) )
                {
                    jMenuItemConnection.setVisible(true);
                    
                }
                else if (resType.equals( ResourceDescriptor.TYPE_CLASS_JAR) ||
                         resType.equals( ResourceDescriptor.TYPE_FONT) ||
                         resType.equals( ResourceDescriptor.TYPE_IMAGE) ||
                         resType.equals( ResourceDescriptor.TYPE_JRXML) ||
                         resType.equals( ResourceDescriptor.TYPE_RESOURCE_BUNDLE))
                {
                    jMenuItemGet.setVisible(true);
                }
                
                if (resType.equals( ResourceDescriptor.TYPE_FONT) )
                {
                    jMenuItemImportFont.setVisible(true);
                }
                
                if (((RepositoryFolder)selectedNode.getUserObject()).getDescriptor().getWsType().equals("ReportOptionsResource"))
                {
                    jMenuItemRunRU.setVisible(true);
                }
            }
            else if ( selectedNode.getUserObject() instanceof RepositoryFolder)
            {
                jMenuItemEditJRXML.setVisible(false);
                jMenuItemExplore.setVisible(true);
                jMenuItemGet.setVisible(false);
                jMenuAdd.setEnabled(true);
           	jMenuItemDatasource.setEnabled(true);
                jMenuItemXMLADatasource.setEnabled(true);
                jMenuItemDelete.setVisible(true);
           	
                if ( selectedNode.getUserObject() instanceof RepositoryReportUnit)
                {
                    jMenuItemFolder.setEnabled(false);
                    jMenuItemReference.setEnabled(true);
                    jMenuItemReportUnit.setEnabled(false);
                    jMenuItemDataType.setEnabled(false);
                    jMenuItemListOfValues.setEnabled(false);
                    jMenuItemRunRU.setVisible(true);
                    jMenuItemDatasource.setEnabled(false);
                    jMenuItemXMLADatasource.setEnabled(false);
                }
                
                
            }
            else if ( selectedNode.getUserObject() instanceof ControlsSet)
            {
                jPopupMenuRUInputControls.show(jTreeRepository,evt.getX(), evt.getY());
                return;
            }
            else if ( selectedNode.getUserObject() instanceof ResourcesSet)
            {
                jMenuItemEditJRXML.setVisible(false);
                jMenuItemExplore.setVisible(false);
                jMenuItemGet.setVisible(false);
                jMenuAdd.setEnabled(true);
                jMenuItemFolder.setEnabled(false);
                jMenuItemReference.setEnabled(true);
                jMenuItemReportUnit.setEnabled(false);
                jMenuItemDataType.setEnabled(false);
                jMenuItemListOfValues.setEnabled(false);
                jMenuItemDatasource.setEnabled(false);
                jMenuItemXMLADatasource.setEnabled(false);
                jMenuItemDelete.setVisible(false);
            }
            
            jMenuItemExplore.setEnabled(true);
            jMenuItemServerDelete.setEnabled(true);
            jMenuItemServerSettings.setEnabled(true);
            jPopupMenuServer.show(jTreeRepository,evt.getX(), evt.getY());
            return;
        }
    }//GEN-LAST:event_jTreeRepositoryMouseReleased
    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAddServer;
    private javax.swing.JButton jButtonNewReportUnit;
    private javax.swing.JButton jButtonRunReport;
    private javax.swing.JButton jButtonSaveJrxml;
    private javax.swing.JMenu jMenuAdd;
    private javax.swing.JMenuItem jMenuItemBundle;
    private javax.swing.JMenuItem jMenuItemConnection;
    private javax.swing.JMenuItem jMenuItemDataType;
    private javax.swing.JMenuItem jMenuItemDatasource;
    private javax.swing.JMenuItem jMenuItemDelete;
    private javax.swing.JMenuItem jMenuItemEditJRXML;
    private javax.swing.JMenuItem jMenuItemExplore;
    private javax.swing.JMenuItem jMenuItemFolder;
    private javax.swing.JMenuItem jMenuItemFont;
    private javax.swing.JMenuItem jMenuItemGet;
    private javax.swing.JMenuItem jMenuItemImage;
    private javax.swing.JMenuItem jMenuItemImportFont;
    private javax.swing.JMenuItem jMenuItemInputControl;
    private javax.swing.JMenuItem jMenuItemJar;
    private javax.swing.JMenuItem jMenuItemJrxml;
    private javax.swing.JMenuItem jMenuItemLinkInputControl;
    private javax.swing.JMenuItem jMenuItemListOfValues;
    private javax.swing.JMenuItem jMenuItemLocalInputControl;
    private javax.swing.JMenuItem jMenuItemLogin;
    private javax.swing.JMenuItem jMenuItemNewServer;
    private javax.swing.JMenuItem jMenuItemProperties;
    private javax.swing.JMenuItem jMenuItemQuery;
    private javax.swing.JMenuItem jMenuItemReference;
    private javax.swing.JMenuItem jMenuItemRefresh;
    private javax.swing.JMenuItem jMenuItemRefreshContent;
    private javax.swing.JMenuItem jMenuItemReportUnit;
    private javax.swing.JMenuItem jMenuItemRunRU;
    private javax.swing.JMenuItem jMenuItemServerDelete;
    private javax.swing.JMenuItem jMenuItemServerSettings;
    private javax.swing.JMenuItem jMenuItemXMLADatasource;
    private javax.swing.JPopupMenu jPopupMenuRUInputControls;
    private javax.swing.JPopupMenu jPopupMenuServer;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JSeparator jSeparator3;
    private javax.swing.JSeparator jSeparator4;
    private javax.swing.JSeparator jSeparator5;
    private javax.swing.JSeparator jSeparator6;
    private javax.swing.JSeparator jSeparator7;
    private javax.swing.JToolBar jToolBar1;
    private javax.swing.JTree jTreeRepository;
    // End of variables declaration//GEN-END:variables
    
    
    /**
     * This method populate all childs of a node instancing the right object for each descriptor
     *
     */
    private void addChilds(DefaultMutableTreeNode selectedNode, JServer server, List resourceDescriptors)
    {
        for (int i=0; i<resourceDescriptors.size(); ++i)
        {
            ResourceDescriptor rd = (ResourceDescriptor)resourceDescriptors.get(i);
            addChild(selectedNode, server, rd);    
        }
    }
    
    
    /**
     * This method populate all childs of a node instancing the right object for each descriptor
     *
     */
    private DefaultMutableTreeNode addChild(DefaultMutableTreeNode selectedNode, JServer server, ResourceDescriptor rd)
    {
            if (isDataSource(rd) && !IRPlugin.getMainInstance().getBrandingProperties().getProperty("ireport.manage.datasources.enabled", "true").equals("true"))
            {
                return null;
            }
            
            DefaultMutableTreeNode newNode = null;

            RepositoryFolder obj = createRepositoryObject(server, rd);
            if (obj != null) 
            {
                newNode = new DefaultMutableTreeNode(obj);
                selectedNode.add( newNode );
            } 
            return newNode;
    }
    
    
    /**
     * Return the best object to wrap this ResourceDescriptor like:
     * 
     *  RepositoryReportUnit
     *  RepositoryFolder
     *  RepositoryJrxmlFile
     *  RepositoryFile
     *
     *  The origilan resource descriptor is used inside the new object and
     *  COULD be modified.
     *  
     */
    public static RepositoryFolder createRepositoryObject(JServer server, ResourceDescriptor rd)
    {
        if (rd.getWsType() == null)
        {
            rd.setWsType(ResourceDescriptor.TYPE_UNKNOW);
        }
               
        if (rd.getWsType().equals( ResourceDescriptor.TYPE_REPORTUNIT)  )
        {
            return new RepositoryReportUnit(server, rd );
        }
        else if (rd.getWsType().equals( ResourceDescriptor.TYPE_FOLDER)  )
        {
            return new RepositoryFolder(server, rd );
        }
        else if (rd.getWsType().equals( ResourceDescriptor.TYPE_JRXML)  )
        {
            return new RepositoryJrxmlFile(server, rd );
        }
        else
        {
            return new RepositoryFile(server, rd );
        }
    }
    
    
    private void newResource(String resourceType)
    {
        TreePath path = jTreeRepository.getSelectionPath();
        if (path == null) return;
        DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
        
        //selectedNode.removeAllChildren();
        JServer server = null;
        
        String currentUri = "/";
        String reportUnitUri = null;
        
        boolean parentLoaded = false;
        if ( selectedNode.getUserObject() instanceof JServer)
        {
            server = (JServer)selectedNode.getUserObject();
            parentLoaded = server.isLoaded();
        }
        else if ( selectedNode.getUserObject() instanceof RepositoryReportUnit)
        {
            RepositoryFolder rf = (RepositoryFolder)selectedNode.getUserObject();
            server = rf.getServer();
            currentUri = rf.getDescriptor().getUriString();
            reportUnitUri = currentUri;
            parentLoaded = rf.isLoaded();
        }
        else if ( selectedNode.getUserObject() instanceof RepositoryFolder)
        {
            RepositoryFolder rf = (RepositoryFolder)selectedNode.getUserObject();
            server = rf.getServer();
            currentUri = rf.getDescriptor().getUriString();
            parentLoaded = rf.isLoaded();
        }
        else if ( selectedNode.getUserObject() instanceof ControlsSet)
        {
            RepositoryFolder rf = ((ControlsSet)selectedNode.getUserObject()).getReportUnit();
            server = rf.getServer();
            currentUri = rf.getDescriptor().getUriString();
            reportUnitUri = currentUri;
            parentLoaded = rf.isLoaded();
        }
        else if ( selectedNode.getUserObject() instanceof ResourcesSet)
        {
            RepositoryFolder rf = ((ResourcesSet)selectedNode.getUserObject()).getReportUnit();
            server = rf.getServer();
            currentUri = rf.getDescriptor().getUriString();
            reportUnitUri = currentUri;
            parentLoaded = rf.isLoaded();
        }
        
        if  (resourceType.equals(ResourceDescriptor.TYPE_DATASOURCE))
        {
            DataSourceDialog nrd = new DataSourceDialog(MainFrame.getMainInstance(), true);

            nrd.setParentFolder(currentUri);
            nrd.setServer(server);
            //nrd.setReportUnitUri(reportUnitUri);
            //nrd.setResourceType(resourceType);

            nrd.setVisible(true);

            if (nrd.getDialogResult() == JOptionPane.OK_OPTION)
            {
                if (parentLoaded)
                {
                    addChild((DefaultMutableTreeNode)selectedNode, server, nrd.getNewResourceDescriptor());
                    jTreeRepository.updateUI();
                }
                else
                {
                    jMenuItemExploreActionPerformed(null);
                }
            }
        }
        else if  (resourceType.equals(ResourceDescriptor.TYPE_OLAP_XMLA_CONNECTION))
        {
            XMLAConnectionDialog nrd = new XMLAConnectionDialog(MainFrame.getMainInstance(), true);

            nrd.setParentFolder(currentUri);
            nrd.setServer(server);
            //nrd.setReportUnitUri(reportUnitUri);
            //nrd.setResourceType(resourceType);

            nrd.setVisible(true);

            if (nrd.getDialogResult() == JOptionPane.OK_OPTION)
            {
                if (parentLoaded)
                {
                    addChild((DefaultMutableTreeNode)selectedNode, server, nrd.getNewResourceDescriptor());
                    jTreeRepository.updateUI();
                }
                else
                {
                    jMenuItemExploreActionPerformed(null);
                }
            }
        }
        else if (resourceType.equals(ResourceDescriptor.TYPE_REFERENCE))
        {
            ResourceReferenceDialog rrd = new ResourceReferenceDialog(MainFrame.getMainInstance(), true);
            rrd.setServer(server);
            rrd.setParentFolder(currentUri);
            //ResourceChooser rc = new ResourceChooser();
            //rc.setServer( server );
            //rc.showDialog(this, null);
            rrd.setVisible(true);
            
            if (rrd.getDialogResult() == JOptionPane.OK_OPTION)
            {
                if (parentLoaded)
                {
                    addChild((DefaultMutableTreeNode)selectedNode, server, rrd.getNewResourceDescriptor());
                    jTreeRepository.updateUI();
                }
                else
                {
                    jMenuItemExploreActionPerformed(null);
                }
            }
        }
        else if  (resourceType.equals(ResourceDescriptor.TYPE_DATA_TYPE))
        {
            DataTypeDialog nrd = new DataTypeDialog(MainFrame.getMainInstance(), true);

            nrd.setParentFolder(currentUri);
            nrd.setServer(server);

            nrd.setVisible(true);

            if (nrd.getDialogResult() == JOptionPane.OK_OPTION)
            {
                if (parentLoaded)
                {
                    addChild((DefaultMutableTreeNode)selectedNode, server, nrd.getNewResourceDescriptor());
                    jTreeRepository.updateUI();
                }
                else
                {
                    jMenuItemExploreActionPerformed(null);
                }
            }
        }
        else if  (resourceType.equals(ResourceDescriptor.TYPE_LOV))
        {
            ListOfValuesDialog nrd = new ListOfValuesDialog(MainFrame.getMainInstance(), true);

            nrd.setParentFolder(currentUri);
            nrd.setServer(server);

            nrd.setVisible(true);

            if (nrd.getDialogResult() == JOptionPane.OK_OPTION)
            {
                if (parentLoaded)
                {
                    addChild((DefaultMutableTreeNode)selectedNode, server, nrd.getNewResourceDescriptor());
                    jTreeRepository.updateUI();
                }
                else
                {
                    jMenuItemExploreActionPerformed(null);
                }
            }
        }
        else if  (resourceType.equals(ResourceDescriptor.TYPE_QUERY))
        {
            QueryDialog nrd = new QueryDialog(MainFrame.getMainInstance(), true);

            nrd.setParentFolder(currentUri);
            nrd.setServer(server);

            if (IRPlugin.getMainInstance().getBrandingProperties().getProperty("ireport.manage.datasources.enabled", "true").equals("true"))
            {
                List datasources = null;
                try {
                       datasources = server.getWSClient().listDatasources(); 
                       nrd.setDatasources(datasources);
                } catch (Exception ex)
                {

                   JOptionPane.showMessageDialog(MainFrame.getMainInstance(),
                           IRPlugin.getFormattedString("repositoryExplorer.message.errorListingDatasources", "Error getting the list of available datasources:\n{0}", new Object[] {ex.getMessage()}));
                   ex.printStackTrace();
                }
            }
            
            nrd.setVisible(true);
            
            if (nrd.getDialogResult() == JOptionPane.OK_OPTION)
            {
                if (parentLoaded)
                {
                    addChild((DefaultMutableTreeNode)selectedNode, server, nrd.getNewResourceDescriptor());
                    jTreeRepository.updateUI();
                }
                else
                {
                    jMenuItemExploreActionPerformed(null);
                }
            }
        }
        else if  (resourceType.equals(ResourceDescriptor.TYPE_INPUT_CONTROL))
        {
            InputControlDialog nrd = new InputControlDialog(MainFrame.getMainInstance(), true);

            nrd.setParentFolder(currentUri);
            nrd.setServer(server);
            nrd.setReportUnitUri(reportUnitUri);

            nrd.setVisible(true);

            if (nrd.getDialogResult() == JOptionPane.OK_OPTION)
            {
                if (parentLoaded)
                {
                    if (reportUnitUri != null)
                    {
                        if ( selectedNode.getUserObject() instanceof ControlsSet)
                        {
                            addChild((DefaultMutableTreeNode)selectedNode, server, nrd.getNewResourceDescriptor());
                        }
                        else if (selectedNode.getUserObject() instanceof RepositoryReportUnit)
                        {
                            for (int i=0; i< selectedNode.getChildCount(); ++i)
                            {
                                DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode)selectedNode.getChildAt(i);
                                if (dmtn.getUserObject() instanceof ControlsSet)
                                {
                                    addChild(dmtn, server, nrd.getNewResourceDescriptor());
                                    break;
                                }
                            }
                        }
                    }
                    else
                    {
                        addChild((DefaultMutableTreeNode)selectedNode, server, nrd.getNewResourceDescriptor());
                    }
                    jTreeRepository.updateUI();
                }
                else
                {
                    jMenuItemExploreActionPerformed(null);
                }
            }
        }
        else
        {
            NewResourceDialog nrd = new NewResourceDialog(MainFrame.getMainInstance(), true);

            nrd.setParentUri(currentUri);
            nrd.setServer(server);
            nrd.setReportUnitUri(reportUnitUri);
            nrd.setResourceType(resourceType);

            nrd.setVisible(true);

            if (nrd.getDialogResult() == JOptionPane.OK_OPTION)
            {
                if (parentLoaded)
                {
                    addChild((DefaultMutableTreeNode)selectedNode, server, nrd.getNewResourceDescriptor());
                    jTreeRepository.updateUI();
                }
                else
                {
                    jMenuItemExploreActionPerformed(null);
                }
            }
        
        }
    }
    
    /**
     * Return the tree component...
     */ 
    public JTree getTreeRepository()
    {
        return jTreeRepository;
    }
    
    /**
     * Return all report units with one or more documents opened in the main frame...
     */
    public List getOpenedReportSources(JServer server)
    {
        java.util.ArrayList list = new java.util.ArrayList();
        
        DefaultMutableTreeNode root = (DefaultMutableTreeNode)jTreeRepository.getModel().getRoot();
        
        for (int i=0; i<root.getChildCount(); ++i)
        {
            DefaultMutableTreeNode dmn = (DefaultMutableTreeNode)root.getChildAt(i);
            if (dmn.getUserObject() == server)
            {
                
                return getOpenedReportSources(dmn, list);
            }
        }
        return list;
    }
    
    private List getOpenedReportSources(DefaultMutableTreeNode dmn, List list)
    {
        if (dmn.getUserObject() instanceof RepositoryJrxmlFile)
        {
            RepositoryJrxmlFile rf = (RepositoryJrxmlFile)dmn.getUserObject();
            if (rf.getReportFrame() != null)
            {
                list.add(rf);
            }
            return list;
        }

        for (int i=0; i<dmn.getChildCount(); ++i)
        {
            list = getOpenedReportSources((DefaultMutableTreeNode)dmn.getChildAt(i), list);
        }
        
        return list;
    }
    
    
    /**
     * Update the special ReportUnit structure:
     *  
     *  ReportUnit
     *   +- DataSource
     *   +- Main JRXML
     *   +- Controls
     *       +-- ... controls
     *   +- Resources
     *       +-- ... resources
     *
     */
    private void updateReportUnitNodeContent(DefaultMutableTreeNode selectedNode, List list)
    {
        RepositoryReportUnit reportUnit = (RepositoryReportUnit)selectedNode.getUserObject();
        
        Vector existingNodes = new Vector();
        
        // Remove all existing nodes (except controls and resources nodes)
        for (int k=0; k < selectedNode.getChildCount(); ++k)
        {
            Object obj = ((DefaultMutableTreeNode)selectedNode.getChildAt(k)).getUserObject();
            if (obj instanceof RepositoryFolder)
            {
                existingNodes.add( obj );
                selectedNode.remove(k);
                k--;
            }
        }
        
        // 1. The first node is the datasource
        for (int i=0; i<list.size(); ++i)
        {
            ResourceDescriptor rd = (ResourceDescriptor)list.get(i);
            if ( isDataSource(rd))
            {
                list.remove(i);
                if (!rd.getIsReference())
                {
                    boolean found = false;
                    // Find rd in the vector....
                    for (int k=0; k<existingNodes.size(); ++k)
                    {
                        if (existingNodes.elementAt(k) instanceof RepositoryFolder)
                        {
                            RepositoryFolder repoFolder = (RepositoryFolder)existingNodes.elementAt(k);
                            if (repoFolder.getDescriptor().getUriString().equals( rd.getUriString()))
                            {
                                repoFolder.setDescriptor(rd);
                                found = true;
                                existingNodes.remove(k);
                                selectedNode.add(new DefaultMutableTreeNode(repoFolder));
                                break;
                            }
                        }
                    }
                   
                    if (!found)
                    {
                        RepositoryFolder rf = createRepositoryObject(reportUnit.getServer(), rd);
                        selectedNode.add(new DefaultMutableTreeNode(rf));
                    }
                }
            }
        }

        // 2. The second node is the main JRXML
        for (int i=0; i<list.size(); ++i)
        {
            ResourceDescriptor rd = (ResourceDescriptor)list.get(i);
            if (rd.getWsType().equals( rd.TYPE_JRXML) && rd.isMainReport())
            {
                list.remove(i);
                   
                boolean found = false;
                // Find rd in the vector....
                for (int k=0; k<existingNodes.size(); ++k)
                {
                    if (existingNodes.elementAt(k) instanceof RepositoryFolder)
                    {
                        RepositoryFolder repoFolder = (RepositoryFolder)existingNodes.elementAt(k);
                        if (repoFolder.getDescriptor().getUriString().equals( rd.getUriString()))
                        {
                            repoFolder.setDescriptor(rd);
                            found = true;
                            existingNodes.remove(k);
                            selectedNode.add(new DefaultMutableTreeNode(repoFolder));
                            break;
                        }
                    }
                }

                if (!found)
                {
                   RepositoryFolder rf = createRepositoryObject(reportUnit.getServer(), rd);
                   selectedNode.add(new DefaultMutableTreeNode(rf));
                }

                //}
                break;
            }
        }
        
        // 3. Then we have controls
        // Remove all controls....
        DefaultMutableTreeNode controlSet = null;
        
        // Look for the controlSet node...
        for (int i=0; i<selectedNode.getChildCount(); ++i)
        {
            Object obj = ((DefaultMutableTreeNode)selectedNode.getChildAt(i)).getUserObject();
            if (obj instanceof ControlsSet)
            {
                controlSet = (DefaultMutableTreeNode)selectedNode.getChildAt(i);
            }
        }
        
        if (controlSet == null)
        {
            ControlsSet cs = new ControlsSet();
            cs.setReportUnit(reportUnit);
            controlSet = new DefaultMutableTreeNode(cs);
            selectedNode.add(controlSet);
        }
        
        controlSet.removeAllChildren();
        
        for (int i=0; i<list.size(); ++i)
        {
            ResourceDescriptor rd = (ResourceDescriptor)list.get(i);
            if (rd.getWsType().equals( rd.TYPE_INPUT_CONTROL))
            {
                RepositoryFolder rf = createRepositoryObject(reportUnit.getServer(), rd);
                controlSet.add(new DefaultMutableTreeNode(rf));
            }
        }
        // 4. ...and resources
        // Update resources....
        DefaultMutableTreeNode resourcesSet = null;
        for (int i=0; i<selectedNode.getChildCount(); ++i)
        {
            Object obj = ((DefaultMutableTreeNode)selectedNode.getChildAt(i)).getUserObject();
            if (obj instanceof ResourcesSet)
            {
                resourcesSet = (DefaultMutableTreeNode)selectedNode.getChildAt(i);
            }
        }
        
        if (resourcesSet == null)
        {
            ResourcesSet cs = new ResourcesSet();
            cs.setReportUnit(reportUnit);
            resourcesSet = new DefaultMutableTreeNode(cs);
            selectedNode.add(resourcesSet);
        }
        existingNodes = new Vector();
        for (int i=0; i<resourcesSet.getChildCount(); ++i)
        {
            existingNodes.add( ((DefaultMutableTreeNode)resourcesSet.getChildAt(i)).getUserObject());
        }
        
        resourcesSet.removeAllChildren();
        
        for (int i=0; i<list.size(); ++i)
        {
            ResourceDescriptor rd = (ResourceDescriptor)list.get(i);
            if (!rd.getWsType().equals( rd.TYPE_INPUT_CONTROL) && !rd.isMainReport())
            {
                if (rd.getIsReference() &&
                    isDataSource( rd))
                {
                    continue;
                }
                
                boolean found = false;
                // Find rd in the vector....
                for (int k=0; k<existingNodes.size(); ++k)
                {
                    if (existingNodes.elementAt(k) instanceof RepositoryFile)
                    {
                        RepositoryFile repoFile = (RepositoryFile)existingNodes.elementAt(k);
                        if (repoFile.getDescriptor().getUriString().equals( rd.getUriString()))
                        {
                            repoFile.setDescriptor(rd);
                            found = true;
                            existingNodes.remove(k);
                            resourcesSet.add(new DefaultMutableTreeNode(repoFile));
                            break;
                        }
                    }
                }
                
                if (!found)
                {
                    RepositoryFolder rf = createRepositoryObject(reportUnit.getServer(), rd);
                    resourcesSet.add(new DefaultMutableTreeNode(rf));
                }
            }
        }
        
        // Move controlSet to the end...
        selectedNode.remove( controlSet );
        selectedNode.add( controlSet );
        
        selectedNode.remove( resourcesSet );
        selectedNode.add( resourcesSet );
    }
    
    public static boolean isDataSource(ResourceDescriptor rd)
    {
        if (rd == null) return false;
        if (rd.getWsType() == null) return false;
        if (rd.getWsType().equals( rd.TYPE_DATASOURCE) ||
            rd.getWsType().equals( rd.TYPE_DATASOURCE_JDBC) ||
            rd.getWsType().equals( rd.TYPE_DATASOURCE_JNDI) ||
            rd.getWsType().equals( rd.TYPE_DATASOURCE_BEAN)) return true;        
        return false;
    }
    
    /**
     * It exists, return the first parent report unit....
     *
     */
    public static RepositoryReportUnit getParentReportUnit(DefaultMutableTreeNode node)
    {
        if (node.getUserObject() instanceof RepositoryReportUnit) return (RepositoryReportUnit)node.getUserObject();
        
        Object[] parents =  node.getUserObjectPath();
        
        for (int i = parents.length-1; i>=0; --i)
        {
            if (parents[i] != null && parents[i] instanceof RepositoryReportUnit)
            {
                return (RepositoryReportUnit)parents[i];
            }
        }

        return null;
    }
    
    public void showMessageFromWorker(final String message)
    {
        
        Runnable r = new Runnable() {
            public void run()
            {
                JOptionPane.showMessageDialog(MainFrame.getMainInstance(), message);
            }
        };

        if (SwingUtilities.isEventDispatchThread())
        {
            r.run();
        }
        else
        {
            try { 
                SwingUtilities.invokeLater(r);
            } catch (Exception ex){}
        }                    
    
    }

    public boolean isTreeEnabled() {
        return treeEnabled;
    }

    public void setTreeEnabled(boolean enabled) {
        this.treeEnabled = enabled;
    }
    
}

