Wednesday, December 17, 2014

SQL: Increase/Decrease an amount of a field/column

For example, you have three fields (name  varchar2, price float, order integer) in the Fruit table. You now want to decrease  the price by 0.5 and increase the order by 5 for the Apple. Following is one way of doing it.

UPDATE Fruit
SET price = price - 0.5, order = order + 5
WHERE name = 'APPLE';

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

                        
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.

Monday, December 15, 2014

Increase/Decrease the month by 1 and get the last day of the month in Java

Use the roll method of Calendar to increment the month generated correct dates regardless of the actual days in the moth. For example, use the roll method to increase the month by 1 on a Calendar instance of date January 31, 2012 will give February 28, 2012.

The following sample code shows how to use the roll method to increment or decrement the month and then get the last day of the month.

int year = 2012;
int month = Calendar.JANUARY;
int day = 31;

Calendar calendar = new GregorianCalendar(year, month, day);

//increments the month by 1
calendar.roll(Calendar.MONTH, true);

//or decrements the month by one
//calendar.roll(Calendar.MONTH, false);

//get the last day of the month
int lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);

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

                        
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, November 13, 2014

Missing IN or OUT parameter at index:: 1

The exception occurs when number of values assigned to a query does not equal the columns involved in the query.

The following query when executed throws such an exception.

String sql = "INSERT INTO ORDER VALUES(?, ?, ?,?);
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString("Whole Sale");
ps.setDate(CURRENT_DATE);
ps.setFloat(188.23);
ps.setFloat(1.89);
ps.setString("Kevin Smith");

There are 4 columns in the sql, but it is trying to set 5 values to the query.

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

                        
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.

SQLException: ORA-00984: column not allowed here

The exception occurs when assigning value for inserting or updating records and value given is not properly presented.

The following queries throw such an exception.

String name = "Apple";

1. INSERT INTO FRUIT (NAME, PRICE) values (name, 1.68);

2. UPDATE FRUIT set NAME=name where PRICE=1.68;

To Fix them, do the following.

1. INSERT INTO FRUIT (NAME, PRICE) values ("'"+name+"'", 1.68);

2. UPDATE FRUIT set NAME= "'"+name+"'" where PRICE=1.68;

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

                        
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.


Monday, November 3, 2014

NetBeans: Change the default java platform and add a new java platform

A. Change the default java platform


Open the netbeans.conf file located at <NetBenas home>\etc. change the netbeans_jdkhome=<C:\Program Files\Java\jdk1.8.0_25 or other jdk home>

Restart NetBeans IDE.

B. Add a java platform to the NetBeans:


  1. Click Tools in the top menu of NetBeans IDE, select Java Platforms.
  2. In the pop up window, click the "Add platform..." button at the left bottom.
  3. Select the jdk you would like to add, click "Next >".
  4. Enter a platform name and click "Finish".
-------------------------------------------------------------------------------------------------------------

                        
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.

Desktop shortcut throws C:\ProgramData\Oracle\Java\javapath\java.exe The specified path does not exist

When you double click the desktop shortcut for executing your Java program, the following message pops up.


To fix this, right-click on your desktop shortcut icon and select Properties. In the Target field in the new pop up window, type 'java <your execute program>' or 'java -jar <your executable jar name>', then click the "Apply" button at the bottom, it will automatically put the correct path in the Target field.
       
----------------------------------------------------------------------------------------------------------------------

                        
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.

Oracle: Save query result to a local spread sheet or text file with fields separated by comma, pipeline, or other characters


At the command prompt, type sqlplus <username>/<password>, then hit enter.

Do the following to save to a file.

SQL> SPOOL <file path/file name><.txt or .csv> CREATE/APPEND/REPLACE
   
      (By default, the option is REPLACE if you don't specify it.)

SQL> SET colsep <delimiter such as ,  or |>

//Print the column header to the output file. Default is ON
SQL> SET head ON/OFF

//Print underline beneath the column headers. Default is ON
SQL> SET UNDERLINE ON/OFF

//Print the total number of rows selected
SQL> SET FEEDBACK ON/OFF

SQL> <your SELECT sql statement>

SQL> SPOOL OFF

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

                        
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, October 28, 2014

Java: Copy a directory recursively to a new location

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

public class DirectoryCopy {
      public static void main(String[] args) {
            try {
                  DirectoryCopy runner = new DirectoryCopy();
                  runner.copyFile("R:\\FileDepot", "C:\\MyFiles\\ProjectDesign");
            }catch(IOException e) {
                  e.printStackTrace();
            }
      }

      public void copyFile(String sourceDir, String desDir) throws IOException {
        File file = new File(sourceDir);
        File file2 = new File(desDir);
        if (file.isDirectory()) {
            if (!file2.exists()) {
                file2.mkdir();
            }
            String[] allFiles = file.list();
            for (String f : allFiles) {
                copyFile(sourceDir+"\\"+f, desDir+"\\"+f);
            }
        } else {
            if (!file2.exists()) {
                file2.createNewFile();
            }
            Files.copy(file.toPath(), file2.toPath(), StandardCopyOption.REPLACE_EXISTING);
        }

    }
}

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

                        
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.

Windows: How to get all the local drives and remote sites mounted/mapped to your computer?

Open the Command Prompt and type 'net use' without the quotes.

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

                        
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, October 23, 2014

Launch default web browser for displaying page section/particular position/sub topic like "page.html#namelink" in Java - resolved




import java.io.IOException;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class GetDefaultBrowser {

    public static void main(String[] args) {
        System.out.println(new GetDefaultBrowser().getDefaultBrowser());
    }

    public String getDefaultBrowser() {
        String defaultBrowser = "";
        try {
            //1.  Find the default browser in registry
            String browser = "";
            Process process0 = Runtime.getRuntime().exec("REG QUERY HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http\\UserChoice");
            Scanner kb = new Scanner(process0.getInputStream());
            while(kb.hasNextLine()){
                String line = kb.nextLine();
                if (line.toUpperCase().indexOf("PROGID")>=0){
                    String[] elements = line.split(" ");
                    browser = elements[elements.length-1];
                    System.out.println(browser);
                }
            }

            //2. Get the default browser path from registry
            Process process = Runtime.getRuntime().exec("REG QUERY HKEY_CLASSES_ROOT\\"+browser+"\\shell\\open\\command");
            kb = new Scanner(process.getInputStream());
            while (kb.hasNextLine()) {
                String registry = (kb.nextLine()).replaceAll("\\\\", "/").trim();
                if (registry.indexOf("Default") < 0){
                    continue;
                }
             
                int fidx = registry.indexOf("\"");
                int lidx = registry.indexOf("exe");
             
                if (fidx > 0 && lidx > 0) {
                    defaultBrowser = registry.substring(fidx+1, lidx+3);
                 
                    Runtime.getRuntime().exec(defaultBrowser +
                            " file:///C:/MyFiles/GreatJouney.htm#T01_FLORIDA");
                    break;
                }
            }
         
            kb.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return defaultBrowser;
    }
}

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

                        
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, October 22, 2014

JSch: Transfer file between remote and local computers/machines/systems in Java

There are many ways to do this. One way is use JSch to open a SftpChannel between your local machine and remote machine. You can download JSch from its offical site: http://www.jcraft.com/jsch/

Following is an example of the code.

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;


public class RemoteSftp {
    public static void main(String[] args){
        try{
            JSch jsch=new JSch();

            Session session = jsch.getSession("<username>","<host name or IP address>");
            session.setPassword("<password>");
            session.setConfig("StrictHostKeyChecking", "no");
            session.connect();

            Channel channel = session.openChannel("sftp");
            channel.connect();
            ChannelSftp sftpChannel = (ChannelSftp)channel;
       
            sftpChannel.get("<source file path/file name>", "<destination file path>");
            sftpChannel.put("<source file path/file name>", "<destination file path>");

            sftpChannel.disconnect();
            session.disconnect();
        }catch(JSchException e){
            e.printStackTrace();
        }catch(SftpException se){
            se.printStackTrace();
        }
    }
}

------------------------------------------------------------------------------------------------------------------
    
                        
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, October 21, 2014

JSch: com.jcraft.jsch.jschexception unknownhostkey: rsa key fingerprint is - resolved

This exception is thrown because for security purpose, it needs to check if the host key you set in the program matches the host key in the ~/.ssh/known_hosts file.

The following code throws such an exception at the marked line.

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;


public class FileCopy {
    public static void main(String[] args){
        try{
            JSch jsch=new JSch();
            Session session = jsch.getSession("<username>","<host name or IP address>");
            session.setPassword("<password>");

            session.connect();

            Channel channel = session.openChannel("sftp");
            channel.connect();
            ChannelSftp sftpChannel = (ChannelSftp)channel;
         
            sftpChannel.get("<source file path/file name>", "<destination file path>");
            sftpChannel.disconnect();
            session.disconnect();
        }catch(JSchException e){
            e.printStackTrace();
        }catch(SftpException se){
            se.printStackTrace();
        }
    }
}

To fix it, you may do one of the followings.


1. Add this line of  code before you call session.connect()

          session.setConfig("StrictHostKeyChecking", "no");

2. Copy the ~/.ssh/known_hosts file from the host to your machine, and add the following line of code before you call session.connect().

         jsch.setKnownHosts("<known_hosts>");
          
-------------------------------------------------------------------------------------------------------

                        
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.

Monday, October 20, 2014

NetBeans: Use an old/previous version/revision of code/file/project, Revert vs Checkout

If for some reason, one of your code users could not accommodate the recent modifications of the code at the moment and would like to go back to an old version of the code, you could either revert your current code to the old version or checkout the old version, and then do a build and send the jar to your code user.

A. Revert

  1. Open the window explorer, find the file or project that you are interested in, make a copy of it and save it some where.
  2. In NetBeans, right-click on the file/project, select "Subversion", then "Revert Modifications"
  3. In the pop-up window, select "Revert Modifications from Single Commit", then click the "Search" button.
  4. In the new pop-up window, click the "List" button, click on the revision that you would like to revert to, then click the "OK" button at the bottom.
  5. Click the "Revert" button.
Revert may generate conflicts in file.

After you have sent the jar to the particular user, you can follow the procedure to revert your code back to the current revision. Or simply update the code to the HEAD.

B. Checkout

  1. In NetBeans, close the project.
  2. In Window Explorer, rename the project to something else.
  3. In NetBeans, click "Team" on the top menu, select "Checkout"
  4. Enter the correct information related to your repository n the pop-up window, and click the "Next" button.
  5. Click the "Browse" button at the line of "Repository Folder(s) to choose the project that you would like to checkout
  6. Click the "Search" button at line Repository Revision.
  7. In the new pop-up window, click the "List" button, click on the revision that you would like to revert to, then click the "OK" button at the bottom.
  8. Click the "Finish" button.

After you have finished with the old code, you can update the code to your current working version and close the project in NetBeans. In window explorer, rename the old project and rename the current revision of the project back to the project name and open the project in NetBeans.

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

                        
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.

Friday, October 17, 2014

DynamicReport: Setting font name, size and style for report, column, text component and subreport


JasperReportBuilder report = DynamicReports.report();

1. The default font for the whole report.

          report.setDefaultFont(stl.font("<font name>", isBold, isItalic, fontSize ));

          //Or
          // report.setDefaultFont(stl.fontArial().setFontSize(9));
          // report.setDefaultFont(stl.font().boldItalic());
          // report.setDefaultFont(stl.font().setUnderline(true));

2. Font for a column

           report.columns(col.column("Name", type.stringType())
                     .setStyle(stl.style().setFont(stl.font("<font name>", isBold, isItalic, fontSize ))));

           //Or
           // TextColumnBuilder clmn = col.column("Name", type.stringType());
           // clmn.setStyle(stl.style().setFontSize(9).bold().italic());
           //report.addColumn(clmn);

4. Font for a text component

           cmp.text("<your text>").setStyle(stl.style().setFont(stl.font("<font name>", isBold, isItalic, fontSize )));

5. Font for a sub-report

            SubreportBuilder subreport = <your sub-report>;
            subreport.setStyle(stl.style().setFont(stl.font("<font name>", isBold, isItalic, fontSize )));

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

                        
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, October 8, 2014

DynamicReports: How to make subreport display at a fixed page position / bottom of last page - resolved

Lets say that you have a subreport which displays a message. The length of the message can be from 0 to 20 lines. Following this message subreport, you have another subreport which displays some data and you would like it to be always displayed at the bottom one third of the page regardless the length of the message.

One way to make the second data subreport to be always displayed at a certain height of the page is to set the height of the first message subreport above it. The way to do it is to put the subreport in a vertical list or a horizontal list and set the height/width/dimension of that vertical list or horizontal list.

However, if the message has so many lines that it overflows the space you specified, the message subreport will expand and push your data subreport down. If this happens and you would like the data subreport to be displayed at the bottom one third of the next page, you need to count the lines of your message and need to know how many lines of message the space you specified can hold and the whole page can hold. If the lines of message is larger than the lines of message your space can hold, you need to add empty lines to the message until it starts to display on the next page. You need to let it display at least one line on the next page, only then the height you specified for the message subreport will apply to the message on the next page and let your data subreport be displayed at the right position.


import java.util.ArrayList;
import java.util.List;
import net.sf.dynamicreports.jasper.builder.JasperReportBuilder;
import net.sf.dynamicreports.report.builder.DynamicReports;
import static net.sf.dynamicreports.report.builder.DynamicReports.cmp;
import static net.sf.dynamicreports.report.builder.DynamicReports.col;
import static net.sf.dynamicreports.report.builder.DynamicReports.exp;
import static net.sf.dynamicreports.report.builder.DynamicReports.stl;
import net.sf.dynamicreports.report.builder.component.SubreportBuilder;
import net.sf.dynamicreports.report.builder.datatype.DataTypes;
import net.sf.dynamicreports.report.exception.DRException;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

public class ReportDimensionDemo {
    private int messageRows = 0;

    public static void main(String[] args){
        new ReportDimensionDemo();
    }
 
    public ReportDimensionDemo() {
        JasperReportBuilder report = DynamicReports.report();
        report.setDataSource(createDataSource());
     
        SubreportBuilder messageSubreport = cmp.subreport(buildMessageSubreport())
                .setDataSource(exp.subDatasourceBeanCollection("messageData"));
        SubreportBuilder dataSubreport = cmp.subreport(buildDataSubreport())
                .setDataSource(exp.subDatasourceBeanCollection("dataData"));
     
        report.detail(cmp.verticalList(messageSubreport).setFixedHeight(300),
               // .setFixedWidth(200)
                //.setFixedDimension(200, 300)
                dataSubreport );
       //to display at the bottom of last page
       //report.summary(dataSubreport);      
        try {
            report.show(false);
        }catch(DRException de){
            de.printStackTrace(System.out);
        }
    }
 
    private JasperReportBuilder buildMessageSubreport() {
        JasperReportBuilder report = DynamicReports.report();
        report.columns(col.column("message", DataTypes.stringType()));
     
        return report;
    }
 
    private JasperReportBuilder buildDataSubreport() {
        JasperReportBuilder report = DynamicReports.report();
        report.columns(col.column("Name", "name", DataTypes.stringType())
                    .setStyle(stl.style(stl.pen1Point())),
                col.column("Price", "price", DataTypes.doubleType())
                        .setStyle(stl.style(stl.pen1Point()))
                        .setPattern("$##0.00"));
     
        return report;
    }
 
    private JRDataSource createDataSource() {
        List<ReportData> dataSource = new ArrayList<ReportData>();
        ReportData reportData = new ReportData();
        List<MessageData> messageList = new ArrayList<MessageData>();
        MessageData messageData = new MessageData();
        List<DataData> dataList = new ArrayList<DataData>();
        DataData dataData = new DataData();
     
        for (i=0; i<50; i++) {
             messageData.setMessage("The most useful report in the universe - "+i);
             messageList.add(messageData);
             //count the lines of message
             messageRows++;
             messageData = new MessageData();
        }

        //If the message overflow the height you specified, push the message band
        //to the next page so that the data subreport is displayed at the right
         //position on the next page.
        int remainder = messageRows%<message lines per whole page>
        if (remainder > <message lines in specified space>) {
              while (remainder < (<message lines per whole page> + 2)) {
                      messageData.setMessage("");
                      messageList.add(messageData);
                      messageData = new MessageData();
              }
       }
     
        reportData.setMessageData(messageList);
     
        dataData.setName("Apple");
        dataData.setPrice(1.68);
        dataList.add(dataData);
        dataData = new DataData();
        dataData.setName("Papaya");
        dataData.setPrice(3.14);
        dataList.add(dataData);
        reportData.setDataData(dataList);
     
        dataSource.add(reportData);
        return new JRBeanCollectionDataSource(dataSource);
    }
 
    public class ReportData {
        private List<MessageData> messageData;
        private List<DataData> dataData;
     
        public List<MessageData> getMessageData() {return messageData;}
        public void setMessageData(List<MessageData> m) {messageData=m;}
        public List<DataData> getDataData() {return dataData;}
        public void setDataData(List<DataData> d) {dataData=d;}
    }
 
    public class MessageData{
        private String message;
     
        public String getMessage() {return message;}
        public void setMessage(String m) {message=m;}
    }
 
    public class DataData {
        private String name;
        private Double price;
     
        public String getName() {return name;}
        public void setName(String n) {name=n;}
        public Double getPrice() {return price;}
        public void setPrice(Double p) {price=p;}
    }
}
   
----------------------------------------------------------------------------------------------------------------

                        
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.

Friday, October 3, 2014

setSize vs setPreferredSize in JTextArea, JTextField, JButton, JLabel, JPanel and JFrame

For JFrame:
          Always use setSize for setPreferredSize does nothing.

For JPanel, JButton and JLabel:
          No need to set their sizes for their sizes are always expanding to the space available. You need to use some invisible components or fillers to occupy the space that you don't want these components to be.

For JTextField:
         The setColumns method designates the size of the JTextField.
         The setPreferredSize makes the JTextField disappear, while the setSize does nothing.

For JTextArea:
          The setRows and setColumns methods designate the size of the JTextArea.

         The setPreferredSize fixes the displaying area. If the setLineWrap(true) method is not called, the input characters will keep adding to the end of the line, however the width of the JTextArea will not expand and it only displays the number of characters its width can hold. If the setLineWrap(true) method is called, the input characters will be displayed in a new line when the width of the displaying area is reached. However, when the height of the displaying area is reached, the height of the displaying area will not expand even though the input characters are keeping adding to the end of the text.

        When setSize is used instead of setPreferredSize, the behavior of the JTextArea is the same as it is not used, if the setLineWrap(true) method is not called, the input characters will keep adding to the end of the line and the width of the JTextArea expands accordingly. If the setLineWrap(true) method is called, the input characters will be displayed in a new line when the width of the displaying area is reached and when the height of the displaying area is reached, the height of the displaying area will expand accordingly.

          If you really want to use the setPreferredSize or the setSize to set the size of the JTextArea instead of using setRows and setColumns, do not call the setRows and setColumns methods and call the setLineWrap(true) before you call the setPreferredSize or the setSize method.

           The setPreferredSize mthod will set the size of the JTextArea to the size specified in the method. The size is fixed and will not expand according to the size of the text you put in it.

           The setSize method will set the width to the specified amount, but will not set the height. The height dynamically expands according to the the text put in the text area.

When the JTextArea is put in a JScrollPane:
          No matter whether the setRows and setColumns or the setPreferredSize or the setSize is used, the size of the JTextArea will occupy the whole available space in the JScrollPane. When setSize is used, it will automatically scroll, where else when setPreferredSize is used the JScrollPane will not scroll.

           However, when a JTextArea is put in a JScrollPane, it is better to not use either setPreferredSize or setSize on the JTextArea and the JScrollPane will scroll when it is needed.

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

                        
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, October 2, 2014

\AppData\Local\NetBeans\Cache\7.4\executor-snippets\junit.xml:134: The following error occurred while executing this line:

To fix the following error

C:\Users\user\AppData\Local\NetBeans\Cache\7.4\executor-snippets\junit.xml:134: The following error occurred while executing this line:

C:\Users\user\AppData\Local\NetBeans\Cache\7.4\executor-snippets\junit.xml:78: The <classpath> for <junit> must include junit.jar if not in Ant's own classpath
BUILD FAILED (total time: 0 seconds)

1. If you are doing JUnit test, add the JUnit jars to your class path.

2. Check to see if the class you are executing has a main method. If it doesn't have one, add a public static void main method to it to make it executable.

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

                        
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.

How to make JTextArea display a maximum number of characters?

Following are the steps of setting the maximum numbers of characters that a JTextArea can take.


  1. Create a Document class that extends the PlainDocument class. 
    • In the class create a maxSize field. 
    • Override the insertString method so that only the maxSize or less number of characters can be inserted into the document. 
    • Create a setMaxSize method for setting the value of the maxSize.
  2. Create a Text Area class that extends the JTextArea, which uses the Document created in step 1 as its default document. Add a setMaxSize method to the class that calls the Document's setMaxSize mthod to set the max size for the Document.
Here is the sample code.


import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

public class TextAreaSize {
    
    private class MyDocument extends PlainDocument {
        private int maxSize = 1000000000;
        
        @Override
        public void insertString(int offset, String s, AttributeSet attributeSet)
                throws BadLocationException {
            int length = s.length();
            if (length == 0) {
                return;
            }

            if (offset + length > maxSize) {
                s = s.substring(0, maxSize - offset);
            }
            super.insertString(offset, s, attributeSet);
        }
        
        public void setMaxSize(int size) {
            maxSize = size;
        }
    }
    
    private class MyTextArea extends JTextArea {
        private MyDocument document;
        
        public MyTextArea (MyDocument d){
            super(d);
            document = d;
        }
        
        public void setMaxSize(int s){
            document.setMaxSize(s);
        }
    }
    
    public TextAreaSize() {
        MyTextArea textArea = new MyTextArea(new MyDocument());
        textArea.setMaxSize(30);
        textArea.setRows(2);
        textArea.setColumns(20);
        
        JPanel panel = new JPanel();
        panel.add(textArea);
        
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(panel);
        frame.setSize(500, 300);
        frame.setVisible(true); 
    }
    
    public static void main(String[] args){
        new TextAreaSize();
    }
}

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

                        
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.


How to make JTextArea display a fixed number of characters each line

There are two ways to achieve this result. One way is to use the setRows and setColumns method to set the size of the JTextArea. The other way is making your text area the subclass of the JTextArea and override the paint() method to get the width and height of the font used. Then, set the size of your text area.

Since for many types of font, the characters do not always have the same widths, some characters are wider than the others, it is better that you use the monospaced font for achieving a constant result.

Following is an example.

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;

public class CharInLine {
    private int charWidth = 0;
    private int charHeight = 0;
    private int charPerLine = 30;
 
    public CharInLine() {
        MyTextArea textArea = new MyTextArea();
        textArea.setFont(new Font("monospaced", Font.PLAIN, 12));
     
        //Method 1
        //setting the rows and columns is important for an
        //empty JTextArea to show its size.
        textArea.setRows(5);
        textArea.setColumns(30);
        textArea.setBorder(BorderFactory.createTitledBorder("Text Area"));
     
        //Method 2
        //designate 30 characters per line and 5 lines in the text area
        textArea.setLineWrap(true);
        textArea.setSize(new Dimension(charWidth*charPerLine, charHeight*5));
        //textArea.setPreferredSize(new Dimension(charWidth*charPerLine, charHeight*5));    

        JPanel panel = new JPanel();
        panel.add(textArea);
     
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(panel,BorderLayout.CENTER);
        frame.setSize(500, 300);
     
        frame.setVisible(true);
    }
 
    private class MyTextArea extends JTextArea {
        @Override
        public void paint(Graphics g){
            super.paint(g);
            FontMetrics fm = g.getFontMetrics();
            charWidth = fm.charWidth('M');
            charHeight = fm.getHeight();
        }
    }
 
    public int getCharWidth() {
        return charWidth;
    }
 
    public static void main(String[] args){
        new CharInLine();
    }
}

Reference:

1. setSize vs setPreferredSize in JTextArea, JTextField, JButton, JLabel, JPanel and JFrame

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

                        
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.

Monday, September 29, 2014

SQL ORA-00979: not a GROUP BY expression

This exception occurs when the SELECT clause contains aggregate functions such as MAX, MIN, SUM, AVG, and COUNT, and there has no GROUP BY clause or the GROUP BY clause does not include all the items in the SELECT clause except the aggregate functions.

For example, the following queries throw such an exception.

1. SELECT NAME, DESCRIPTION, MAX(PRICE) PRICE FROM FRUIT WHERE PRICE < 1.33;

In this case, the query has an aggregate function MAX(PRICE) in the SELECT clause but does not have a GROUP BY clause.

2. SELECT NAME, DESCRIPTION, MAX(PRICE) PRICE FROM FRUIT WHERE PRICE < 1.33 GROUP BY NAME;

In this case, though the GROUP BY clause is there but it dose not contain all the non-aggregate items. The DESCRIPTION is missing from the GROUP BY clause.

To Fix this problem, you may add all the items in the SELECT clause to the GROUP BY clause . However, the GROUP BY clause must have all the non-aggregate items (both NAME and DESCRIPTION in the above queries).

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

                        
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, September 23, 2014

DynamicReports: How to set the height/width/dimension of a sub-report?

Lets say that you have a subreport which displays a message. The length of the message can be from 0 to 20 lines. Following this message subreport, you have another subreport which displays some data and you would like it to be always displayed at the bottom one third of the page regardless the length of the message.

One way to make the second data subreport to be always displayed at a certain height of the page is to set the height of the first message subreport above it. The way to do it is to put the subreport in a vertical list or a horizontal list and set the height/width/dimension of that vertical list or horizontal list.


import java.util.ArrayList;
import java.util.List;
import net.sf.dynamicreports.jasper.builder.JasperReportBuilder;
import net.sf.dynamicreports.report.builder.DynamicReports;
import static net.sf.dynamicreports.report.builder.DynamicReports.cmp;
import static net.sf.dynamicreports.report.builder.DynamicReports.col;
import static net.sf.dynamicreports.report.builder.DynamicReports.exp;
import static net.sf.dynamicreports.report.builder.DynamicReports.stl;
import net.sf.dynamicreports.report.builder.component.SubreportBuilder;
import net.sf.dynamicreports.report.builder.datatype.DataTypes;
import net.sf.dynamicreports.report.exception.DRException;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;

public class ReportDimensionDemo {
    public static void main(String[] args){
        new ReportDimensionDemo();
    }
 
    public ReportDimensionDemo() {
        JasperReportBuilder report = DynamicReports.report();
        report.setDataSource(createDataSource());
     
        SubreportBuilder messageSubreport = cmp.subreport(buildMessageSubreport())
                .setDataSource(exp.subDatasourceBeanCollection("messageData"));
        SubreportBuilder dataSubreport = cmp.subreport(buildDataSubreport())
                .setDataSource(exp.subDatasourceBeanCollection("dataData"));
     
        report.detail(cmp.verticalList(messageSubreport).setFixedHeight(300),
               // .setFixedWidth(200)
                //.setFixedDimension(200, 300)
                dataSubreport );
        try {
            report.show(false);
        }catch(DRException de){
            de.printStackTrace(System.out);
        }
    }
 
    private JasperReportBuilder buildMessageSubreport() {
        JasperReportBuilder report = DynamicReports.report();
        report.columns(col.column("message", DataTypes.stringType()));
     
        return report;
    }
 
    private JasperReportBuilder buildDataSubreport() {
        JasperReportBuilder report = DynamicReports.report();
        report.columns(col.column("Name", "name", DataTypes.stringType())
                    .setStyle(stl.style(stl.pen1Point())),
                col.column("Price", "price", DataTypes.doubleType())
                        .setStyle(stl.style(stl.pen1Point()))
                        .setPattern("$##0.00"));
     
        return report;
    }
 
    private JRDataSource createDataSource() {
        List<ReportData> dataSource = new ArrayList<ReportData>();
        ReportData reportData = new ReportData();
        List<MessageData> messageList = new ArrayList<MessageData>();
        MessageData messageData = new MessageData();
        List<DataData> dataList = new ArrayList<DataData>();
        DataData dataData = new DataData();
     
        messageData.setMessage("The most useful report in the universe.");
        messageList.add(messageData);
        reportData.setMessageData(messageList);
     
        dataData.setName("Apple");
        dataData.setPrice(1.68);
        dataList.add(dataData);
        dataData = new DataData();
        dataData.setName("Papaya");
        dataData.setPrice(3.14);
        dataList.add(dataData);
        reportData.setDataData(dataList);
     
        dataSource.add(reportData);
        return new JRBeanCollectionDataSource(dataSource);
    }
 
    public class ReportData {
        private List<MessageData> messageData;
        private List<DataData> dataData;
     
        public List<MessageData> getMessageData() {return messageData;}
        public void setMessageData(List<MessageData> m) {messageData=m;}
        public List<DataData> getDataData() {return dataData;}
        public void setDataData(List<DataData> d) {dataData=d;}
    }
 
    public class MessageData{
        private String message;
     
        public String getMessage() {return message;}
        public void setMessage(String m) {message=m;}
    }
 
    public class DataData {
        private String name;
        private Double price;
     
        public String getName() {return name;}
        public void setName(String n) {name=n;}
        public Double getPrice() {return price;}
        public void setPrice(Double p) {price=p;}
    }
}
   
-----------------------------------------------------------------------------------------------------------  

                        
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, September 4, 2014

How to get current working directory in Java - resolved

The current working directory is the root directory of your java project. There are several ways to retrieve the current working directory.

1. System.getProperty("user.dir"))

           public class CurrentDirectoryTest {
                      public static void main(String[] args){
                              System.out.println("Current Directory is: "+System.getProperty("user.dir"));
                      }
           }

2. Paths.get("").toAbsolutePath().toString()
   
          public class CurrentDirectoryTest {
                      public static void main(String[] args){
                              System.out.println("Current Directory is: "+Paths.get("").toAbsolutePath().toString());
                      }
           }

3. (new File("")).getAbsolutePath()

           public class CurrentDirectoryTest {
                      public static void main(String[] args){
                              System.out.println("Current Directory is: "+(new File("")).getAbsolutePath());
                      }
           }

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

                        
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, September 3, 2014

NetBeans contains files with errors - resolved

If you have a class X in project B extends a class Y in project A, error badges may occur in project B after you modified class Y and rebuilt project A. When you point the cursor at the error badge, it says "Contains files with errors". When you open the java file of class X and point the cursor at the error line, it says "Class X cannot convert to class Y".

To fix this problem


  1. Right-click on project B and select "Porperties".
  2. Click "Libraries" on the left under Categories.
  3. Select the library or the jar of project A in the right pane and click the "Remove" button to remove it.
  4. Click "OK" to close the window.
  5. Restart NetBeans.
  6. Repeat steps 1 and 2.
  7. Click the "Add Library" or "Add JAR/Folder" button to add the library or the jar of project A back to project B.         
-----------------------------------------------------------------------------------------------------------------

                        
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, August 26, 2014

Launch the default or a particular web browser in Java

A. Launch the default web browser

1. Launch in Windows

import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

public class LaunchBrowserTest {
    public static void main(String args[]) {
        String url = "http://www.google.com";

         //method 1 of launching web browser in Windows
         if (Desktop.isDesktopSupported()) {
                Desktop desktop = Desktop.getDesktop();
                try {
                    desktop.browse(new URI(url));
                } catch (IOException | URISyntaxException e) {
                    e.printStackTrace();
                }
            }

            //method 2 of launching web browser in Windows
            String os = System.getProperty("os.name").toLowerCase();
             Runtime rt = Runtime.getRuntime();
             if (os.indexOf("win") >= 0) {
                    try {
                            rt.exec("rundll32 url.dll,FileProtocolHandler " + url);
                     } catch (IOException  e) {
                             e.printStackTrace();
                      }
                }
         }
}

2. Launch in MAC

public class LaunchBrowserTest {
    public static void main(String args[]) {
        String url = "http://www.google.com";
        String os = System.getProperty("os.name").toLowerCase();
        Runtime rt = Runtime.getRuntime();

         if (os.indexOf("mac") >= 0) {
                  try {
                          rt.exec("open " + url);
                   } catch (IOException  e) {
                             e.printStackTrace();
                      }
                }
         }
}

3. Launch in other systems

public class LaunchBrowserTest {
    public static void main(String args[]) {
           String url = "http://www.google.com";
            Runtime rt = Runtime.getRuntime();
     
            try {
                    rt.exec("xdg-open " + url);
                } catch (IOException e) {
                    e.printStackTrace();
                }
       }
}

B. Launch a particular web browser

1. Launch in Windows

public class LaunchBrowserTest {
    public static void main(String args[]) {
        String url = "http://www.google.com";
        String os = System.getProperty("os.name").toLowerCase();
        Runtime rt = Runtime.getRuntime();

        try {
            //launch the google chrome
            String[] cmds = new String[] {"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe", url};
             //launch the internet explorer
             // String[] cmds = new String[] {"C:/Program Files (x86)/Internet Explorer/iexplore.exe", url};                      //launch the firefox
             //String[] cmds = new String[] {"<your path>/firefox.exe", url};

            rt.exec(cmds);
        } catch (IOException e) {
                    e.printStackTrace();
                }
       }
}

2. Launch in Unix/Linux

public class LaunchBrowserTest {
    public static void main(String args[]) {
        String url = "http://www.google.com";
        String os = System.getProperty("os.name").toLowerCase();
        Runtime rt = Runtime.getRuntime();

        if (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0) {
              try {
                  //launch the google chrome
                   rt.exec(new String[] {"chrome", url});
                  //or
                   // rt.exec(new String[]{"sh", "-c", "chrome\"+url+"\"});
               
                  //launch the firefox
                   rt.exec(new String[] {"firefox", url});
                  //or
                  // rt.exec(new String[]{"sh", "-c", "firefox\"+url+"\"});
              } catch (IOException e) {
                    e.printStackTrace();
                }
       }
}

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

                        
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.