Tagged: java Toggle Comment Threads | Keyboard Shortcuts

  • Subinkrishna Gopi 8:17 pm on July 2, 2012 Permalink |
    Tags: , input, io, java, , 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?

    Advertisements
     
    • 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 4:37 pm on April 10, 2012 Permalink |
    Tags: , favorite, java,   

    My most favorite methods – Part 1 

    This is my most favorite/commonly used/useful method. This method checks if the given string is valid or not.

    /**
    * Checks if the given string is valid or not.
    *
    * @param aString
    * @return {@code true} if {@code aString} is not {@code null} and if it's
    *         'trimmed' length is more than 0, else {@code false}
    */
    static boolean isValidString(String aString)
    {
       return ((null != aString) && (aString.trim().length() > 0));
    }
    
     
    • Stuart 4:48 pm on April 10, 2012 Permalink

      I prefer the StringUtils.isNotBlank() from org.apache.commons-lang3

      Also, you shouldn’t really be comparing strings with “!=” or “==” should you?

    • Subinkrishna G 11:15 am on April 18, 2012 Permalink

      I am not a big fan of Apache Commons 😉 Yes, I agree that we should not compare the strings using ‘!=’or ‘==’. But here I am not comparing the strings, in fact I am doing a null check.

    • Stuart 11:39 am on April 18, 2012 Permalink

      Personally I think having all the little helper functions lumped into one place is quite useful, but then I write a lot of small programs, so having easy access to lang3 with maven does make my life a little easier!

      Doh! of course, null comparison, point taken 🙂

  • Subinkrishna Gopi 7:24 pm on May 20, 2011 Permalink |
    Tags: , , editor, ide, intellij idea, java, new found love   

    IntelliJ IDEA, Me & the new found love! 

    And I am falling in love with IntelliJ IDEA, finally. I was using Eclipse IDE for the last five years. Eclipse is awesome, period. But everything is too easy with Eclipse. You will get plugins for all possible things to do with it. So, after spending five long years with Eclipse (who is still my best friend) I decided to try something new. I downloaded the community version of IntelliJ IDEA. I am really impressed by the features it offer though it’s a subset of the actual offering! It made me feel like a programmer!

    Picture: My Hello World! program 🙂

    image

     
  • Subinkrishna Gopi 11:11 am on October 28, 2010 Permalink |
    Tags: , , , guide, how-to, java, simple, tutorial   

    Today’s read: Get Started Developing for Android with Eclipse 

    This one is pretty good. Perhaps one of the very useful how-tos! I read this article in smashingmagazine.com a few days back. I was thinking of sharing it from that moment. It’s better late than never. The article talks a lot of things. From about installing the Android SDK, configuring it and even about writing a sample application.

    There’s a lot to get excited about in mobile application development today. With increasingly sophisticated hardware, tablet PCs and a variety of software platforms (Symbian OS, iOS, WebOS, Windows Phone 7…), the landscape for mobile developers is full of opportunities — and a little complex as well.

    So much choice can be overwhelming when you just want to get started building mobile applications. Which platform should you choose? What programming language should you learn? What kit do you need for your planned project? In this tutorial, you’ll learn how to start writing applications for Android, the open-source mobile operating system popularized by Google.

    Source: Smashing Magazine

    Read the article | http://developer.android.com

     
  • Subinkrishna Gopi 5:56 pm on October 18, 2010 Permalink |
    Tags: , DBMS, , ejb3, entity, hibernate, java, 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 🙂

     
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