Friday 17 April 2015

Dropdown access nested child object of entity object in spring form:select box


If you want to access nested objects which is coming child object like if we have relationship of ManyToOne or OneToMany then when we fetch object of one entity then the dependent object's reference will also come inside that object
Lets take an Example.

We have to models as below 

Address

@Entity
@Table(name="Address")
public class Address implements Serializable {

    private static final long serialVersionUID = 1L;
   
    @Id
    @Column(name="id",unique=true)
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
   
    @Column(name="address1")
    private String address1;
   
    @Column(name="address2")
    private String address2;
   
    @Column(name="city")
    private String city;
   
    @Column(name="state")
    private String state;
   
    @Column(name="zip")
    private String zip;
 
@OneToMany(mappedBy="address",cascade=CascadeType.ALL)
    private List<Contact> contacts;
                                     //all setter and getter here
}


Contact

@Entity
@Table(name="CONTACTS")
public class Contact implements Serializable  {
    private static final long serialVersionUID = 1L;
   
    @Id
    @Column(name="ID")
    @GeneratedValue
    private Integer id;
   
    @Column(name="FIRSTNAME")
    private String firstname;

    @Column(name="LASTNAME")
    private String lastname;

    @Column(name="EMAIL")
    private String email;
   
    @Column(name="TELEPHONE")
    private String telephone;
   
    @ManyToOne
    private Address address;
                                    //all setter and getter here
}


Now here we have used ManyToOne and OneToMany dependency.
so we can have more then one contact for one address.

Now if i am inserting a new contact then i have to select the address to which contact belong.
and when i get contact then related address should also get selected.
now lets take one controller which will have method to add and get the contact.

ContactController 

@Controller
public class ContactController {

    @Autowired
    private ContactService contactService;    
  
    @Autowired
    private AddressService addressService;

    @RequestMapping("/index")
    public String listContacts(Map<String, Object> map) {

        if(contactService.listContact().size()>0){
            map.put("contact", contactService.listContact().get(0));
        }else
        {
            map.put("contact", new Contact());
        }
     

        map.put("addressList", addressService.listAddress());
        map.put("contactList", contactService.listContact());
      
        return "contact";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addContact(@ModelAttribute("contact")
    Contact contact, BindingResult result) {
          
            contact.setAddress(addressService.getAddressById(contact.getAddress().getId()));
      
        contactService.addContact(contact);

        return "redirect:/index";
    }

  @RequestMapping("/delete/{contactId}")
    public String deleteContact(@PathVariable("contactId")
    Integer contactId) {

        contactService.removeContact(contactId);

        return "redirect:/index";
    }
 }


Now lets create the contact.jsp page on which we will have a form to add the contact and display first contact filled in form if any.

contact.jsp 

 <%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
<title>Spring 3 MVC Series - Contact Manager</title>
</head>
<body>

    <h2>Contact Manager</h2>

    <form:form method="post" action="add.html" commandName="contact">

        <table>
            <tr>
                <td>First Name</td>
                <td><form:input path="firstname" /></td>
            </tr>
            <tr>
                <td>Last Name</td>
                <td><form:input path="lastname" /></td>
            </tr>
            <tr>
                <td>Email</td>
                <td><form:input path="email" /></td>
            </tr>
            <tr>
                <td>telephone</td>
                <td><form:input path="telephone" /></td>
            </tr>
            <tr>
                <td>Address</td>
                <td>
               <c:if test="${!empty addressList}">
                        <form:select path="address.id" itemValue="address.id">
                                <c:forEach items="${addressList}" var="address">

                                    <form:option value="${address.id}">${address.address1},${address.address2},${address.city}</form:option>

                                </c:forEach>
                            </form:select>
                    </c:if>
</td>
            </tr>
            <tr>
                <td colspan="2"><input type="submit"
                    value="<spring:message code="label.addcontact"/>" /></td>
            </tr>
        </table>
    </form:form>

    <h3>Contacts</h3>
    <c:if test="${!empty contactList}">
        <table class="data">
            <tr>
                <th>Name</th>          <th>Email</th>           <th>Telephone</th>          <th>&nbsp;</th>
            </tr>
            <c:forEach items="${contactList}" var="contact">
                <tr>
                    <td>${contact.lastname}, ${contact.firstname}</td>
                    <td>${contact.email}</td>
                    <td>${contact.telephone}</td>
                    <td><a href="delete/${contact.id}">delete</a></td>
                </tr>
            </c:forEach>
        </table>
    </c:if>


</body>
</html>


This will diasplay the form which is allow to add the contact to selected address and display the contact with its related address seleted in <form:select> drop down. 

NOTE: Create required serveries and dao. 





send sms in java spring using way2sms

send sms in java spring using way2sms

using below code you can send an sms to any number from way2sms.
just you need to use your credentials.



WaySms.Java

package way2sms;


import java.net.HttpURLConnection;


public class WaySms {
private static int responseCode = -1;
private static String userCredentials = null;
private static String cookie = null;
private static String site = null;
private static String token=null;
private static Credentials credentials = new Credentials();

public static void main(String[] args) {
 
 login("loginnumber", "pass");
 sendSMS("tonumber", "yourMsg140Length");
 
 System.out.println("Message has been sent successfully!");
}


private static void getSite() {
 URLConnector.connect("http://www.way2sms.com/", false, "GET", null, null);
 responseCode = URLConnector.getResponseCode();
 System.out.println(responseCode);
 if(responseCode != HttpURLConnection.HTTP_MOVED_TEMP && responseCode != HttpURLConnection.HTTP_OK)
  exit("getSite failed!");
 else {
  site = URLConnector.getLocation();
  if(site != null)
   site = site.substring(7, site.length() - 1);
 }
 System.out.println(site);
 URLConnector.disconnect();
}

private static void preHome() {
 URLConnector.connect("http://" + site + "/content/prehome.jsp", false, "GET", null, null);
 responseCode = URLConnector.getResponseCode();
 System.out.println(responseCode);
 if(responseCode != HttpURLConnection.HTTP_MOVED_TEMP && responseCode != HttpURLConnection.HTTP_OK)
  exit("preHome failed");
 else
  cookie = URLConnector.getCookie();
 token = cookie.substring(cookie.indexOf("~") + 1);
 URLConnector.disconnect();
}

public static void login(String uid, String pwd) {
 getSite();
 preHome();

 String location = null;

 credentials.set("username", uid);
 credentials.append("password", pwd);
 credentials.append("button", "Login");
 userCredentials = credentials.getUserCredentials();

 URLConnector.connect("http://" + site + "/Login1.action", false, "POST", cookie, userCredentials);
 responseCode = URLConnector.getResponseCode();
 System.out.println(responseCode);
 if(responseCode != HttpURLConnection.HTTP_MOVED_TEMP && responseCode != HttpURLConnection.HTTP_OK)
  exit("authentication failed!");
 else
  location = URLConnector.getLocation();
 URLConnector.disconnect();

 URLConnector.connect(location, false, "GET", cookie, null);
 responseCode = URLConnector.getResponseCode();
 System.out.println(responseCode);
 if(responseCode != HttpURLConnection.HTTP_MOVED_TEMP && responseCode != HttpURLConnection.HTTP_OK)
  exit("redirection failed!");
 URLConnector.disconnect();
}

public static void sendSMS(String receiversMobNo, String msg) {

 credentials.reset();
 credentials.append("Token", token);
 credentials.append("message", msg);
 credentials.append("mobile", receiversMobNo);
 credentials.append("msgLen", "124");
 credentials.append("ssaction", "ss");
 

 userCredentials = credentials.getUserCredentials();
 System.out.println("Token=" + token);
 //URLConnector.connect("http://" + site + "/quicksms.action", true, "POST", cookie, userCredentials);
 URLConnector.setProperty("Token", token);
 URLConnector.setProperty("message", msg);
 URLConnector.setProperty("mobile", receiversMobNo);
 URLConnector.setProperty("msgLen", "139");
 URLConnector.setProperty("ssaction", "ss");
 
 
 URLConnector.connect("http://" + site + "/smstoss.action" , true, "POST", cookie, credentials.getUserCredentials());
 
 responseCode = URLConnector.getResponseCode();
 System.out.println("IN "+responseCode);
 if(responseCode != HttpURLConnection.HTTP_MOVED_TEMP && responseCode != HttpURLConnection.HTTP_OK)
  exit("sendSMS failed!");
 URLConnector.disconnect();
}

private static void sendBulkSMS(String[] receiversMobNos, String msg) {
int noOfReceivers = receiversMobNos.length;

for(int i = 0; i < noOfReceivers; i++)
 sendSMS(receiversMobNos[i], msg);
}
private static void exit(String errorMsg) {
 System.err.println(errorMsg);
 System.exit(1);
}
}
URLConnector.java

package way2sms;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URL;

public class URLConnector {
private static HttpURLConnection connection;
private static Proxy proxy;

public static void setProxy(String host, int port) {
 proxy = new Proxy(Proxy.Type.HTTP, java.net.InetSocketAddress.createUnresolved(host, port));
}

public static void connect(String urlPath, boolean redirect, String method, String cookie, String credentials) {
 try {
  URL url = new URL(urlPath);

  if(null != proxy)
   connection = (HttpURLConnection) url.openConnection(proxy);
  else
   connection = (HttpURLConnection) url.openConnection();

  connection.setInstanceFollowRedirects(redirect);

  if(cookie != null)
   connection.setRequestProperty("Cookie", cookie);

  if(method != null && method.equalsIgnoreCase("POST")) {
   connection.setRequestMethod(method);
   
   connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
  }

  connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:10.0.4) Gecko/20100101 Firefox/10.0.4");

  connection.setUseCaches (false);
  connection.setDoInput(true);
  connection.setDoOutput(true);

  if(credentials != null) {
   DataOutputStream wr = new DataOutputStream (connection.getOutputStream ());
   wr.writeBytes (credentials);
   wr.flush ();
   wr.close ();
  }
 } catch(Exception exception) {
  System.out.println("Connection error");
 }
}

public static void setProperty(String key,String val)
{
connection.addRequestProperty(key, val);
}
public static String getCookie() {
 String cookie = null;

 if(connection != null) {
  String headerName=null;

  for (int i = 1; (headerName = connection.getHeaderFieldKey(i)) != null; i++) {
   if (headerName.equals("Set-Cookie")) {
    cookie = connection.getHeaderField(i).split(";")[0];
    break;
   }
  }
 }

 return cookie;
}

public static String getLocation() {
 String location = null;

 if(connection != null) {
  String headerName=null;

  for (int i = 1; (headerName = connection.getHeaderFieldKey(i)) != null; i++) {
   if (headerName.equals("Location")) {
    location = connection.getHeaderField(i).split(";")[0];
    break;
   }
  }
 }

 return location;
}

public static int getResponseCode() {
 int responseCode = -1;

 if(connection != null) {
  try {
   responseCode = connection.getResponseCode();
  } catch(Exception exception) {
   System.err.println("Response code error");
  }
 }

 return responseCode;
}

public static String getResponse() {
 StringBuilder response = new StringBuilder();

 if(connection != null) {
  try {
   InputStream is = connection.getInputStream();
   BufferedReader rd = new BufferedReader(new InputStreamReader(is));

   String line;
   while((line = rd.readLine()) != null) {
    response.append(line);
    response.append('\r');
   }

   rd.close();
  } catch(Exception exception) {
   System.err.println("Response error");
  }
 }

 return response.toString();
}

public static String getErrorMessage() {
 StringBuilder errorMessage = new StringBuilder();

 if(connection != null) {
  try {
   InputStream es = connection.getErrorStream();
   BufferedReader rd = new BufferedReader(new InputStreamReader(es));

   String line;
   while((line = rd.readLine()) != null) {
    errorMessage.append(line);
    errorMessage.append('\r');
   }

   rd.close();
  } catch(Exception exception) {
   System.err.println("Error in getting error message");
  }
 }

 return errorMessage.toString();
}

public static void disconnect() {
 if(connection != null)
  connection.disconnect();
}
}





Credentials.java

package way2sms;

import java.net.URLEncoder;
import java.util.ArrayList;

public class Credentials {
private ArrayList<String> list = new ArrayList<String>();

public void set(String name, String value) {
 StringBuilder buffer = new StringBuilder();

 buffer.append(name);
 buffer.append("=");
 buffer.append(getUTF8String(value));

 add(buffer.toString());
}

public void append(String name, String value) {
 StringBuilder buffer = new StringBuilder();

 buffer.append("&");
 buffer.append(name);
 buffer.append("=");
 buffer.append(getUTF8String(value));

 add(buffer.toString());
}

private void add(String item) {
 list.add(item);
}

private String getUTF8String(String value) {
 String encodedValue = null;

 try {
  encodedValue = URLEncoder.encode(value, "UTF-8");
 } catch(Exception exception) {
  System.err.println("Encoding error");
 }

 return encodedValue;
}

public boolean isEmpty() {
 return list.isEmpty();
}

public void reset() {
 list.clear();
}

public String getUserCredentials() {
 StringBuilder buffer = new StringBuilder();
 int size = list.size();

 for(int i = 0; i < size; i++)
  buffer.append(list.get(i));

 return buffer.toString();
}
}

Source code also available at https://github.com/jayesh36