Thursday, 19 March 2015

Spring < form:select /> tag selected option Example

In Spring controller , write below code to bind the <form:select />, <form:option /> or <form:options />, we will use bellow value to render HTML form:select box :

@Controller

@RequestMapping("/")

public TestController{

protected ModelAndView createSelectWithValue(HttpServletRequest request) throws Exception { 
 
        Map cData = new HashMap(); 
 
        Map<String,String> countryList = new LinkedHashMap<String,String>(); 
 
        countryList.put("TX", "Texas");
 countryList.put("IN", "India");
 countryList.put("NY", "New York");
 countryList.put("NJ", "New Jessy");
 cData.put("cList", countryList); 
  
        ModelAndView mav=new ModelAndView();
        mav.addAttribute("selectedCountry","IN"); 
        mav.addAttribute("cList",cData);
        mav.setView("index");
  
        return mav;
  }
}
 
 
index.jsp
 
1) Simply display <form:select />

   <form:select path="c" items="${cList}" />
 
   OR
 
   <form:select path="c">
    <form:options items="${cList}" />
   </form:select> 
 
   OR
 
   <form:select path="c">
   <form:option value="NONE" label="--- Select ---"/>
   <form:options items="${cList}" />
   </form:select> 
    

2) Load with selected value specified
 
   <select id="country" name="country">
    <option value=""></option>
 
      <c:forEach items="${cList}" var="name">
        <c:when test="${name[0]== selectedCountry}">
            <option value="${name[0]}" selected>${name[1]}</option>
        </c:when>
        <c:otherwise>
            <option value="${name[0]}" >${name[1]}</option>
        </c:otherwise>
     </c:forEach>
  </select> 
 
 
 
 

filter array from array with jquery


we have used jQuery.grep() method and jQuery.inArray() method to filter one array from another array.





<html>
<head>

<script src="https://code.jquery.com/jquery-1.10.2.js"></script>

<script>
$(document).ready(function(){

var OriginalArray = [ 1, 9, 3, 8, 6, 1, 5, 9, 4, 7, 3, 8, 6, 9, 1 ];
var arrayfilterElement = [ 1, 9, 3 ];


var FilteredArray;

$( "p.first" ).text( OriginalArray.join( ", " ) );

FilteredArray= jQuery.grep(OriginalArray, function( n, i ) {

return (jQuery.inArray(n,arrayfilterElement)==-1) ;

});

$( "p.last" ).text( FilteredArray.join( ", " ) );

});

</script>
</head>
<body>

<p class="first"></p>
<p class='last'></p>

</body>
</html>

Wednesday, 11 March 2015

remove object or item from array in javascript and JQuery

you can remove object or item from array in javascript and JQuery by following ways.



Using JQuery

1) filter item from list using map() of jquery

    indexes = $.map(list, function(obj, index) {
        if(obj.name == "Jayesh") {
           return index;
        }
    })
 
    Index = indexes[0];

2) removing item from array 
    list.splice(Index, 1);

Remove Item From Array Using Java Script



var array = [2, 5, 9];
var index = array.indexOf(5);
if (index > -1) {
    array.splice(index, 1);
}


Remove Object From Array Using Java Script


1) create function to find and remove object with particulate attribute and value
  
var removeObjectFromArray = function(arr, attr, value){
    var i = arr.length;
    while(i--){
       if( arr[i]
           && arr[i].hasOwnProperty(attr)
           && (arguments.length > 2 && arr[i][attr] === value ) ){

           arr.splice(i,1);

       }
    }
    return arr;
}



2) Example  of calling above created function

var arr = [{Pid:1,name:'Jayesh'},{Pid:2,name:'Mahesh'},{Pid:3,name:'Dhaval'}];
removeObjectFromArray (arr, 'Pid', 1);
//now new value in array will be  [{Pid:2,name:'Mahesh'},{Pid:3,name:'Dhaval'}]

removeObjectFromArray (arr, 'name', 'Mahesh');
///now new value in array will be [{Pid:3,name:'Dhaval'}]

Monday, 9 March 2015

Send Mail in java Example

Send Mail

here is java program to send a mail to one or more recipients.


import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SendMail {

public boolean sendMail(String file,String camp,String recipients)
{

     String[] recipientsList=recipients.split(";");
   
     String to = "to_address";
     String from = "from_address";

        // Assuming you are sending email from localhost
         String host = "yoursmtpserver";
     // Get system properties
     Properties properties = System.getProperties();

     // Setup mail server
     properties.setProperty("mail.smtp.host", host);
     properties.setProperty("mail.transport.protocol","smtp");
                      properties.setProperty("mail.smtp.starttls.enable","true");
     properties.put("mail.smtp.port", "587");
     properties.put("mail.smtp.auth", "true");
     properties.put("mail.debug", "true");
   
   
     // Get the default Session object.
     Session session = Session.getDefaultInstance(properties,new javax.mail.Authenticator() {
               protected PasswordAuthentication getPasswordAuthentication() {
                   return new PasswordAuthentication("from_address", "PASSWORD");
               }
           });

     try{
        // Create a default MimeMessage object.
        MimeMessage message = new MimeMessage(session);

        // Set From: header field of the header.
        message.setFrom(new InternetAddress(from));

        // Set To: header field of the header.
     
     
        for (String string : recipientsList) {
        message.addRecipient(Message.RecipientType.TO,
                             new InternetAddress(string));
}
     
     
        // Set Subject: header field
        message.setSubject("Subject Here");

        // Create the message part
        BodyPart messageBodyPart = new MimeBodyPart();

        // Fill the message
        messageBodyPart.setText("MSG Body");
     
        // Create a multipar message
        Multipart multipart = new MimeMultipart();

        // Set text message part
        multipart.addBodyPart(messageBodyPart);

        // Part two is attachment
        messageBodyPart = new MimeBodyPart();
        String filename = file;
        DataSource source = new FileDataSource(filename);
     
        messageBodyPart.setDataHandler(new DataHandler(source));
        messageBodyPart.setFileName(filename);
        multipart.addBodyPart(messageBodyPart);

        // Send the complete message parts
        message.setContent(multipart );

        // Send message
        Transport.send(message);
        System.out.println("Sent message successfully....");
     }catch (MessagingException mex) {
        mex.printStackTrace();
     }
return true;
  }





}

create custom list view in android


To create custom list view we need to follow following steps.


1) create new adapter we call it as CustomAdapter
   

public class CustomAdapter extends BaseAdapter {

        Context context;
        String[] UserName;
        String[] UserStatus;
       
        private static LayoutInflater inflater = null;

        public CustomAdapter(Context context, String[] data,String[] data1) {
            // TODO Auto-generated constructor stub
            this.context = context;
            this.UserName = data;
            this.UserStatus=data1;
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return UserName.length;
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return UserName[position];
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
           
              View vi = convertView;
                if (vi == null)
                    vi = inflater.inflate(R.layout.custome_listview_item, null);
                ImageView Uimg=(ImageView) vi.findViewById(R.id.imageView1);
                Uimg.setImageResource(R.drawable.header_bg_brown);
                TextView text = (TextView) vi.findViewById(R.id.ItemHeader);
                text.setText(UserName[position]);
                TextView textt = (TextView) vi.findViewById(R.id.Itemtext);
                textt.setText(UserStatus[position]);
                return vi;
      
        }
   }

2) then create layout file for custom list view row. we are calling it row because this layout will use to design  each row of list.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/royalblue_color"
    android:orientation="vertical" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:nextFocusRight="@+id/ItemHeader"
            />

       
        <TextView
            android:id="@+id/ItemHeader"
            android:layout_width="240dp"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:nextFocusLeft="@id/imageView1"
            android:text="Header"
            android:textColor="@color/white_color"
            android:textSize="20dp" />

        <TextView
            android:id="@+id/Itemtext"
            android:layout_width="240dp"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/ItemHeader"
            android:text="Text"
            android:textColor="@color/white_color"
            android:textStyle="italic" />

    </RelativeLayout>

</LinearLayout>

3) adding item to list on activity 

ApplicationObjectsClass aoc = new ApplicationObjectsClass();

public class WebViewActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view);

                Users user = new Users();
                                        user.setUserID("Test1");
                                        user.setUserID("Test2");
                                        //as new user will come we will add them to this list
                                       
                                        aoc.addOnlineUser(user);
                                       
                                        int usercount = aoc.getOnlineUserList()
                                                .size();
                                        int count = 0;
                                       
                                        String[] listItem = new String[usercount];
                                        String[] listItemStatus = new String[usercount];
                                       
                                        for (Users object2 : aoc.getOnlineUserList()) {
                                       
                                            listItem[count] = object2.getUserID();
                                            listItemStatus[count] = "Status of "+ object2.getUserID();
                                           
                                            count++;
                                        }

                                       
                                        CustomAdapter custAdapter;
                                        custAdapter = new CustomAdapter(getBaseContext(), listItem,
                                                listItemStatus);
                                        ListView listV = (ListView) findViewById(R.id.listView1);
                                       
                                        listV.setAdapter(custAdapter);
                                       
                                        listV.setOnItemClickListener(new OnItemClickListener() {
                                           
                                        public void onItemClick(android.widget.AdapterView<?> adapter, View view, int position, long id) {
                                           
                                        Object item = adapter.getAdapter().getItem(position);
                                       
                                        Log.d("Get Item",item.toString());
                                           
                                        Intent intent = new Intent(getBaseContext(),ChatActivity.class);
                                        intent.putExtra("connectTo", item.toString());
                                       
                                       
                                        startActivity(intent);
                                           
                                        }});   
                                       
                                        final LinearLayout lm = (LinearLayout) findViewById(R.id.LinearLayout1);
                                       
        }
    }