Tuesday, May 31, 2016

Drag and Drop between JLists (1)

Sample code of using the DragSourceListener, DragGestureListener, and DropTargetListener to drag element from one list to another.

import java.awt.BorderLayout;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DragGestureEvent;
import java.awt.dnd.DragGestureListener;
import java.awt.dnd.DragSource;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DragSourceListener;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetDragEvent;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.dnd.DropTargetEvent;
import java.awt.dnd.DropTargetListener;
import java.io.IOException;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JSplitPane;

public class DragDropDemo extends JFrame {
    private SourceList<String> source;
    private TargetList<String> target;
 
    public DragDropDemo() {
        source = new SourceList<String>(new String[]{"Papaya", "Orange", "Apple", "Mango", "Pear", "Avakado"});
        target = new TargetList<String>();
     
        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, source, target);
        JLabel label = new JLabel("Please drag your selection from the left list to the right");
     
        add(splitPane);
        add(label, BorderLayout.NORTH);
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        pack();
        setVisible(true);
    }
 
    private class SourceList<E> extends JList implements DragSourceListener, DragGestureListener {
        DragSource dragSource;
     
        public SourceList(E[] data){
            super(data);
            dragSource = new DragSource();
            dragSource.createDefaultDragGestureRecognizer(this, DnDConstants.ACTION_COPY_OR_MOVE, this);
        }
     
        public void dragDropEnd(DragSourceDropEvent e){
            System.out.println("Finished dragging !");
        }
        public void dragExit(DragSourceEvent e){
            System.out.println("Exiting dragging !");
        }
        public void dropActionChanged(DragSourceDragEvent e){
            System.out.println("Changing drag action !");
        }
        public void dragOver(DragSourceDragEvent e){
            System.out.println("Over dragging !");
        }
        public void dragEnter(DragSourceDragEvent e){
            System.out.println("Entering dragging !");
        }
     
        public void dragGestureRecognized(DragGestureEvent e){
            Transferable transferable = new StringSelection((String)getSelectedValue());
            dragSource.startDrag(e, DragSource.DefaultCopyDrop, transferable, this);
        }
    }
 
    private class TargetList<E> extends JList implements DropTargetListener {
        DefaultListModel model = new DefaultListModel();
        public TargetList() {
            super();
            setModel(model);
            new DropTarget(this, this);
        }
     
        public void drop (DropTargetDropEvent e){
            Transferable transferable = e.getTransferable();
            if (!transferable.isDataFlavorSupported(DataFlavor.stringFlavor)){
                e.rejectDrop();
            }
            e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
            String dragged;
            try {
                dragged = (String)transferable.getTransferData(DataFlavor.stringFlavor);
                model.addElement(dragged);
                validate();
            }catch(UnsupportedFlavorException fe){
                e.rejectDrop();
            }catch(IOException ie){
                e.rejectDrop();
            }
        }

        public void dragExit(DropTargetEvent e) {
            System.out.println("Exiting Dropping !");
        }
     
        public void dropActionChanged(DropTargetDragEvent e){
            System.out.println("Changing Drop Action !");
        }
        public void dragOver(DropTargetDragEvent e){
            System.out.println("Over Dropping !");
        }
        public void dragEnter(DropTargetDragEvent e){
            System.out.println("Entering Dropping !");
        }
    }
 
    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new DragDropDemo();
            }
        });
    }
}

Further Readings:
1. Drag and Drop between JLists (2)
2. Drag and Drop between JLists (3)

---------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Drag and Drop Between JLists (2)

The following sample code uses the TransferHandler to drag a component from one JList to another.

import java.awt.BorderLayout;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import javax.swing.DefaultListModel;
import javax.swing.DropMode;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JSplitPane;
import javax.swing.TransferHandler;

public class DragDropDemo2 extends JFrame {
    private JList<String> source;
    private JList<String> target;
    private DefaultListModel model = new DefaultListModel();
 
    public DragDropDemo2() {
        source = new JList<String>(new String[]{"Papaya", "Orange", "Apple", "Mango", "Pear", "Avakado"});
        target = new JList<String>();
        target.setModel(model);
     
        source.setDragEnabled(true);
        target.setDropMode(DropMode.ON_OR_INSERT);
     
        source.setTransferHandler(new ExportTransferHandler());
        target.setTransferHandler(new ImportTransferHandler());
     
        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, source, target);
        JLabel label = new JLabel("Please drag your selection from the left list to the right");
     
        add(splitPane);
        add(label, BorderLayout.NORTH);
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        pack();
        setVisible(true);
    }
 
    private class ExportTransferHandler extends TransferHandler {
        public int getSourceActions(JComponent c){
            return TransferHandler.COPY_OR_MOVE;
        }
     
        public Transferable createTransferable(JComponent c) {
            return new StringSelection(source.getSelectedValue());
        }
    }
 
    private class ImportTransferHandler extends TransferHandler {

        public boolean canImport(TransferHandler.TransferSupport supp) {
            if (!supp.isDataFlavorSupported(DataFlavor.stringFlavor)) {
                return false;
            }
            return true;
        }
     
        public boolean importData(TransferHandler.TransferSupport supp) {
            // Fetch the Transferable and its data
            Transferable t = supp.getTransferable();
            String data = "";
            try {
                data = (String)t.getTransferData(DataFlavor.stringFlavor);
            } catch (Exception e){
                System.out.println(e.getMessage());
                return false;
            }

            // Fetch the drop location
            JList.DropLocation loc = target.getDropLocation();
            int row = loc.getIndex();
            model.add(row, data);
            target.validate();
            return true;
        }
    }
 
    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new DragDropDemo2();
            }
        });
    }
}

Further Readings:
1. Drag and Drop between JLists (1)
2. Drag and Drop between JLists (3)

-----------------------------------------------------------------------------------------------------------------
Watch the blessing and loving online channel: SupremeMasterTV live




If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book for free here.

Drag and Drop between JLists (3)

Sample code for dragging Icons from one list to another.

import java.awt.BorderLayout;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import javax.swing.DefaultListModel;
import javax.swing.DropMode;
import javax.swing.ImageIcon;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JSplitPane;
import javax.swing.TransferHandler;

public class DragDropDemo2 extends JFrame {
    private JList<ImageIcon> source;
    private JList<ImageIcon> target;
    private DefaultListModel<ImageIcon> model = new DefaultListModel<ImageIcon>();
    private String imageLoc = "C:/images/";
 
    public DragDropDemo2() {
        source = new JList<ImageIcon>(new ImageIcon[]{new ImageIcon(imageLoc+"open.gif"),
                        new ImageIcon(imageLoc+"paste.gif"), new ImageIcon(imageLoc+"print.gif")});
        target = new JList<ImageIcon>();
        target.setModel(model);
     
        source.setDragEnabled(true);
        target.setDropMode(DropMode.ON_OR_INSERT);
     
        source.setTransferHandler(new ExportTransferHandler());
        target.setTransferHandler(new ImportTransferHandler());
     
        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, source, target);
        JLabel label = new JLabel("Please drag your selection from the left list to the right");
     
        add(splitPane);
        add(label, BorderLayout.NORTH);
        this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        pack();
        setVisible(true);
    }
 
    private class ExportTransferHandler extends TransferHandler {
        public int getSourceActions(JComponent c){
            return TransferHandler.COPY_OR_MOVE;
        }
     
        public Transferable createTransferable(JComponent c) {
            return new MyTransferable();
        }
    }
 
    private class MyTransferable implements Transferable {
        public Object getTransferData(DataFlavor flavor){
            if (flavor == DataFlavor.imageFlavor){
                return source.getSelectedValue();
            }
            return null;
        }
     
        public DataFlavor[] getTransferDataFlavors(){
            return new DataFlavor[] {DataFlavor.imageFlavor};
        }
     
        public boolean isDataFlavorSupported(DataFlavor flavor){
            if (flavor.equals(DataFlavor.imageFlavor)){
                return true;
            }
            return false;
        }
    }
 
    private class ImportTransferHandler extends TransferHandler {

        public boolean canImport(TransferHandler.TransferSupport supp) {
            if (!supp.isDataFlavorSupported(DataFlavor.imageFlavor)) {
                return false;
            }
            return true;
        }
     
        public boolean importData(TransferHandler.TransferSupport supp) {
            // Fetch the Transferable and its data
            Transferable t = supp.getTransferable();
            ImageIcon selected = null;
            try {
                selected = (ImageIcon)t.getTransferData(DataFlavor.imageFlavor);
            } catch (Exception e){
                System.out.println(e.getMessage());
                return false;
            }

            // Fetch the drop location
            JList.DropLocation loc = target.getDropLocation();
            int row = loc.getIndex();
            model.add(row, selected);
            target.validate();
            return true;
        }
    }
 
    public static void main(String[] args) {
        javax.swing.SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new DragDropDemo2();
            }
        });
    }
}

Further Readings:
1. Drag and Drop between JLists (1)
2. Drag and Drop between JList (2)

-------------------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Thursday, May 26, 2016

SQL: Convert between Julian date (YYYYDDD or YYDDD) and normal date in Oracle and PostgreSQL

Oracle


1. Convert Julian date to normal date

SELECT to_date(2016135, 'YYYYDDD') as theDate FROM dual;

THEDATE
---------
14-MAY-16

SELECT to_date(16135, 'YYDDD') as theDate FROM dual;

THEDATE
---------
14-MAY-16

2. Convert normal date to Julian date

SELECT to_number(to_char(sysdate,'YYYYDDD')) as theDate FROM dual;

 THEDATE
----------
   2016147

SELECT to_number(to_char(sysdate,'YYDDD')) as theDate FROM dual;

THEDATE
----------
     16147

PostgreSQL


1. Convert Julian date to normal date

SELECT to_date('2016135', 'YYYYDDD') AS theDate;
or
SELECT to_date(to_char(2016135, '9999999'), 'YYYYDDD') AS theDate;

  thedate
------------
 2016-05-14

SELECT to_date('16135', 'YYDDD') as theDate;
or
SELECT to_date(to_char(16135, '99999'), 'YYDDD') as theDate;

  thedate
------------
 2016-05-14

2. Convert normal date to Julian date

 SELECT to_number(to_char(current_date, 'YYYYDDD'), '9999999') as theDate;

 thedate
---------
 2016147

 SELECT to_number(to_char(current_date, 'YYDDD'), '99999') as theDate;

 thedate
---------
   16147

---------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Wednesday, May 25, 2016

Launch Crystal Report in Java with PostgreSQL database

//Set report source
ReportClientDocument rcd = new ReportClientDocument();
rcd.open(reportPath + reportName + ".rpt", 0);

DatabaseController databaseController = rcd.getDatabaseController();
Tables tables = databaseController.getDatabase().getTables();

setConnectionInfo(tables, userName, password, host, port, databaseName);

//If there are subreports, need to do the above operation on subreports
IStrings subreportNames = rcd.getSubreportController().getSubreportNames();

SubreportController src = rcd.getSubreportController();

for (int s = 0; s < subreportNames.size(); s++ ) {
      ISubreportClientDocument subreportClientDoc = src.getSubreport(subreportNames.getString(s));
      DatabaseContoller dbc = subreportClientDoc.getDatabaseController();
      Tables subreportTables = dbc.getDatabase().getTables();

      setConnectionInfo(subreportTables, userName, password, host, port, databaseName);
}

//Set parameters
ParameterFieldController pfc = rcd.getDataDefController().getParameterFieldController();
pfc.setCurrentValue("", paramName, paramValue);

//Display report
ReportViewerBean rvb = new ReportViewerBean();
rvb.init();
rvb.start();
rvb.setReportSource(rcd.getReportSource());

//Add the ReportVieverBean to your JFrame content pane
getContentPane.add(rvb);
setVisible(true);

//Close report
rvb.stop();
rvb.destroy();
rcd.close();

private void setConnectionInfo(Tables tables, String userName, String password, String host, String port, String databaseName) {
      for (int i = 0; i < tables.size(); i++) {
             ITable table = tables.getTable(i);

             table.setName(table.getName());
             table.setAlias(table.getAlias());

           

             PropertyBag propertyBag = new PropertyBag();

            StringBuilder url = new StringBuilder();
                url.append("jdbc:postgresql://").append(host).append(":")
                        .append(port).append("/").append(databaseName);
             
             StringBuilder uri = new StringBuilder();
                uri.append("!org.postgresql.Driver!").append(url.toString())
                        .append("!user={userid}!password={password}");

             propertyBag.put("JDBC Connection String", uri.toString());
             propertyBag.put("Connection URL", url.toString());
             propertyBag.put("Database Classname", "org.postgresql.Driver");
             propertyBag.put("Database", databaseName);
             propertyBag.put("Database Type", "JDBC (JNDI)");
             propertyBag.put("JDBC Connection", "True");
             propertyBag.put("Server", "");
             propertyBag.put("User ID", userName);
             propertyBag.put("Password", password);

            IConnectionInfo connInfo = table.getConnectionInfo();

             connInfo.setAttributes(propertyBag);
             connInfo.setUserName(userName);
             connInfo.setPassword(password);

             table.setConnectionInfo(connInfo);
             databaseController.setTableLocation(table, tables.getTable(i));
      }
}

--------------------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.

Tuesday, May 24, 2016

Crystal reports failed to open the connection; details: JDBC driver not found - solved

This solution is base on Crystal Reports 2013, Pack 7, Version 14.1.7.1853.

1. Download the JDBC driver jar file. For Oracle it is ojdbc7.jar; PostgreSQL, postgresql-9.4.1208.jre7.jar

2. Put the jar file in C:\Program Files (x86)\SAP BusinessObjects\SAP BusinessObjects Enterprise XI 4.0\java/lib/ directory.

3. Edit the CRConfig.xml file located in C:\Program Files (x86)\SAP BusinessObjects\SAP BusinessObjects Enterprise XI 4.0\java\ directory. Add the jar file to the <Classpath> </Classpath>. Separate it from other file path with ";".

4. Restart the Crystal Report.

------------------------------------------------------------------------------------

                        

If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.



Thursday, May 19, 2016

ERROR JRCCommunicationAdapter - detected an exception: Logon Error: FATAL: role "user" does not exist

I had this error when were running Crystal reports after we switched from using Oracle to PostgreSQL. Below is the original code.

ReportClientDocument reportClientDoc = new ReportClientDocument();
reportClientDoc.open(<reportName.rpt>, 0);

Tables tables = databaseController.getDatabase().getTables();
for (int i = 0; i < tables.size(); i++) {
      ITable table = tables.getTable(i);
      IConnectionInfo connectionInfo = table.getConnectionInfo();

      PropertyBag propertyBag = new PropertyBag();

      propertyBag.put("URI", "!oracle.jdbc.OracleDriver!jdbc:oracle:thin:{userid}/{password}@" + host + ":" + port + ":" + databaseName);

      //propertyBag.put("Use JDBC", "true");
      propertyBag.put("Database DLL", "crdb_jdbc.dll");

      connectionInfo.setAttributes(propertyBag);
      connectionInfo.setUserName(<database userName>);
      connectionInfo.setPassword(<database password>);

      table.setConnectionInfo(connectionInfo);

      //Throws error here.It somehow does not use the username and password
      //set in the connectionInfo to logon. Instead, it uses the application login user id.
      databaseController.setTableLocation(table, tables.getTable(i));
}

To fix this, use the code below to replace the code above in blue background.

      StringBuilder url = new StringBuilder();
      url.append("jdbc:postgresql://").append(host).append(":")
                .append(port).append("/").append(databaseName);
             
       StringBuilder uri = new StringBuilder();
       uri.append("!org.postgresql.Driver!").append(url.toString())
                .append("!user={userid}!password={password}");
        propertyBag.put("JDBC Connection String", uri.toString());
        propertyBag.put("Connection URL", url.toString());
        propertyBag.put("Database Classname", "org.postgresql.Driver");
        propertyBag.put("Database", databaseName);
        propertyBag.put("Database Type", "JDBC (JNDI)");
        propertyBag.put("JDBC Connection", "True");
        propertyBag.put("Server", "");
        propertyBag.put("User ID", userName);
        propertyBag.put("Password", password);

----------------------------------------------------------------------------------------

                        
If you have ever asked yourself these questions, this is the book for you. What is the meaning of life? Why do people suffer? What is in control of my life? Why is life the way it is? How can I stop suffering and be happy? How can I have a successful life? How can I have a life I like to have? How can I be the person I like to be? How can I be wiser and smarter? How can I have good and harmonious relations with others? Why do people meditate to achieve enlightenment? What is the true meaning of spiritual practice? Why all beings are one? Read the book free here.