Sunday, December 16, 2012

Print JEditorPane content using Java with header and footer

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package javatest.pritom;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.MessageFormat;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingUtilities;
import javax.swing.text.Document;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;

/**
 *
 * @author User
 */
public class JavaSimpleBrowser extends JPanel {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame("Print Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.getContentPane().add(new JavaSimpleBrowser(), BorderLayout.CENTER);
                frame.setSize(800, 600);
                frame.setLocationByPlatform(true);
                frame.setVisible(true);
            }
        });
    }
   
    private JComponent simpleBrowser;
    private final JEditorPane editorPane;
    private final JScrollPane scrollPane;
    public JavaSimpleBrowser() {
        this.setSize(new Dimension(800, 600));
        this.setPreferredSize(new Dimension(800, 600));
        JPanel pnlM = new JPanel(new BorderLayout());
        this.add(pnlM, BorderLayout.CENTER);
       
        HTMLEditorKit kit = new HTMLEditorKit();
       
        StyleSheet styleSheet = kit.getStyleSheet();
        styleSheet.addRule("body {color:#000; font-family:times; margin: 0px; }");
        styleSheet.addRule("p.line {"
                + "border-width: 3px; border-style: solid; border-color: red;"
                + "font : 10px monaco; padding: 4px; background-color: gray;"
                + "} ");
       
        editorPane = new JEditorPane();
        editorPane.setEditorKit(kit);
        Document doc = kit.createDefaultDocument();
        editorPane.setDocument(doc);
        editorPane.setContentType("text/html");
        editorPane.setText(getHtml());
        editorPane.setEditable(false);
       
        scrollPane = new JScrollPane(editorPane);
        scrollPane.setPreferredSize(new Dimension(780, 500));
        scrollPane.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
       
        pnlM.add(scrollPane, BorderLayout.CENTER);
       
        JButton button = new JButton("Print");
        pnlM.add(button, BorderLayout.NORTH);
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                MessageFormat header = new MessageFormat("Order Details History");               
                MessageFormat footer = new MessageFormat(" Page #{0,number,integer}");
                try {
                    editorPane.print(header, footer);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
    }
   
    private String getHtml() {
        StringBuffer sb = new StringBuffer();
       
        sb.append("<html>");
        sb.append("<body>");
        for(int index = 0; index < 500; index++) {
            sb.append("<p class='line'>I AM IN LINE: "+index+"</p>");
        }
        sb.append("</body>");
        sb.append("</html>");
       
        return sb.toString();
    }
}

Friday, December 14, 2012

Java: Reading and writing text files

package pritom;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * User: pritom
 * Date: 14/12/12
 * Time: 9:28 AM
 * To change this template use File | Settings | File Templates.
 */
public class ReadWriteTextFileJDK7 {

    public static void main(String... aArgs) throws IOException {
        ReadWriteTextFileJDK7 text = new ReadWriteTextFileJDK7();

        //treat as a small file
        List<String> lines = text.readSmallTextFile(FILE_NAME);
        log(lines);
        lines.add("This is a line added in code.");
        text.writeSmallTextFile(lines, FILE_NAME);

        //treat as a large file - use some buffering
        text.readLargerTextFile(FILE_NAME);
        lines = Arrays.asList("Line added #1", "Line added #2");
        text.writeLargerTextFile(OUTPUT_FILE_NAME, lines);
    }

    final static String FILE_NAME = "C:/tmp/input.txt";
    final static String OUTPUT_FILE_NAME = "C:/tmp/output.txt";
    final static Charset ENCODING = StandardCharsets.UTF_8;

    //For smaller files

    List<String> readSmallTextFile(String aFileName) throws IOException {
        System.out.print("***** readSmallTextFile *****\n");
        Path path = Paths.get(aFileName);
        return Files.readAllLines(path, ENCODING);
    }

    void writeSmallTextFile(List<String> aLines, String aFileName) throws IOException {
        System.out.print("***** writeSmallTextFile *****\n");
        Path path = Paths.get(aFileName);
        Files.write(path, aLines, ENCODING);
    }

    //For larger files

    void readLargerTextFile(String aFileName) throws IOException {
        System.out.print("***** readLargerTextFile *****\n");
        Path path = Paths.get(aFileName);
        Scanner scanner =  new Scanner(path, ENCODING.name());
        while (scanner.hasNextLine()){
            //process each line in some way
            log(scanner.nextLine());
        }
    }

    void readLargerTextFileAlternate(String aFileName) throws IOException {
        System.out.print("***** readLargerTextFileAlternate *****\n");
        Path path = Paths.get(aFileName);
        BufferedReader reader = Files.newBufferedReader(path, ENCODING);
        String line = null;
        while ((line = reader.readLine()) != null) {
            //process each line in some way
            log(line);
        }
    }

    void writeLargerTextFile(String aFileName, List<String> aLines) throws IOException {
        System.out.print("***** writeLargerTextFile *****\n");
        Path path = Paths.get(aFileName);
        BufferedWriter writer = Files.newBufferedWriter(path, ENCODING);
        for(String line : aLines){
            writer.write(line);
            writer.newLine();
        }
        writer.flush();
    }

    private static void log(Object aMsg){
        System.out.println(String.valueOf(aMsg));
    }

}
http://www.javapractices.com/topic/TopicAction.do?Id=42 

Thursday, December 13, 2012

Finding real body height using jQuery

function getDocumentHeight() {
    if ($.browser.msie) {
        var $temp = $("<div>")
            .css("position", "absolute")
            .css("left", "-10000px")
            .append($("body").html());

        $("body").append($temp);
        var h = $temp.height();
        $temp.remove();
        return h;
    }
    return $("body").height();
}

Java: iterate through HashMap

Map resultMap = new HashMap();

ResultSet resultSetRegion = s.executeQuery(sSql2);
if(resultSetRegion.next()) {
    resultMap.put( "firstName", "" + resultSetRegion.getString("first_name") );
}

Iterator it = resultMap.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry pairs = (Map.Entry) it.next();
    System.out.println("KEY: "+pairs.getKey()+"\tVALUE: "+pairs.getValue());
}

Run Bash Script Using Java And Get Debug And Error Output

String command = "sudo /usr/bin/some_name.sh";
System.out.println("runBashScriptCommand: " + command);
try {
    Runtime runtime = Runtime.getRuntime();
    Process process = runtime.exec(command);
    printBufferedReaderOutputFromProcess(process);
    process.waitFor();
    return "true";
} catch (Exception ex) {
    System.out.println("EX:" + ex.toString());
    return ex.toString();
}

private void printBufferedReaderOutputFromProcess(Process p) {
    try {
        String s = null;
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
        BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        // read the output from the command
        System.out.println("\n\npHere is the standard output of the command:\n");
        while ((s = stdInput.readLine()) != null) {
            System.out.println(s);
        }
        // read any errors from the attempted command
        System.out.println("Here is the standard error of the command (if any):\n");
        while ((s = stdError.readLine()) != null) {
            System.out.println(s);
        }
    } catch (Exception ex) {
        System.out.println("printBufferedReaderOutputFromProcess:" + ex.toString());
    }
}

Wednesday, December 12, 2012

Height of tab (JTabbedPane) in MAC

Code: 
JTabbedPane paneItem = new JTabbedPane();
JLabel iconInTab = new JLabel(new ImageIcon("myImage.png"));
iconInTab.setPreferredSize(new Dimension(100,80)); 
paneItem.addTab(null,new JPanel());
paneItem.setTabComponentAt(0,iconInTab);
 
I've also try this using html but it did not work either:
paneItem.addTab("<html><p><p><p></html>",new ImageIcon("myImage.png"),new JPanel()) 

Solution:
paneItem.setUI(new BasicTabbedPaneUI());
Also with some features:
paneItem.setTabPlacement(JTabbedPane.TOP);
paneItem.setTabLayoutPolicy(JTabbedPane.WRAP_TAB_LAYOUT);
paneItem.setComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT);

Tuesday, December 11, 2012

Move all files except one

File Structure:
/root/tmp/test
[root@dswing test]# ll
total 12
-rw-r--r-- 1 root root    2 Dec 12 13:41 a.txt
-rw-r--r-- 1 root root    4 Dec 12 13:42 b.txt
-rw-r--r-- 1 root root    0 Dec 12 13:43 c.txt
drwxr-xr-x 2 root root 4096 Dec 12 13:50 ks

Command:
find /root/tmp/test/ -maxdepth 1 -mindepth 1 -type f -not -name c.txt | grep -i txt$ | xargs -i cp -af {} /root/tmp/test/ks

Description:
-maxdepth 1 makes it not search recursively.  
-mindepth 1 makes it not include the /root/tmp/test/ path itself into the result.
-type f means search only for file type.
-not -name c.txt means all files except c.txt
grep -i txt$ means files name ends with txt.