Friday, May 30, 2014

SSL Error/Certificate Error: Cannot connect to real www.google.com / real website

Web browsers such as Google chrome and Microsoft internet explorer fail to go to any websites through https, and give an error page.

In Google chrome, the error page looks like the following



In Microsoft internet explorer,  the error page looks like the following.



To fix this problem

  1. Adjust the date and time of your computer to the current date and time
  2. Close the web browsers and reopen them
  3. For Google chrome, click the three bar icon at the top-right corner, choose Settings. Click on the Show Advanced Settings at the bottom. Scroll down, under HTTPS/SSL, click the Manage Certificates button. use the arrows at the top-right corner of the pup-up window to show more tabs, select Trusted Publishers and remove all expired certificates. Then select the Untrusted Publishers tab and remove all the expired certificates.
  4. For Microsoft internet explorer, click on the setting icon at the top-right corner, choose Internet Options. Select the Content tab, click the Clear SSL State button to clear all the SSL state. Click the Certificates button, use the arrows at the top-right corner of the pup-up window to show more tabs, select Trusted Publishers and remove all expired certificates. Remove all the expired certificates from the Untrusted Publishers tab too.
----------------------------------------------------------------------------------------------------------------

                        
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.

DynamicReports: Setting page/paper orientation and margins

JasperReportBuilder report = DynamicReports.report();

//Setting the page/paper type and paper orientation for display (report.show())
report.setPageFormat(PageType.LETTER, PageOrientation.LANDSCAPE);
// report.setPageFormat(PageType.A4, PageOrientation.PORTRAIT);

//setting the orientation for saving to a file (report.toPdf(), report.toText(),...)
report.setPrintOrder(Orientation.VERTICAL); //landscape
//report.setPrintOrder(Orientation.HORIZONTAL); //portrait

//setting the page margins
report.setPageMargin(DynamicReports.margin().setLeft(50).setTop(80).setRight(50).setBottom(80));

StyleBuilder titleStyle = Styles.style().bold().setHorizontalAlignment(HorizontalAlignment.CENTER);
report.title(Components.text("Test Report")
                .setStyle(titleStyle));

report.columns(Columns.column("column 1", "col1", DataTypes.stringType());

report.setDataSource(<your data source>);

report.show(false);
       
-----------------------------------------------------------------------------------------------------------------

                        
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.

DynamicReports: Close the JasperViewer without closing the parent JFrame

JasperReportBuilder report = DynamicReports.report();
report.setPageFormat(PageType.LETTER, PageOrientation.LANDSCAPE);

StyleBuilder titleStyle = Styles.style().bold().setHorizontalAlignment(HorizontalAlignment.CENTER);
report.title(Components.text("Test Report")
                .setStyle(titleStyle));

report.columns(Columns.column("column 1", "col1", DataTypes.stringType());

report.setDataSource(<your data source>);


//To prevent closing the parent frame by report.show()
//use the following code
report.show(false);
          
------------------------------------------------------------------------------------------------------------------

                        
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.

Using a printer device to print a text document in java

To print a document using a printer, you must have one or more printers connected to your computer. The javax.print packages have all the java classes for doing this job. Following is an sample code to print a text document using a printer.

public class PrintTest {
    public static void main(String[] args) {
        byte[] bytes = null;
        try {
            //read the file to be printed into a byte array
            Path path = FileSystems.getDefault().getPath("<file directory>","<file name>");
            bytes = Files.readAllBytes(path);
        } catch (IOException ffne) {//FileNotFoundException ffne) {
            ffne.printStackTrace();
        }

        //create the Doc object using the byte array
        DocFlavor docFlavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;

//      DocAttributeSet daset = new HashDocAttributeSet();
//      daset.add(OrientationRequested.LANDSCAPE);
//      daset.add(Sides.ONE_SIDED);

        Doc myDoc = new SimpleDoc(bytes, docFlavor, daset);

        //create the PrintRequestAttributeSet
        PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
//        aset.add(new Copies(5));
//        aset.add(Sides.ONE_SIDED);
//        aset.add(Sides.TWO_SIDED_LONG_EDGE);
//        aset.add(MediaName.NA_LETTER_WHITE);
//        aset.add(MediaSizeName.NA_LETTER);
//        aset.add(MediaTray.TOP);
//        aset.add(OrientationRequested.LANDSCAPE);

        //Find the printer that maches the name that you would like to use
        PrintService[] services = PrintServiceLookup.lookupPrintServices(docFlavor, null);

        for (PrintService service : services) {
            if (service.getName().equalsIgnoreCase("<your printer name>")) {

                 //Manually confirm the printer or select another printer
//               service = ServiceUI.printDialog(null, 250, 250, services, service,
//                                              docFlavor, aset);

                //create the DocPrintJob
                DocPrintJob job = service.createPrintJob();

                try {
                    //print the document
                    job.print(myDoc, aset);

                } catch (PrintException pe) {
                    pe.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.

Setting text styles, colors, font and alignment in JTextPane (2): html

You can also setting the styles, colors, font and other character of the text in JTextPane using html. Following is an example code.

import java.awt.Color;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;

public class HtmlTest extends JTextPane {
 
    public static void main(String[] args){
        //create the JTextPane and set the ContentType to text/html
        HtmlTest test = new HtmlTest();
        test.setContentType("text/html");
        test.setBackground(Color.yellow);
     
        String str = "<p align='center'><font size='14' color='blue' style='background-color: gray;'>Style Test Result</font></p><br/>"+
                    "<font size='8' color='red' style='background-color:green;'>the first line</font><br/>"+
                    "the second line<br/>";
     
        //get the HTMLEditorKit
        HTMLDocument doc = (HTMLDocument)test.getDocument();
        HTMLEditorKit editorKit = (HTMLEditorKit)test.getEditorKit();
        try{
            //insert the text using the HTMLEditorKit
            editorKit.insertHTML(doc, doc.getLength(), str,0,0, null);
        }catch(BadLocationException ble){
            ble.printStackTrace(System.out);
        } catch(IOException ioe){
            ioe.printStackTrace(System.out);
        }
     
        JFrame f = new JFrame("Style Test");
        f.setContentPane(new JScrollPane(test));
        f.setSize(500, 300);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}

           Previous <

References

1. Setting text styles, colors, font and alignment in JTextPane (1): attributes

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

                        
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 29, 2014

Setting text styles, colors, font and alignment in JTextPane (1): attributes

JTextPane allows to set font, styles, foreground color, background color, and text alignment for each segment of  the text, which is very difficult to do with JTextArea. Following is a sample code for setting some of this characters in JTextPane.

import java.awt.Color;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.text.SimpleAttributeSet;
import javax.swing.text.StyleConstants;

public class AttributeTest extends JTextPane {
    SimpleAttributeSet attributeSet;
 
    public AttributeTest() {
        //create the SimpleAttributeSet
        attributeSet = new SimpleAttributeSet();
    }
 
    public void addString(int fontSize,
            Color foregroundColor,
            Color backgroundColor,
            boolean isBold,
            boolean isItalic,
            int alignment,
            String str) {
        //add the attributes to the SimpleAttributeSet
        StyleConstants.setFontSize(attributeSet, fontSize);
        StyleConstants.setForeground(attributeSet, foregroundColor);
        StyleConstants.setBackground(attributeSet, backgroundColor);
        StyleConstants.setBold(attributeSet, isBold);
        StyleConstants.setItalic(attributeSet, isItalic);
        StyleConstants.setAlignment(attributeSet, alignment);
     
        //set the attribute to the StyledDocument
        int len = this.getText().length();    
        StyledDocument sDoc = this.getStyledDocument();
        sDoc.setCharacterAttributes(len, str.length(), attributeSet, false);

        // Or using the following two lines of code to replace the above two lines of code
       // this.setCaretPosition(len);
      //  this.setCharacterAttributes(attributeSet, false);
   
       //insert the string to the JTextPane
        this.replaceSelection(str);
    }
 
    public static void main(String[] args){
        String[] strs = {"The Third Line\n",
                         "The Second Line\n",
                         "The First Line\n",
                         "Style Test Result\n"
                         };
        AttributeTest test = new AttributeTest();
        for (int i=0; i<strs.length; i++) {
            if (i == 3){
                test.addString(14, Color.blue, Color.LIGHT_GRAY, true, false, StyleConstants.ALIGN_CENTER, strs[i]);
            } else if (i == 2){
                test.addString(11, Color.red, Color.GREEN, false, true, StyleConstants.ALIGN_LEFT, strs[i]);
            } else if (i == 1) {
                test.addString(11, Color.orange, Color.LIGHT_GRAY, false, false, StyleConstants.ALIGN_LEFT, strs[i]);
            } else {
                test.addString(11, Color.black, Color.CYAN, false, false, StyleConstants.ALIGN_LEFT, strs[i]);
            }
        }
        test.setBackground(Color.yellow);
        JFrame f = new JFrame("Style Test");
        f.setContentPane(new JScrollPane(test));
        f.setSize(500, 300);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setVisible(true);
    }
}

                                                    > next

References

1. Setting text styles, colors, font and alignment in JTextPane (2): html

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

                        
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? Order Here

Wednesday, May 21, 2014

How to debug java code to fix runtime exceptions

If your java code throws any exceptions during its execution, follow the steps below to find out the cause and fix them.
  1. Look at the stack trace printed in your log file or in the console. Scroll down to see if there is a line starting with "Caused by". Following that line to look for the first line that is about your code. If you could not find a line starting with "Caused by", look from the beginning of the stack trace to find the first line that indicates a place in your code
  2. Look at the place of your code found above to see if there is anything inappropriate, then fix it. You may need to look at the stack trace the second or third lines that are directly related to your code to understand what is going on. If you could not tell what is wrong, you need to debug this section of code.
  3. Debugging java code in NetBeans
    • Setting breakpoint: A breakpoint is a place in the source code that makes the debugger to hang when the execution reaches it. To set a breakpoint, select a line, click the left grey margin area of the line or right click on the left grey margin area of the line, select Breakpoint, then select Toggle Line Breakpoint, the line is highlighted in red with a square red mark on the left margin.
    • Setting a watch: If you would like to monitor the value of a variable, click the Debug button on the top menu and choose New Watch. Enter the variable name that you want to monitor. Or you can right click on the variable name directly and choose New Watch. Click OK. You can monitor the changes of the variable value in the Watches window during debugging.
    • Starting the debugger: Right click on your executable application and choose Debug File. Alternatively, you can select the executable application in the Projects pane, click the Debug button on the top menu and select Debug File. The debugger will execute the program until it reaches a breakpoint, it then hangs. 
    • Using the following keys or corresponding buttons on the top menu to watch the execution of the program.
      • F8 (Step Over): Executes the current line of code. If the current line is a method call, execute the method without stepping into the code of the method.
      • F7 (Step Into): Executes the current line of code. If the current line is a method call, step into the code of the method and stops at the first line of the method .
      • Ctrl+F7 (Step Out): Finishes the execution of the current method and returns to the caller of the method.
      • F5 (Continue): Continue the execution until it reaches the next breakpoint.
      • F4 (Run to Cursor): Continue the execution to the line where the cursor is located
    • While debugging, click the Window button on the top menu, select Debugging, then select Variables, Watches, and any other you would like to monitor. You can monitor the values of the variables in the Variables and Watches windows. Or you can hover the cursor on the variable during line by line execution. You can also highlight an expression by dragging the cursor through it while the left mouse button is pressed, and the hover the cursor over it to see the value of the expression.
  4. Debugging java code in eclipse
    • Setting breakpoint: Select the line of code that you decide to start debugging, go to the left end of the line, double click the small margin area to the left of the line or right click to select Toggle Breakpoint, and the line is marked as a debugging point
    • Starting the debugger: Right-click on the executable application, select Debug as and then select Java Application. If a Confirm Perspective Switch window pops up asking if you want to open the debug perspective, click Yes. If the debugger has already been started, you can click the bug icon on the top menu to start debugging after you having set the debug breakpoint. The execution of the program will hang at the breakpoint.
    • Using the keys described below or corresponding buttons on the top menu to watch the execution of the code
      • F5 (Step into): Executes the current line and goes to the next line. If the current line is a method call, the debugger will step into the code of  the method
      • F6 (Step over): Executes the current line and goes to the next line regardless if the current line is a method call or not. If the current line is a method call, the program executes the method call without the debugger stepping into the code of the method.
      • F7 (Step out): The program finishes the execution of the current method and returns to the caller of this method
      • F8 (Go to next breakpoint): The program will execute until it reaches the next breakpoint.
    • Using the Variables View to analyse the execution. The Variables View displays the names and values of fields and local variables in the current executing stack. To change the display of the view, click the drop down icon at the top-right corner and select the display
  5. Manually debugging
    • If the editor that you use for coding does not have the debugging function. You may select points in your code where you would like to see how the execution progresses, and print to the console a message to indicate that the previous section of code executed successfully and it is entering the next section of code, and if possible attach the values of any pertinent variables using System.out.println("<message>"). If at a place the message stops printing and the program terminates, you know that the problem is located between that place and the place the last message is printed
    • You may also use the Java Debugger (jdb) to debug your code.
         
--------------------------------------------------------------------------------------------------------------------

                        
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.
--------------------------------------------------------------------------------------------------------------------------------

References

1. Java debugging tutorial - 10 tips on debugging in java with example
2. Java Debugging with Eclipse - Tutorial
3. NetBeans Debugger- Short Tutorial

Saturday, May 17, 2014

How to get rid of/remove the Connect search malware, Conduit search engine and Trovi Search from your web browsers

The Connect search malware also known as Connect DLCS is a browser hijacker and spyware. It is automatically installed onto your Microsoft Windows computer, often associated with search.conduit.com and bing.com. Once it is installed, it attaches to popular Internet browsers including google chrome, Mozilla Firefox, and Internet Explorer. The Connect malware changes the browser settings such as the start page/home page when a new window or tab is opened and replacing the default search engine with search.conduit.com, Trovi Search or bing.com or other search engines.

The Connect malware not only hijacks your web browsers but also collects sensitive user  information such as your online purchasing, browsing activity, full name, home address, email, and phone numbers, and sends it to Conduit.

The Connect DLCS is often downloaded and installed to your computer while you download and install free software such as video downloading/recording/streaming software, download managers, etc. which have bundled the Connect DLCS into their installations. The Connect malware is also associated with free software downloaded from certain download websites like CNET, Brothersoft and Softonic.

Once it is installed, it spreads to many places and it is quite difficult to thoroughly remove it.

To remove Connect malware from your computer, follow the steps below

A. Uninstall Connect DLCS and search.conduit.com programs
  1. Open the Control Panel, click the " Uninstall a program" link
  2. In the pop up window, looking for recently installed programs with names like Connect toolbar, Connect DLCS, Search Protect, Client Connect LTD, Search Protect by conduit, Smileys We Love, UpdateChecker, and Trovi
  3. Click on it and uninstall/remove it

B. Remove Connect Toolbar add-ons and extensions from web browsers and repair browser settings
  1. Google Chrome 
    • Open Google Chrome, click the three bar icon next to the address bar, choose Tools, then Extensons
    •  Look for Connect DLCS, Connect Bar, Connect DLC, Conduit and Trovi, click the trash can icon at the right to remove it
    • Also remove any unwanted extensions
    • Click the three bar icon next to the address bar, choose Settings. 
    • Under the On startup, click on the Set pages link. Remove all unwanted web pages and set your startup page. Click OK
    • Under Search, click the "Manage Search Engines" button. 
    • Make google as your default search engine
    • Look for Conduit, Trovi Search, any search engine that uses search.conduit.com, select it and click the "X" at the very rigt to remove it
    • Click Start, type "%UserProfile%\AppData\Local\Google\Chrome\User Data\Default" (without quotes) in the search box and press Enter. 
    • In the default folder, rename a filed named Preferences to Preferences.old and rename another file named Web Data to Web Data.old
  2. Mozilla Firefox
    • Open Mozilla Firefox, click the orange Firefox button on the top left and choose Add-ons
    • Click the Extensions, look for Connect Toolbar/Connect DLC/Connect Bar, and remove it
    • Click the orange Firefox button and choose Options
    • Select the General tab, enter your default home page in the home page box, and click OK
    • In the opened Firefox window, click the drop down arrow of the search box on the top right corner and choose Manage Search Engines
    • Look for Connect DLC, Conduit, Trovi Search, and any search engines use search.conduit.com, remove them, then click OK
    • Open a new blank tab, type about:config in the address box and press return
    • Click the "I will be careful, I promise!" button
    • Type Connect in the search box to search, look at the value column of the search result to locate anything containing Connect DLCS/Connect Bar, select it, right click on it and choose Reset to remove it one by one
    • Restart Firefox
    • Click the orange Firefox button and choose Help, then the Troubleshooting Information link. Click the Reset Firefox button to reset to default settings
  3. Microsoft Internet Explorer
    • Open Microsoft Internet Explorer, click Tools on the top menu or the Settings icon at the top right corner, and choose Internet Options
    • Select the General tab, change the Home page from search.conduit.com to your disired web page, click OK, then Close
    • Restart Internet Explorer, click Tools or the Settings icon and choose Internet Options
    • Select the Programs tab, click the Manage add-ons button
    • Click Toolbars and Extensions link on the left, disable any Connect, Conduit, Trovi and unwanted add-ons
    • Click Search Providers link on the left, set google as your default search provider, look for Connect DLCS, Trovi search, and Conduit and remove all of them. Click Close
    • Restart Internet Explorer, click Tools or the Settings icon and choose Internet Options
    • Select the Advanced tab, click the Reset botton, check Delete personal settings in the pop up and click Reset. Click Close after it is done.
C. Remove Conduit search and Trovi search from Registry
  1. Click Start, type REGEDIT in the search box and press Enter
  2. Type Ctrl+F, enter search.conduit in the search field and click Find Next
  3. Delete any registry that its Name, Type or Value contains conduit (right click on the name and choose Delete). 
  4. Search for conduit and delete the folder named ConduitSearchScopes and the folder named Conduit
  5. Keep searcing, delete any registries and folders that contain conduit until nothing shows in the search result
  6. Repeat steps 2-5 to search for trovi and delete related entries from the registry

D. Remove Conduit and Trovi from Startup and Services
  1. Click Start, type MSCONFIG in the search box and press Enter
  2. Select the Startup tab, uncheck all the entries that contains conduit or trovi
  3. Select the Services tab, check the Hide all microsoft services. Uncheck all the entries that contain conduit or trovi

E. Remove Conduit and Trovi from Task Scheduler
  1. Click Start, right click on Computer, and select manage
  2. Expand Task Scheduler, click on the Task Scheduler Library
  3. Delete all tasks that contain conduit or trovi and all unknown tasks

F. Restart your computer

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

                        

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.
------------------------------------------------------------------------------------------------------------------

References:

1. How to remove Connect Toolbar – Connect Search (Removal Guide)
2. How to Remove Conduit Search from Chrome, Firefox, IE

Friday, May 16, 2014

NetBeans - Throwable.printStackTrace() should be removed

If you use NetBeans for your Java development, whenever you use printStackTrace() in a catch block, you get a warning sign that the Throwable.printStackTrace() should be removed.

To get rid of this warning sign, do one of the followings

         1. Log the exception. For example to log to a file.
                  Logger logger = Logger. getAnonymousLogger();
                  logger.addHandler(new FileHandler("<directory>/<file name>");
                  logger.log(Level.SEVERE, <exception>.getMessage(), <exception>);
     
         2. Print the stack trace to a file
                  PrintStream ps = new PrintStream(
                                            new FileOutputStream("<directory>/<file name>", true));
                  <exception>.printStackTrace(ps);

         3. If your really want to print to the console, use <exception>.printStackTrace(System.out) instead of <exception>.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.

Friday, May 9, 2014

Email in Java - the JavaMail API (2): Multipart and attachment

To construct a complex email body, the javax.mail.Multipart and the javax.mail.internet.MimeBodyPart are used to set the content of the message. Each part can be set to independent style and content. The first part (part 0) is the main body of the email, all the other parts are attachments to the email.

Following is a sample code of constructing a complex email.

import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class JavaMailDemo {
    //an example of username: "john.smith@gmail.com"
    private final String username = "<username>@<email host>";
    private final String password = "<your password>";
 
    private Properties properties = null;
    private Session session = null;
 
    public JavaMailDemo() {
        properties = new Properties();
        //the smtp host at gmail is "smtp.gmail.com"
        properties.put("mail.smtp.host", "<the smtp email host>");
        //the smtp port at gmail is "587"
        properties.put("mail.smtp.port", "<port>");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
     
        session = Session.getInstance(properties,
 new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
 });
    }
 
    public void sendEmail(String recipients, String subject, String content,
                             String messageType, String filePath)
                             throws MessagingException {
        MimeMessage message = new MimeMessage(session);
        Multipart theMail = new MimeMultipart();
     
        //Add the text content
        MimeBodyPart textContent = new MimeBodyPart();
        textContent.setContent(content, "text/plain");
        theMail.addBodyPart(textContent, 0);

       //Add the html content
       MimeBodyPart htmlContent = new MimeBodyPart();
       htmlContent.setContent("<html><h1>"+content+"</h1></html>", "text/html");
       theMail.addBodyPart(htmlContent, 1);
     
        //Add the attachment
        FileDataSource theFile = new FileDataSource(filePath);
        MimeBodyPart attachment = new MimeBodyPart();
        attachment.setDataHandler(new DataHandler(theFile));
        attachment.setFileName(filePath);
        theMail.addBodyPart(attachment);
     
        message.setContent(theMail);
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
//        message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(recipients));
//        message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(recipients));
        message.setSubject(subject);
     
        Transport.send(message);
    }

    public static void main(String[] args) {
        String recipients = "sarah.campbell@gmail.com, sarah.campbell@yahoo.com";
        String subject = "Testing again";
        String content = "I am happy that you are reading this";
     
        JavaMailDemo mailSender = new JavaMailDemo();
        try {
            mailSender.sendEmail(recipients, subject, content, "text/html",
                    "<path>/<file name>");
         
        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}

          Previous <

References:

1.Email in Java - the JavaMail API (1): A simple text or html email
2. Internet media type

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

                        
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.

Email in Java - the JavaMail API (1): A simple text or html email

If you don't have the javax.mail package in your JDK, you can download it from its official website

Following is an example of sending a simple text email to recipients

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SimpleEmailDemo {
    //an example of username: "john.smith@gmail.com"
    private final String username = "<username>@<mail host>";
    private final String password = "<your password>";
 
    private Properties properties = null;
    private Session session = null;
 
    public SimpleEmailDemo() {
        properties = new Properties();
        //the smtp host at gmail is "smtp.gmail.com"
        properties.put("mail.smtp.host", "<the smtp host>");
        //the smtp port at gmail is "587"
        properties.put("mail.smtp.port", "<port>");
        properties.put("mail.smtp.auth", "true");
        properties.put("mail.smtp.starttls.enable", "true");
     
        session = Session.getInstance(properties,
 new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
 });
    }
 
    public void sendEmail(String recipients, String subject, String content, String messageType)
                             throws MessagingException {
        MimeMessage message = new MimeMessage(session);
        message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(recipients));
//        message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(recipients));
//        message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(recipients));
        message.setSubject(subject);

        if (messageType.equalsIgnoreCase("text/html")) {
                message.setContent(content, messageType);
        } else {
               message.setText(content);
        }
     
        Transport.send(message);
    }

    public static void main(String[] args) {
        String recipients = "justLucky@gmail.com, justLucky@yahoo.com";
        String subject = "Testing";
        String content = "I am happy that you are reading this";
        String htmlContent = "<html><h1>I am happy that you are reading this</h1></html>";
     
        SimpleEmailDemo mailSender = new SimpleEmailDemo();
        try {
            mailSender.sendEmail(recipients, subject, content, null);
         
            mailSender.sendEmail(recipients, subject, htmlContent, "text/html");
        } catch (MessagingException e) {
            System.out.println(e.getMessage());
        }
    }
}

                                            > Next

References:

1. Email in Java - the JavaMail API (2): Multipart and attachment
2. Java - Sending Email
3. JavaMail API – Sending Email Via Gmail SMTP Example

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

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

The sign function of SQL

The SQL sign function returns -1, 0, or 1 when the corresponding field of a table in the database is numeric and the value is negative, 0, or positive.

For example

          SELECT sign (dailyChange) PriceChange from PRICE where DATE = to_date('03/21/2014', 'MM/dd/yyyy');

If on March 21, 2014, the price was decreased, that is the dailyChange is a negative value, the output of the query is -1; if the price did not change, the output is 0; and if the price was increased, the output of the query is 1.

Another example

          SELECT sign(TotalCharge - Paid) OweMoney from ORDER where customer_ID = 5588;

If the customer paid less than the total charge, the output is 1; if the customer paid the exact amount of total charge, the output is 0; and if the customer paid more than the total charge, the output is -1.

References
1. ORACLE/PLSQL: SIGN FUNCTION

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

                        
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.

The decode function of SQL

The SQL decode function assigns a value to the output field according to the corresponding field value of a table in the database. For example

          SELECT decode(ID, 1, 'Apple', 2, 'Pear', 3, 'Papaya', 'Others') Fruit, PRICE from FRUIT;

The output has two columns, Fruit and PRICE. When the ID value in the FRUIT table in the database is 1 the Fruit value in the output will be Apple; when the ID is 2, the Fruit value will be Pear; when the ID value is 3, the Fruit value will be Papaya; and when the ID in the FRUIT table is neither 1 nor 2 nor 3, the Fruit value in the output. is Others.

References:

1. Decode

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

                        
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 6, 2014

Read from and write to the command line in Java

A. Read from the command line

1. The Scanner
          Scanner theScanner = new Scanner(System.in);
          if (theScanner.hasNextLine()) {
                     String input = theScanner.nextLine();
           }

2. The BufferedReader and the InputStreamReader
           BufferedReader theReader = new BufferedReader(
                                  new InputStreamReader(System.in));
           String line = theReader.readLine();

3. The Console
          Console theConsole = System.Console();
          if (theConsole != null) {
                    String line = theConsole.readLine();
                    char[] password = theConsole.readPassword("Enter your password: ");
                    ............
                    Arrays.fill(password, ' ');
          }

B. Write to the command line

1. The System.out
           System.out.println("The word to write");

2. The Console
           Console theConsole = System.Console();
           if (theConsole != null) {
                      theConsole.format("Enter 1 to continue, 2 to exit");
           }

References:

1. I/O from the Command Line

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

                        
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.

Read from and write to a file in Java (2): other commonly used methods

The most commonly handy methods for reading from and writing to a file are in the java.nio.file.Files class, which was introduced in Java 7. The following methods had been mostly used before the Files class was introduced.

A. Read from a file

          File theFile = new File("<directory>/<file name>");

1. The Scanner        
           Scanner scanner = new Scanner(theFile);
           while (scanner.hasNextLine()) {
                     System.out.println(scanner.nextLine());
           }

2. The BufferedReader and FileReader
          BufferedReader theReader = new BufferedReader(
                               new FileReader(theFile));
          String line = "";
          while ((line = theReader.readLine()) != null) {
                   System.out.println(line);
          }

3. The InputStreamReader and FileInputStream
          CharSet cs = CharSet.forName(System.getProperty("file.encoding"));
          InputStreamReader theReaer = new InputStreamReader(
                            new FileInputStream(theFile), cs);
          int char = -1;
          while ((char = theReader.read()) != -1) {
                     System.out.println(char);
          }

4. The BufferedInputStream and FileInputStream
          BufferedInputStream bis = new BufferedInputStream(
                             new FileInputStream(theFile));
           byte[] theBytes = new byte[theFile.length()];
           bis.read(theBytes, 0, theBytes.length);

B. Write to a file

          File theFile = new File("<directory>/<file name>");

1. The PrintWriter, BufferedWriter, and FileWriter
          PrintWriter pw = new PrintWriter(
                              new BufferedReader(
                              new FileWriter(theFiel, true)));
          pw.println("The word to write");

2. The OutputStreamWriter and the FileOutputStream
          OutputStreamWriter osw = new OutputStreamWriter(
                               new FileOutputStream(theFile, true));
           String theString = "The word to write";
           osw.write(theString, 0, theString.length());

3. The BufferedOutputStream and the FileOutputStream
           BufferedOutputStream bos = new BufferedOutputStream(
                                 new FileOutputStream(theFile, true));
           byte[] theBytes = (new String("The word to write")).getBytes();
           bos.write(theBytes, 0, theBytes.length);

           Previous <

References:

1. Read from and write to a file in Java (1): java.nio.file.Files
2. Read from and write to the command line in Java
3. Java communications over network
4. Reading, Writing, and Creating Files
5. Java IO Tutorial

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

                        
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, May 5, 2014

Read from and write to a file in java (1): java.nio.file.Files

The Files class was introduced in Java 7. It contains only static methods that are convenient to use for operations on a file.

A. Read from a file

          Path theFile = FileSystems.getDefault().getPath("<dirctory>", "<file name>");

1. the readAllLines method
           List<String> allLines = Files.readAllLines(theFile);

2. the newBufferedReader
            BufferedReader reader = Files.newBufferedReader(theFile);
            String line = "";
            for ((line = reader.readLine()) != null) {
                      System.out.println(line);
           }

3. the lines method
          Stream<String> lineStream = Files.lines(theFile);
          List<String> lineList = lineStream.collect(Collectors.toList());

4. the readAllBytes method
          byte[] allByes = Files.readAllBytes(theFile);

5. the newInputStream method
          InputStream is = Files.newInputStream(theFile);
          byte[] isBytes = new byte[Files.size(theFile)];
          is.read(isBytes); //read the file to the byte array

6. the newByteChannel method
          //The advantage of using SeekableByteChannel is that it allows you
          //to set an arbitrary position to start reading and writing
          SeekableByteChannel sbc = Files.newByteChannel(theFile);
          String encode = System.getProperty("file.encoding");
          ByteBuffer theBuffer = ByteBuffer.allocate(theFile.toFile().length());
          sbc.read(theBuffer);
          theBuffer.reWind();
          String theString = CharSet.forName(encode).decode(theBuffer).toString();

B. Write to a file

          Path theFile = FileSystems.getDefault().getPath("<dirctory>", "<file name>");

1. the newBufferedWriter method
          BufferedWriter writer = Files.newBufferedWriter(theFile);
          PrintWriter pw = new PrintWriter(writer);

2. the newOutputStream method
          OutputStream os = Files.newOutputStream(theFile);

3. the write method
          byte[] theBytes = (new String("The words to write")).getBytes();
          Files.write(theFile, theBytes);

4. the newByteChannel method
          SeekableByteChannel sbc = Files.newByteChannel(theFile);
          byte[] theBytes = (new String("The words to write")).getBytes();
          ByteBuffer theBuffer = ByteBuffer.wrap(theBytes);
          sbc.write(theBuffer);

                              > Next

References:

1. Read from and write to a file in Java (2): Other commonly used methods
2. Read from and write to the command line in Java
3. Java communications over network
4. Class Files

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

                        
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.