Read a *.properties file from a *.jar file

jarwell this is an embrassing thing to share but this is the fact, that I found difficulties when i tried to read *.properties file when it's already in *.jar file first, I tried to load the properties file with this way :

   1: URL url = InOut.class.getClassLoader().getResource("appSetting/test.properties");
   2: File f = new File(url.toURI());
   3: FileInputStream fis =  new FileInputStream(f);
   4: Properties prop  = new Properties();
   5: prop.load(fis);
   6: System.out.println(prop.getProperty("test"));

there's no problem when I try to run it from Eclipse, but when I already have exported it into a .jar file and try to run it, this error hit my screen... –____–

java.lang.IllegalArgumentException: URI is not hierarchical
at java.io.File.<init>(File.java:380)
at inOutTask.InOut.main(InOut.java:49)

well, I tried to load a Properties file from File object initiated with URI. And the URI comes from URL object that I have created in the first line : jar:file:/home/123/abc/test.jar!/appSetting/test.properties. as you can see it tried to load a properties file in a jar file. in my opinion we can't access file in a file.. so that's the problem. Actually method load() in line 5 accept an InputStream object, so why it could accept FileInputStreamObject? It's because FileInputStream is an extended class from InputStream. so to get around this problem I just need to pass an InputStream object to method load() with this way :


   1: InputStream is = ClassName.class.getClassLoader().getResourceAsStream("appSetting/test.properties");
   2: Properties prop  = new Properties();
   3: prop.load(is);
   4: System.out.println(prop.getProperty("test"));

or


   1: InputStream is = ClassName.class.getResourceAsStream("/appSetting/test.properties");
   2: Properties prop  = new Properties();
   3: prop.load(is);
   4: System.out.println(prop.getProperty("test"));

I use ClassName.class because I called this line of code from a main method, so if want to call this getResourceAsStream() method from a POJO class just change it into this.getClass(). the difference between those two are :

  • the first way ClassLoader.getResourceAsStream(path) will consider all paths to be absolute paths. So calling String.getClassLoader.getResourceAsString("myfile.txt") and String.getClassLoader.getResourceAsString("/myfile.txt") will both look for a file in your classpath at the following location: "./myfile.txt"
  • the second way in Class.getResourceAsStream(path), the path is interpreted as a path local to the package of the class you are calling it from. For example calling, String.getResourceAsStream("myfile.txt") will look for a file in your classpath at the following location: "java/lang/myfile.txt". If your path starts with a '/', the it will be considered an absolute path, and will start searching from the root of the classpath. So calling String.getResourceAsStream("/myfile.txt") will look at the following location in your in your class path "./myfile.txt

Setup POSTGRESQL with IDENT Authentication method

postgresql Yoo... this thing takes several hours for me to make it works –____-,
I just can’t find a good example about this.
IDENT Authentication indeed really an evil one. (he said that) >:).

So here we go :

  1. assuming that you already have installed your own POSTGRESQL on your workstation, if no, then this is a short step you need to take :

    #yum install postgresql

    #yum install pgadmin3 (optional)

    by default, you can install POSTGRESQL when you installed fresh Fedora 14 (ehhmm... advertise :D). For the complete step you can read this.

  2. For the first time using POSTGRESQL after installation you would need to do initialization

    #service <postgresql_service_name> initdb

  3. Ok, by default if you installed new version of POSTGRESQL e.g "PostgreSQL 8.4.5 on i386-redhat-linux-gnu" it will set the local and host authentication type into IDENT. Try to open the pg_hba.conf file : (you need root acces to edit this file)

    # nano /etc/var/lib/pgsql/data/pg_hba.conf

    then you'll find this part in it :

    # TYPE DATABASE USER CIDR-ADDRESS METHOD 
    # "local" is for Unix domain socket connections only 
    local all all ident
    # IPv4 local connections: 
    host all all 127.0.0.1/32 ident
    # IPv6 local connections: 
    host all all ::1/128 ident

    The ident authentication method works by inspecting the client's operating system user name and determining the allowed database user names by using a map file that lists the permitted corresponding user name pairs. You could read more about IDENT from here.

  4. When we used IDENT authentication, we'll need IDENT server, it's used to answer questions like "What user initiated the connection that goes out of your port X and connects to my port Y?", now I'm using OIDENTD, to install OIDENTD you just need :

    #yum install oidentd

    you can read more about oidentd from here

  5. Ok, let's begin to editing all files that necessary to makes IDENT Authentication works, start from postgresql's ident file :

    # nano /var/lib/pgqsql/data/pg_ident.conf

    add this configuration at the lowest line :

    # MAPNAME     SYSTEM-USERNAME    PG-USERNAME 
    test      uzer              postgres

    now open again pg_hba.conf then add mapname into it :

    # TYPE  DATABASE    USER        CIDR-ADDRESS          METHOD 
    # "local" is for Unix domain socket connections only 
    local   all         all                               ident map=test
    # IPv4 local connections: 
    host    all         all         127.0.0.1/32          ident map=test
    # IPv6 local connections: 
    host    all         all         ::1/128               ident

    you musn’t skip this step or you will receive error when you try to connect to your database:

    LOG: provided username (postgres) and authenticated username (uzer) don't match
    FATAL: Ident authentication failed for user "postgres"

  6. Oidentd used default configuration oidentd.conf, it should be in /etc/oidentd.conf, but I don't know why, on my local /etc, oidentd.conf doesn't exist. So, I need to create it by my self with

    #nano /etc/oidentd.conf

    and if fill it with :

    default {
    default {
    deny spoof
    deny spoof_all
    deny spoof_privport
    allow random_numeric
    allow numeric
    allow hide
    }
    }

    user uzer {
    default {
    allow spoof
    allow spoof_all
    allow random
    allow hide
    }
    }

    I just add these lines to oidentd.conf but sorry, I can't explain anything about this, I can't get any other details except this.

  7. Everything is set, now we are ready. Run Oidentd and postgresql services with this command in terminal :

    #oidentd -C /etc/oidentd.conf
    #service postgresql start

yapz.. that's all we need to used IDENT authentication method in POSTGRESQL and I am really looking forward your comment, especially about point six. Well, otherwise if you don’t to do the setup, you can just change the IDENT to md5 to save your time configuring POSTGRESQL. Thanks for reading anyway ... :)

Jet OleDb 4.0 and Office 12.0 Access Database Engine

office2007 Have you ever found problem where you want to edit an office files (*.doc, *.xls, *.docx, *.xlsx) on dekstop without the Office application? yeah, I’m sure this is a common problem found by  developers when their application trying to edit an office file on a server without  (read :  not allowed to install) Office installed on it? :P  and I think nowadays still a lot of developers out there using interop / COM files in their program, unfortunately they can’t just install the COM objects without installing the office on the server.

Well, I suggest you to recode you application, change the codes from using COM object to System.Data.OleDb namespace. Trust me this would get around the licensing issue (read : don’t need to install the Office application) but still you need to makesure you have JetOleDb already installed for Office 2003 and Office 12.0 Access Database Engine for office 2007.

For Jet OleDb 4.0 actually already installed on OS XP, but if you found program failed due on OleDbCommand.Connection due to missing msjetoledb40.dll 2 ways around this:

  1. Reduce your component visibilty, then the "Jet Database OLEDB Support"
    compoent will come into view, and you can add it.
  2. Copy the file "msjetoledb40.dll"
    from a XP Professional (system32), and use "regsvr32" to register it.

You can find out more about Jet OleDb 4.0 from here and you can find out more about Office 12.0 Access Database Engine for office 2007 here.

Coder Girl Lyrics

hp-video-folder-iconCoder girl, yeah I found this song several months ago.. I think it’s a good song for us, Programmer :D, enjoy!

Thank for DALECHASE, this is good :)

Coder Girl Lyrics:

to be the keys underneath her finger tips
Her class makes a brotha's back buffer wanna flip
and be number one on her link list
and get a callback, I'm in all caps
feels like my first hello world
what it is to run with a coder girl
and it ain't hard to like how she writes
with her pretty interface, plus her source is tight
wanna get in where I fit in like a plug-in
this is the true meaning of computer lovin'
She's got a data stack that's straight stunning
No mismatch, exceptions or debuggin
invariably, how would I pass this
when my coder girl grants me root access
basically, she's a certified A+
yo, it's more than just technolust

(chorus)

Feels like my first Hello World 'cause
She's my Coder Girl
Man, I had to dedicate this one
To my Coder Girl

I'll put it like this, so you can understand
She makes me wanna update to be a better man
When we compile she's easy to interpret
A cross-platform version I can work with
She's not wrapped in flash
all she wants is her java and a shell to bash
While, she's a sight to C, plus
Her smile glimmers just like a Ruby does
She could never be subroutine
The high priority process of my machine
Sharper than most chics ya' know
She's not another shallow copy actin' sudo
It's that good type dependancy
I function better with C.G. next to me
and it always leads to an overflow
When it's runtime and we take it slow

Setup AppSetting like .NET in JAVA

Configuration Settings

Hufft… I felt really bothered when build an application in JAVA but I can’t have application configuration with global scope, customizable without recompiling code –___– when usually I got it easily when I build .NET application (which is app.config or web.config). Enough already!! :D So, I decided to create my own simple global configuration.. No more pain… no more sighhhhh hehehe :)) Created with XSD Schema and JAXB. Let’s go to the steps :

  1. if you are using IDE Netbeans 6.8, you need “XML Schema and WSDL” plugin setup first. you can do it following this.
  2. if you done with the first step, then create a new java application project, and add a XSD sample file to customize it as we need.
    image
  3. now we need to code the XML file configuration (AppSetting) and XSD Schema.
      1: <?xml version="1.0" encoding="UTF-8"?>
      2:
      3: <appSetting>
      4:     <setting name="CodeCount" serializeAs="String">
      5:         <value>1000000</value>
      6:     </setting>
      7:     <setting name="CodeCountTotal" serializeAs="String">
      8:         <value>2000000</value>
      9:     </setting>
     10:     <setting name="LettersCount" serializeAs="Integer">
     11:         <value>1</value>
     12:     </setting>
     13:     <setting name="NumbersCount" serializeAs="Integer">
     14:         <value>1</value>
     15:     </setting>
     16:     <setting name="Mix" serializeAs="Boolean">
     17:         <value>true</value>
     18:     </setting>
     19: </appSetting>
     20: 
    now the XSD Schema that following the XML file structure :
      1: <?xml version="1.0" encoding="UTF-8"?>
      2:
      3: <xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">
      4:   
      5:     <xsd:annotation>
      6:         <xsd:documentation xml:lang="en">
      7:             AppSetting for Sample Application Setting.
      8:             Copyright 2010 CodeGear. All rights reserved.
      9:         </xsd:documentation>
     10:     </xsd:annotation>
     11:      
     12:     <xsd:element name="appSetting" type="ApplicationGlobalConfiguration"/>
     13:
     14:     <xsd:complexType name="ApplicationGlobalConfiguration" >
     15:         <xsd:sequence>
     16:             <xsd:element ref="setting" minOccurs="0" maxOccurs="unbounded" />
     17:         </xsd:sequence>      
     18:     </xsd:complexType>
     19:
     20:     <xsd:element name="setting" type="SettingType"/>
     21:
     22:     <xsd:complexType name="SettingType">
     23:         <xsd:sequence>
     24:             <xsd:element name="value" type="xsd:string" />
     25:         </xsd:sequence>
     26:         <xsd:attribute name="name" type="xsd:string" />
     27:         <xsd:attribute name="serializeAs" type="xsd:string" />
     28:     </xsd:complexType>
     29:
     30: </xsd:schema>
     31: 

  4. With JAXB we can generate the class persistence according the XSD Schema we have before. From window Project, add new JAXB Binding.

    image
    then It will create JAXB Binding in your project, right click > Regenerate java Code, to generate the java class persistence.

    image
    If you like, you can move the class persistence to your own package.

  5. Now everything sets. To test it, I create simple code like this :
      1: package AppSetting;
      2:
      3: import com.conf.classpersistence.*;
      4: import java.io.File;
      5: import java.io.IOException;
      6: import java.util.List;
      7: import javax.xml.bind.JAXBContext;
      8: import javax.xml.bind.JAXBElement;
      9: import javax.xml.bind.JAXBException;
     10: import javax.xml.bind.Unmarshaller;
     11: /**
     12:  *
     13:  * @author tuta87
     14:  */
     15: public class Main {
     16:
     17:     /**
     18:      * @param args the command line arguments
     19:      */      
     20:     public static void main(String[] args) throws JAXBException, IOException {
     21:         JAXBContext jaxbContext = JAXBContext.newInstance("com.conf.classpersistence");
     22:         Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
     23:
     24:         JAXBElement<ApplicationGlobalConfiguration> appSettingElement =
     25:                 (JAXBElement<ApplicationGlobalConfiguration>)unmarshaller.unmarshal(
     26:                     new File("src/com/conf/xml/AppSetting.xml"));
     27:
     28:         ApplicationGlobalConfiguration appSetting = appSettingElement.getValue();
     29:         appSetting.setupHashtable();
     30:         System.out.println("Configuration count : " + appSetting.getSetting().size());
     31:         List<SettingType> listOfAllSetting = appSetting.getSetting();
     32:         for (SettingType setting : listOfAllSetting){
     33:             System.out.print("Setting Name :  " + setting.getName());
     34:             System.out.print(", DataType :  " + setting.getSerializeAs());
     35:             System.out.println(", Value :  " + setting.getValue());
     36:         }
     37:     }
     38:
     39: }
     40: 
    it will print out this to your console :

    Configuration count : 5
    Setting Name : CodeCount, DataType : String, Value : 1000000
    Setting Name : CodeCountTotal, DataType : String, Value : 2000000
    Setting Name : LettersCount, DataType : Integer, Value : 1
    Setting Name : NumbersCount, DataType : Integer, Value : 1
    Setting Name : Mix, DataType : Boolean, Value : true
    BUILD SUCCESSFUL (total time: 1 second)

    as you can see from the sample code on point five, all configurations saved in List<SettingType>. Now to make it more easier, I want all configuration putted in Hashtable<K,V> object. So it will makes clear about the data type every setting we have.

  6. Open the ApplicationGlobalConfiguration.java, we need to add new Hashtable<K,V> property on it :
      1: package com.conf.classpersistence;
      2:
      3: import java.util.ArrayList;
      4: import java.util.Hashtable;
      5: import java.util.List;
      6: import javax.xml.bind.annotation.XmlAccessType;
      7: import javax.xml.bind.annotation.XmlAccessorType;
      8: import javax.xml.bind.annotation.XmlType;
      9:
     10: @XmlAccessorType(XmlAccessType.FIELD)
     11: @XmlType(name = "ApplicationGlobalConfiguration", propOrder = {
     12:     "setting","hashSetting"
     13: })
     14: public class ApplicationGlobalConfiguration {
     15:
     16:     protected List<SettingType> setting;
     17:     private Hashtable<String, Object> hashSetting;
     18:
     19:     public List<SettingType> getSetting() {
     20:         if (setting == null) {
     21:             setting = new ArrayList<SettingType>();
     22:         }
     23:         return this.setting;
     24:     }
     25:
     26:     public void setupHashtable(){      
     27:         List<SettingType> listOfAllSetting = this.getSetting();
     28:          for (SettingType setting : listOfAllSetting){
     29:              if (setting.getSerializeAs().equals("String"))
     30:                  this.getHashSetting().put(setting.getName(), setting.getValue());
     31:              else if (setting.getSerializeAs().equals("Integer"))
     32:                  this.getHashSetting().put(setting.getName(), Integer.parseInt(setting.getValue()));
     33:              else if (setting.getSerializeAs().equals("Double"))
     34:                  this.getHashSetting().put(setting.getName(), Double.parseDouble(setting.getValue()));
     35:              else if (setting.getSerializeAs().equals("Boolean"))
     36:                  this.getHashSetting().put(setting.getName(), Boolean.parseBoolean(setting.getValue()));
     37:           
     38:         }     
     39:     }
     40:
     41:     public Object getSettingValueByName(String settingName){
     42:         return (this.getHashSetting().get(settingName));
     43:     }
     44:
     45:     /**
     46:      * @return the hashSetting
     47:      */
     48:     public Hashtable<String, Object> getHashSetting() {
     49:         if (this.hashSetting == null)
     50:             return (hashSetting = new Hashtable<String, Object>());
     51:         else
     52:             return hashSetting;
     53:     }
     54: }
     55: 
    You need to pay attention on line :
    Line 12 : add “hashSetting”, it according the property name on Line 17
    Line 17 : add new property
    Line 26 : a method used to setup Hashtable value and key
    Line 41 : a method used to get a value by Setting Name
    Line 48 : a method used to get the Hashtable object.

  7. Now to test it you can do it with this sample code:
      1: boolean bl = ((Boolean)appSetting.getHashSetting().get("Mix")).booleanValue();
      2: String str = (String)appSetting.getHashSetting().get("CodeCountTotal");
      3: int i = (Integer)appSetting.getHashSetting().get("NumbersCount");
      4:       
      5: System.out.print("Try to get Mix value :  " + appSetting.getSettingValueByName("Mix"));

DONE! now i have my own AppSetting on my JAVA application. If you need the sample source of this post, you can take it from my DataBox. Enjoy… :)

fb:comments

facebook_logo2 Hi guys!! Lately I found something more interesting then an ordinary Likes button, something that makes my blog more connected to the other network via facebook open graph it was facebook Comments. The way I implemented facebook comments on my blog, it’s not much different than facebook Likes button. After googling for a while, I found several related sources that describing about facebook comments i.e. here. :D * I feel weird when trying to pointing something with only word, when I usually use my hand :P. Ok, enough talk, lets go to the steps :

  1. First, we need to create our own facebook application, you can do it here! from there, it will assist you to create your own facebook application.

    image

    Type your application name, and choose Agree radiobutton, then click Create Application.

    image

    Now, you can customize your application setting, the only things I did in this steps just choosing logo and icon for my facebook application, click Save Changes.

    image

    Finish, your application ready to use now.

  2. We need to place an initialization facebook javascript sdk, then you need to set the application id (you can get it from first step)
    <div id="fb-root"></div>
    <script>
      window.fbAsyncInit = function() {
        FB.init({appId: 'your app id', status: true, cookie: true,
                 xfbml: true});
      };
      (function() {
        var e = document.createElement('script'); e.async = true;
        e.src = document.location.protocol +
          '//connect.facebook.net/en_US/all.js';
        document.getElementById('fb-root').appendChild(e);
      }());
    </script>
  3. the last thing you need to do, put the <fb:comments/> tag on the place you want on your blog.
    <fb:comments expr:xid='data:post.id' width='400'/>
    This code only works for blog with blogger engine, where attribute xid indicates an unique id for every post I created on my blog.

Yapz!!! finish. Now I have my own facebook comments box on my blog :D

image

when I posted a comment on it, it will automatically putted on my news feed.

image

Nice and easy, isn’t it? :)

Facebook Open Graph (Update)

image Alright!! Here it is, guys. after several days, now I know how to implemented Facebook Open Graph on my blog. First of all, my blog engine is Blogger, so I think this not gonna work on another blog engine like Wordpress. The implementation is very, very, very simple. It was just adding some line on my blog code and taaddaaa!!! I have facebook Likes button on my blog.

Ok, Here we go :

  1. First, open your blogger panel and choose edit layout, so you can take your blog layout code.

    image
  2. Add open graph and facebook namespace at the <html> tag as a xmlns, so it would be look a like :
      1: <html expr:dir='data:blog.languageDirection'
      2:  xmlns='http://www.w3.org/1999/xhtml'
      3:  xmlns:b='http://www.google.com/2005/gml/b'
      4:  xmlns:data='http://www.google.com/2005/gml/data'
      5:  xmlns:expr='http://www.google.com/2005/gml/expr'
      6:  xmlns:og="http://opengraphprotocol.org/schema/"
      7:  xmlns:fb="http://www.facebook.com/2008/fbml">

  3. Then put this code on your head part :
      1: <b:if cond='data:blog.pageType == &quot;item&quot;'>
      2:  <meta property='og:title' expr:content='data:blog.pageName'/>  
      3:  <meta property='og:url' expr:content='data:blog.url'/>
      4:  <meta property='og:type' content='blog'/>
      5:  <meta property='og:site_name' content='Zouota Blog'/>
      6:  <meta property='og:image' content='http://www.freeimagehosting.net/uploads/37eeae1a93.jpg'/>
      7:  <meta property='fb:admins' content='zouota'/>
      8: </b:if>
    Line 1, indicate that the loaded page was an item or a single blog post,
    Line 2, og:title indicate the title of your blog post,
    Line 3, og:url indicate you blog post’s url,
    Line 4, og:type indicate it’s a blog.
    Line 5, og:site_name indicate your Blog Name when it posted on facebook,
    Line 6, og:image indicate your Icon for your blogpost when it posted on facebook,
    Line 7, og:admins, here’s the important thing, indicating a facebook ID who will administering your pages (blog posts).
    The complete reference about this, you can find it here!

  4. At the beginning of <body> part I load facebook Java Scritpt SDK
      1: <script>
      2:    window.fbAsyncInit = function() {
      3:   FB.init({appId: &quot;<data:blog.url/>&quot;, status: true, cookie: true,
      4:      xfbml: true});
      5:    };
      6:    (function() {
      7:   var e = document.createElement('script'); e.async = true;
      8:   e.src = document.location.protocol +
      9:     '//connect.facebook.net/en_US/all.js';
     10:   document.getElementById('fb-root').appendChild(e);
     11:    }());
     12:  </script>

  5. Everything are set. The last thing I need to do is adding facebook “Likes” element. well where you put it, it depends on your blog design.
      1: <div class='endpost'/>   
      2:  <b:if cond='data:blog.pageType == &quot;item&quot;'>
      3:   <fb:like width="450" height="20"/>
      4:  </b:if>
      5: </div>

There you are! when I open one of my blog post :

image

and when I login with my facebook account, it becomes look like :

image

when I click Admin Page, it’s redirecting me to the app.Admin page :

image


So guys, that’s what I do to add facebook Open graph on my blog post page, actually there are severl other thing I need todo to complete the update on facebook, like it said here!

If there's something I missed about this, please let me know and If you like my post about facebook Open Graph, there’s no other thing you need to do, except click my facebook “Likes” button :). Happy “Open Graph” all!