Tuesday, February 27, 2018

[Solved] java.sql.SQLException: ORA-28040: No matching authentication protocol

After you upgrade your Oracle database to 12c, you suddenly see this error when you try to connect remotely to your database through JDBC.

java.sql.SQLException: ORA-28040: No matching authentication protocol

at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:331)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:283)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:278)
at oracle.jdbc.driver.T4CTTIoauthenticate.receiveOsesskey(T4CTTIoauthenticate.java:294)
at oracle.jdbc.driver.T4CConnection.logon(T4CConnection.java:357)
at oracle.jdbc.driver.PhysicalConnection.<init>(PhysicalConnection.java:441)
at oracle.jdbc.driver.T4CConnection.<init>(T4CConnection.java:165)
at oracle.jdbc.driver.T4CDriverExtension.getConnection(T4CDriverExtension.java:35)
at oracle.jdbc.driver.OracleDriver.connect(OracleDriver.java:801)
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)

To fix this problem:

Make sure the JDBC driver used by the client is ojdbc7.jar and all other drivers such as ojdbc14.jar are removed.

If the above does not fix this problem, on your Oracle server, open the file $ORACLE_HOME/network/admin/sqlnet.ora and add the line below to it.

SQLNET.ALLOWED_LOGON_VERSION=8

This SQLNET.ALLOWED_LOGON_VERSION parameter specifies the minimum authentication protocol allowed when connecting to Oracle Database instances. The value 8 permits most password versions, and allows any combination of the DBA_USERS.PASSWORD_VERSIONS values 10G, and 11G.

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

                        
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, February 22, 2018

Setting all JPanel, JCheckbox, JRadioButton in your project non-opaque / transparent through UIManager

To set the transparency of an individual JComponent, we use the JComponent.setOpaque(boolean opaque) to achieve it.

By default, a JPanel is opaque. To set all the JPanel objects in your whole project to be non-opaque, you can achieve it through modifying the UIManager once instead of setting each JPanel object to be non-opaque by calling setOpaque(false).

The odd thing is that the code UIManager.put("Panel.opaque", false) does not always work. In fact, it has never worked for me.

The way it works for me is by setting the background color of panels through the UIManager. There are two Color constructors that take four parameters.

Color(int r, int g, int b, int alpha)
Color(float r, float g, float b, float alpha)

The last parameter alpha specifies the transparency of the color.

For the int argument, alpha is a value between 0 and 255; 0 is completely transparent and 255 completely non-transparent.

For the float argument, alpha is a value between 0.0 and 1.0; 0.0 is complete transparent and 1.0 completely non-transparent.

To set all your JPanel objects transparent (non-opaque), use the following code before constructing any of the JPanel objects:

UIManager.put("Panel.background", new Color(110, 110, 110, 0);
or
UIManager.put("Panel.background", new Color(0.5, 0.5, 0.5, 0.0);

To set all your JPanel objects non-transparent(opaque):
UIManager.put("Panel.background", new Color(110, 110, 110, 255);
or
UIManager.put("Panel.background", new Color(0.5, 0.5, 0.5, 1.0);

Of course, you can set the transparency to any value in between.

Similarly, you can set the transparency of your JCheckbox and JRadioButton objects by setting the values for the CheckBox.background and RadioButton.foreground keys in the UIManager.

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

                        
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, February 12, 2018

java.util.ConcurrentModificationException of java streaming

Java streaming is a multi-thread process. If more than one thread are modifying the state of the same object, it will throw the java.util.ConcurrentModificationException.

One example is using parallel streaming to delete elements from or inserting elements into the original list/array, which interferes the iterating process of each other. Below is a piece of code of another example.

public class EmployeeState {
      private String name = "";
      private String title = "";
      private int skillLever = 0;

      public void setEmployeeState(String n, String t, int s) {
            name = n;
            title = t;
            skillLevel = s;
      }

      public String getName() { return name; }
   
      public String getTitle() { return title; }

      public int getSkillLevel() { return skillLevel; }
}

Public class EmployeesWithTheSkillLevel {
      private int skillNeeded = 0;
      private List<String> empNames;
      private EmployeeState empState;

      public EmployeesWithTheSkillLevel (int s, List<String> en) {
            skillNeeded = s;
            empNames = en;
            empState = new EmployeeState();
      }

      public boolean filtEmp(String empname) {
            boolean bn = false;
            int skill;
            try ( PreparedStatement ps = getConnection().prepareStatement("select title, skillLevel from employee where name = '"+empname +"'");
                        ResultSet rs = ps.executeQuery()) {

                   if (rs.next()) {
                          skill = rs.getInt("skillLevel");
                          if (skill == skillNeeded) {
                                bn = true;
                                empState.setEmployeeState(empname, rs.getString("title"), skill);
                           }
                    } 
              }
              return bn;
      }

      public void print(String empname){
            System.out.println(empname + "\t\t\t" + empState.getTitle());
      }

      public void printEmp() {
            empNames.parallelStream()
                               //This line will throw the java.util.ConcurrentModificationException
                              .filter(e -> filtEmp(e))
                              .forEach(e -> print(e));
      }
}

The line of code .filter(e -> filtEmp(e)) will throw the java.util.ConcurrentModificationException because the filtEmp method modifies the state of the EmployeeState object which is shared by all threads.

To fix it:
Make the EmployeeState object a method field of the filtEmp method instead of a class field, and pass it to the print method.

public boolean filtEmp(String empname) {
            EmployeeState empState = new EmployeeState();
            boolean bn = false;
            int skill;
            try ( PreparedStatement ps = getConnection().prepareStatement("select title, skillLevel from employee where name = '"+empname +"'");
                        ResultSet rs = ps.executeQuery()) {

                   if (rs.next()) {
                          skill = rs.getInt("skillLevel");
                          if (skill == skillNeeded) {
                                bn = true;
                                empState.setEmployeeState(empname, rs.getString("title"), skill);
                           }
                    } 
              }
              return bn;
      }

      public void print(String empname, EmployeeState empState){
            System.out.println(empname + "\t\t\t" + empState.getTitle());
      }

Or you can synchronize the block of code that changes the shared EmployeeState object.

public boolean filtEmp(String empname) {
            boolean bn = false;
            int skill;
            try ( PreparedStatement ps = getConnection().prepareStatement("select title, skillLevel from employee where name = '"+empname +"'");
                        ResultSet rs = ps.executeQuery()) {

                    synchronized (lock) {
                         if (rs.next()) {
                                skill = rs.getInt("skillLevel");
                                if (skill == skillNeeded) {
                                      bn = true;                           
                                      empState.setEmployeeState(empname, rs.getString("title"), skill);
                                }
                           }
                    } 
              }
              return bn;
      }

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

                        
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, February 7, 2018

java.net.ConnectException: Connection refused: connect

java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at java.net.Socket.<init>(Socket.java:434)
at java.net.Socket.<init>(Socket.java:211)

This error occurs when the client is not able to connect to the server. There are several things can make this error happen.

1. The server is down.

2. The server is not listening on the port.

3. The client is using a wrong IP address or port.

4. The server and/or client are not connected to the network.

5. The firewall on the server and/or client is blocking the connection.

References:

1. How to Fix java.net.ConnectException: Connection refused: connect in Java

2. java.net.ConnectException – How to solve Connect Exception

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

                        

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.


Configure Windows firewall to allow a connection

When you need to connect your computer to a server through a network connection, both the firewalls on the server and your computer need to be configured to allow the connection to go through. Otherwise, it will throw a java.net.ConnectException.

To configure the firewall on your computer which has Windows 10 as its operating system:

1. Open the Windows Defender Firewall. Click on the Window icon in the left-bottom corner of your computer, type "firewall" and select the Windows Defender Firewall.

2. Click on the Advanced Settings on the left side of the window.

3. Click the Outbound Rules in the left pane. Then, click the New Rules in the right pane.

4. Select Custom and click the Next button.

5. Select the This program path if you know which program you are using. Otherwise select All programs. Click the Next button

6. Select UDP from the Protocol type drop-down list if you use DatagramSocket, otherwise select TCP if you use ServerSocket / Socket.

7. Select Specific Ports from the Remote port drop-down list and enter the port. Click the Next button.

8. Under Which remote IP addresses does this rule apply to, select These IP addresses.

9. Click the Add button and enter the IP address of your remote server and click the OK button. Click the Next button.

10. Select the Allow the connection and click the Next button. And click the Next button again.

11. Check all the check boxes: Domain, Private, and Public. Click the Next button.

12. Enter a name for this rule. Click the Finish button.

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

                        
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.



Thread and Runnable: How different are they?

To create a Thread in your process, you have to have your class implement the Runnable interface and be a subclass or a target composite class of a Thread class so  that the start() method of the Thread can be called. That is it must implement the Runnable interface and is able to be executed through the Thread start method.

Since the Thread class implements the Runnable interface, you can make your class to extend the Thread class and call the start method. The Thread class has many other methods other than the run() method. All these will be compiled into your code.

Alternatively, you can have your class implement the Runnable interface directly and pass it to a Thread constructor as an argument to create a new Thread. The Runnable interface only has one run() method. Therefore, your class is simpler and smaller.

No difference of performances has been observed between Threads created in these two ways.

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

                        

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, February 5, 2018

Java: Comparator vs Comparable, when to use which?

Comparator is a third party class which compares two objects through its compare (T object1, T object2) method. Different implementations of the Comparator interface can compare the same two objects using different fields and result in different outcomes.

Comparable, on the other hand, is a super type of the objects being compared. The class, the instances of which the objects being compared are, implements the Comparable interface and overrides the compareTo (T object) method. There is only one outcome when two objects are compared in this way.


1. Example code of Comparable

Lets say you have an Employee class and you want to order them by their performances.

      public class Employee implements Comparable {
            private String name;
            private int performance;
            private int yearsWorked;
            private int salary;

            public Employee (String nm, int per, int yw, int sa) {
                 name = nm;
                 performance = per;
                 yearsWorked = yw;
                 salaery = sa;
            }

           public String getName() { return name; }

            public int getPerformance() { return performance; }
         
            public int getYearsWorked() { return yearsWorked; }

            public int getSalary() { return salary; }

            @Override //Overrides the method in the Comparable interface
            public int compareTo (Employee emp) {
                  return this.getPerformance() - emp.getPerformance();
            }

            public static void main (String[] args) throws SQLException {
                  List<Employee> employees = new List<>();
               
                  try {
                        Connection dbConn = <.......>;
                        PreparedStatement ps = dbConn.prepareStatement(
                                  "select name, performance, yearsWorked, salary from employee");
                        ResultSet rs = ps.executeQuery()) {

                        while(rs.next()) {
                               employees.add(new Employee(rs.getString("name"),
                                                                                  rs.getInt("performance"),
                                                                                  rs.getInt("yearsWorked").
                                                                                  rs.getInt("salary"));
                                                                               
                        }
                  }
                  //Sort employees by performance and print them on screen
                  //Collections.sort(employees);
                  employees.stream()
                                  .sorted()
                                  .map(Employee::getName)
                                  .forEach(System.out::println);
            }
      }

2. Example code of Comparator

Now, you also want to order the employees by years worked or by salary. The code shows how to compare by years worked. It is similar to compare by salary.

      public class CompareByYearsWorked<Employee> implements Comparator<Employee> {
            public int compare (Employee e1, Employee e2) {
                  return e1.getYearsWorked() - e2.getYearsWorked();
           }

            public boolean equals(Object obj) {
                  return false;
            }
      }

      Add the segment of code to the end of the main method after you printed the employees in order of their performances.

       //employees.sort(new CompareByYearsWorked());
       employees.stream()
                         .sorted (new CompareByYearsWorked())
                         .map(Employee::getName)
                         .forEach(System.out::println);

You can always use Comparator to compare two object instances of a class. However, the code of using Comparable is more simple and does not require you to pass a parameter of the Comparator when being used. But you can only use Comparable to compare one thing of the objects.

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

                        

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.