Updates from July, 2012 Toggle Comment Threads | Keyboard Shortcuts

  • Subinkrishna Gopi 8:17 pm on July 2, 2012 Permalink |
    Tags: , input, io, , , output,   

    My most favorite methods – part 2 

    Okay, here’s the second one. And it took me a few months to write this one 😛

    /**
     * Copies from an {@link InputStream} to an {@link OutputStream}
     *
     * @param from
     * @param to
     */
    public static void copyStream(InputStream from, OutputStream to)
    {
    	byte[] contents = null;
    	int count = -1;
    
    	if ((null != from) && (null != to))
    	{
    		try
    		{
    			contents = new byte[1024];
    			while (-1 != (count = from.read(contents)))
    			{
    				to.write(contents, 0, count);
    			}
    		}
    		catch (Exception e)
    		{
    			e.printStackTrace();
    		}
    		finally
    		{
    			contents = null;
    		}
    	}
    }
    

    This method copies the contents from the input stream to the output stream. Do I need to explain more?

     
    • Andy Res 9:14 pm on July 2, 2012 Permalink

      It’s funny the way how you write the condition in the if and while loop, like you are checking the “null” and “-1” against your variables, which seems unusual for me. 🙂
      I would write instead if(from!=null), and while((count=from.read(contents))!=-1) ..

    • Subinkrishna G 11:09 am on July 3, 2012 Permalink

      This is one practice that I follow from beginning 😉

  • Subinkrishna Gopi 5:56 pm on October 18, 2010 Permalink |
    Tags: , DBMS, , ejb3, entity, hibernate, , ORM, query, , session   

    How-to: Write a named query for an entity bean with composite key 

    I was working on an EJB3 project where I had to write an entity bean with a composite primary key. And I needed to write a named query to which had to use a sub set of the composite key. And this is what I did.

    The entity bean and the composite key:

    import javax.persistence.Column;
    import javax.persistence.EmbeddedId;
    import javax.persistence.Entity;
    import javax.persistence.NamedQueries;
    import javax.persistence.NamedQuery;
    import javax.persistence.Table;
    
    @Entity
    @Table (name = "myTable")
    public class MyEntityBean implements Serializable
    {
        @EmbeddedId
        private MyCompositeKey key;
    
        // Other instance members
    
        @Column (name = "value")
        private String value;
    
        // Getters & setters
        ...
    }
    
    import java.io.Serializable;
    import javax.persistence.Column;
    import javax.persistence.Embeddable;
    
    @Embeddable
    public class MyCompositeKey implements Serializable
    {
        @Column (name = "key1", nullable = false)
        private String key1;
    
        @Column (name = "key2", nullable = false)
        private String key2;
    
        // Getters & setters
        ....
    }
    

    The equivalent database table will look like:

    +---------------+--------------+------+-----+---------+-------+
    | Field         | Type         | Null | Key | Default | Extra |
    +---------------+--------------+------+-----+---------+-------+
    | key1          | varchar(255) | NO   | PRI |         |       |
    | key2          | varchar(255) | NO   | PRI |         |       |
    | value         | varchar(255) | YES  |     |         |       |
    +---------------+--------------+------+-----+---------+-------+
    

    Writing a named query which makes use of the elements of the composite key is a li’l tricky. Take a look at the following SQL statement which tries to fetch all the records from the table for a matching key1.

    SELECT * FROM myTable WHERE key1='some value';
    

    Embedding the named query in MyEntityBean.

    @Entity
    @Table (name = "myTable")
    @NamedQueries
    ({
        @NamedQuery(
            name = "myQuery",
            query = "SELECT FROM MyEntityBean b WHERE key.key1 = :key1" )
    })
    public class MyEntityBean implements Serializable
    {
        ...
    }
    

    We should be careful about the use of the variable name in the named query. In the named query, we are supposed to use the name of the composite key exactly the same as what we have specified in the bean.

    This query can be accessed from a session bean with the help of EntityManager.

    import javax.ejb.Remote;
    import javax.ejb.Stateless;
    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
    import javax.persistence.Query;
    
    @Remote
    @Stateless (name = "MySessionBean")
    public class MySessionBeanImpl implements SessionBean
    {
        @PersistenceContext
        private EntityManager entityManager;
    
        public void myMethod(String key)
        {
        	Query aQuery = null;
    
        	aQuery = this.entityManager.createNamedQuery("myQuery");
            aQuery.setParameter("key1", key);
    
            List resultList = aQuery.getResultList();
    
            .....
        }
    }
    

    Hope this helps. Have a good day 🙂

     
  • Subinkrishna Gopi 11:59 am on July 30, 2010 Permalink |
    Tags: , code snippet, commons, cookie, , httpclient, , networking, proxy,   

    HttpClient (Apache commons) code sample 

    I was playing around with Apache commons Http utilities the last day. I used to use the java.net.* APIs to satisfy my HTTP(s) needs.

    Here is a sample code which I wrote which takes a URL as input, sets the basic request parameters (e.g. cookie string) and set the proxy settings along with the user credentials.

    import org.apache.commons.httpclient.Credentials;
    import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
    import org.apache.commons.httpclient.Header;
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.UsernamePasswordCredentials;
    import org.apache.commons.httpclient.auth.AuthScope;
    import org.apache.commons.httpclient.methods.GetMethod;
    import org.apache.commons.httpclient.params.HttpMethodParams;
    
    public class HttpClientTest
    {
        public static void main(String[] args)
        {
            HttpClient client = null;
            GetMethod getMethod = null;
            int responseCode = -1;
            byte[] responseStream = null;
    
            String urlString = "http://www.facebook.com";
            String cookieString = null;
    
            try
            {
                // Creating the GetMethod instance
                getMethod = new GetMethod(urlString);
    
                // Retries to establish a successful connection the specified number
                // of times if the initial attempts are not successful.
                getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                        new DefaultHttpMethodRetryHandler(1, false));
                getMethod.getParams().setParameter("http.socket.timeout", new Integer(5000));
                getMethod.setRequestHeader(new Header("Cookie", "<COOKIE_STRING>"));
    
                // Creating an HttpClient instance
                client = new HttpClient();
    
                // Proxy settings: Configures the proxy host, port & user
                // credentials and the scope of the credentials.
                client.getHostConfiguration().setProxy("<HOST>", <PORT>);
                Credentials credentials = new UsernamePasswordCredentials
                    ("<USERNAME>", "<PASSWORD>");
                AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT);
                client.getState().setProxyCredentials(scope, credentials);
    
                // Sets the user-agent for the client instance
                client.getParams().setParameter("http.useragent", "<USER_AGENT>");
    
                // Sends the GET request and gets the response
                responseCode = client.executeMethod(getMethod);
                responseStream = getMethod.getResponseBody();
    
                System.out.println("Response Code: " + responseCode);
                System.out.println("Response Body: \n" + new String(responseStream));
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
            finally
            {
                getMethod.releaseConnection();
                client = null;
            }
        }
    }
    

    P.S. Did I mention that this is test code? 🙂

    Note: I was looking for an API set which does make use of its own Socket level implementation. I don’t think HttpClient got it’s own implementation as it claims to be 100% Java. If you know any API set which performs better than java.net.* APIs please feel free to share it.

     
  • Subinkrishna Gopi 4:51 pm on June 23, 2010 Permalink |
    Tags: cache, , distributed cache, ehcache,   

    Distributed Ehcache – RMI replication (configuration) 

    I am having some fun with Ehcache esp. in distributed caching. Distributed caching is really important in a clustered environment. Read more about distributed caching here – http://ehcache.org/documentation/distributed_caching.html.

    I have downloaded Ehcache 2.1 from http://sourceforge.net/projects/ehcache/files/ (ehcache-2.1.0-distribution.tar.gz, 48 mb approx.) which contains Ehcache core and the Terracotta libraries. Once if we have these libraries, we can configure the caches, peers and listeners. I have created a basic cache – MyCache – and my configuration file looks like this:

    <?xml version="1.0" encoding="UTF-8"?>
    
    <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:noNamespaceSchemaLocation="ehcache.xsd"
             updateCheck="true" monitoring="autodetect"
             dynamicConfig="true" >
    
        <diskStore path="java.io.tmpdir"/>
        <cacheManagerEventListenerFactory class="" properties=""/>
    
        <defaultCache
               maxElementsInMemory="0"
               eternal="false"
               timeToIdleSeconds="1200"
               timeToLiveSeconds="1200">
        </defaultCache>
    
            <!-- For RMI replication (Setting the peer provider factory) -->
    	<cacheManagerPeerProviderFactory
    		class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
    		properties="peerDiscovery=manual, rmiUrls=//remoteHostIpAddress:40000/MyCache"
    		propertySeparator="," />
    
    	<!-- For RMI replication (Setting the peer listener factory) -->
    	<cacheManagerPeerListenerFactory
                class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"
                properties="hostName=localMachineIpAddress, port=40000, socketTimeoutMillis=120000"
                propertySeparator=","/>
    
    	<cache name="MyCache"
    		maxElementsInMemory="1000"
    		eternal="false"
    		overflowToDisk="true"
    		diskSpoolBufferSizeMB="20"
    		timeToLiveSeconds="3000"
    		timeToIdleSeconds="3000"
    		memoryStoreEvictionPolicy="LFU">
    
    		<!-- Cache event listener -->
    		<cacheEventListenerFactory
    			class="subin.cache.listener.factory.CacheEventListenerFactoryImpl"
    			properties="" />
    
    		<!-- RMI replication listener -->
    		<cacheEventListenerFactory
            	class="net.sf.ehcache.distribution.RMICacheReplicatorFactory"
            	properties="replicateAsynchronously=true,
    		         replicatePuts=true,
    		         replicatePutsViaCopy=true,
    		         replicateUpdates=true,
    		         replicateUpdatesViaCopy=true,
    		         replicateRemovals=true" />
    
    		<!-- RMI Cache bootstrap -->
    		<bootstrapCacheLoaderFactory
    			class="net.sf.ehcache.distribution.RMIBootstrapCacheLoaderFactory"
    			properties="bootstrapAsynchronously=true, maximumChunkSizeBytes=5000000"
    			propertySeparator="," />
    
    	</cache>
    
    </ehcache>
    

    Initializing the CacheManager & Accessing the cache

    // Testing the cache creation in ver 2.1
    CacheManager manager = new CacheManager("/path/to/config/file.xml");
    
    // Get the instance of "MyCache"
    Cache myCache = manager.getCache("MyCache");
    
    // Add an element to "MyCache". Its preferred to have both key and value
    // serializable
    Element aCacheElement = new Element(key, value);
    myCache.put(aCacheElement);
    

    Useful Links

    RMI replication: http://ehcache.org/documentation/distributed_caching_with_rmi.html
    Configuration: http://ehcache.org/documentation/configuration.html

     
  • Subinkrishna Gopi 3:28 pm on March 25, 2010 Permalink |
    Tags: authentication, base 64, encoding, , , security,   

    Handling HTTP authentication in Java 

    Google Chrome (Ubuntu 9.10)

    Microsoft IE 8 (Windows XP)

    Most of us might have got this pop up when we browse through some websites – especially in intranets. And it’s perfectly fine for the administrator (a.k.a. webmaster) to put such restrictions on users to enhance the information security. Because that’s what a security engineer is expected to do !

    But what if we have to access the resource through our Java code? How to we handle that? I have faced this issue when I was writing a module to crawl through a secured website using HTTPunit.

    We just need to set the Authorization header with the Base64 encoded username and password. Here is a sample code:

    String usernameAndPassword = "myUsername" + ":" + "myPa$$word";
    String encodedString = new sun.misc.BASE64Encoder().encode (usernameAndPassword.getBytes());
    httpConnection.setRequestProperty("Authorization", "Basic " + encodedString);
    

    How Base 64 encoding works?

     
c
Compose new post
j
Next post/Next comment
k
Previous post/Previous comment
r
Reply
e
Edit
o
Show/Hide comments
t
Go to top
l
Go to login
h
Show/Hide help
shift + esc
Cancel