com.accounting.smsbundle.SmsInfoSessionBean.java Source code

Java tutorial

Introduction

Here is the source code for com.accounting.smsbundle.SmsInfoSessionBean.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.accounting.smsbundle;

import com.accounting.commonutils.HelperUtil;
import com.accounting.entities.office.Office;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.apache.commons.lang3.time.DateUtils;

/**
 *
 * @author faisal
 */
@Stateless
@LocalBean
public class SmsInfoSessionBean {

    @PersistenceContext
    private EntityManager em;
    private static final Double PER_SMS_CHARGE = 1.1;

    public Object mergeObject(Object o) {
        em.merge(o);
        return o;
    }

    public List<SmsInfo> findAllByStatus(SmsInfoStatus status) {
        return em.createQuery("Select s from SmsInfo s where s.sentStatus=:status").setParameter("status", status)
                .getResultList();
    }

    public List<SmsInfo> findAllByOrgId(int orgid) {
        return em.createQuery("Select s from SmsInfo s where s.orgId =:orgid").setParameter("orgid", orgid)
                .getResultList();
    }

    public List<SmsInfo> findAll(Date fromDate, Date todate, SmsInfoStatus status, long sentToId, int orgid) {
        StringBuilder qSql = new StringBuilder();
        qSql.append("Select  s from SmsInfo s where s.orgId=");
        qSql.append(orgid);
        if (fromDate != null && todate != null) {
            qSql.append(" and date(s.createdDate) BETWEEN '").append(HelperUtil.formatDateYYYMMDD(fromDate))
                    .append("' and '").append(HelperUtil.formatDateYYYMMDD(todate)).append("'");
        }
        if (sentToId != 0) {
            //sentToId is customer id, or member id of any other table etc.
            qSql.append(" and d.sentToId=").append(sentToId);
        }
        if (status != null) {
            //sentToId is customer id, or member id of any other table etc.
            qSql.append(" and d.sentStatus=").append(status);
        }
        if (sentToId != 0) {
            //sentToId is customer id, or member id of any other table etc.
            qSql.append(" and d.sentToId=").append(sentToId);
        }
        //        System.out.println("final sql " + qSql.toString());
        Query q = em.createQuery(qSql.toString(), SmsInfo.class);
        return q.getResultList();
    }

    public boolean addSmsQueue(List<SmsInfo> smsinfos) {
        for (SmsInfo sms : smsinfos) {
            sms.setSentStatus(SmsInfoStatus.QUEUE);
            sms.setCreatedDate(new Date());
            em.persist(sms);
        }
        return true;
    }

    public void amountOfSms(Office org) {
        em.merge(org);
    }

    //    public void checkAndSendBirthdayMessage() {
    //
    //        Calendar c = Calendar.getInstance();
    //        c.setTime(new Date());
    ////        System.out.println("day "+c.get(Calendar.DAY_OF_MONTH));
    ////        System.out.println("day "+c.get(Calendar.MONTH));
    //        
    //        
    //        int month = c.get(Calendar.MONTH) + 1;
    //        String k = String.valueOf(month);
    //        if (month < 10) {
    //            k = "0" + month;
    //        }
    //        int day=c.get(Calendar.DAY_OF_MONTH);
    //        String d = String.valueOf(day);
    //        if (day < 10) {
    //            d = "0" + day;
    //        }
    //        String s="SELECT * FROM members  WHERE month(date_of_birth)="+k+" and day(date_of_birth)="+d+" and status=1";
    ////        System.out.println("sql "+s);
    //        Query q = em.createNativeQuery(s,Members.class);
    //        List<Members> birthdayMembers = q.getResultList();
    //        if (!birthdayMembers.isEmpty()) {
    ////            System.out.println("found members ");
    //            List<SmsInfo> memberSmsList = new ArrayList<>();
    //            String orgBdaySmsTxt = setupSessionBean.findAppDataByCode("birthdaysms", birthdayMembers.get(0).getOrganization().getId()).get(0).getDisplayvalue();
    //            for (int i = 0; i < birthdayMembers.size(); i++) {
    ////                System.out.println("member " + birthdayMembers.get(i).getFullName());
    //                SmsInfo smsinfo = new SmsInfo();
    //                smsinfo.setOrgId(birthdayMembers.get(i).getOrganization().getId());
    //                smsinfo.setMobileNumber(birthdayMembers.get(i).getMobileNumber());
    //                smsinfo.setSmsText(orgBdaySmsTxt);
    //                memberSmsList.add(smsinfo);
    //            }
    //            this.addSmsQueue(memberSmsList);
    //        } else {
    //            System.out.println("not found bday members.");
    //        }
    //
    //    }

    public void sendSms() {
        List<SmsInfo> queueSms = findAllByStatus(SmsInfoStatus.QUEUE);
        String smsurl = "";
        if (queueSms != null && !queueSms.isEmpty()) {
            for (SmsInfo smsmsg : queueSms) {
                Office org = em.find(Office.class, smsmsg.getOrgId());
                if (org != null) {
                    if (org.getSmsBalance() != null && org.getSmsBalance() >= PER_SMS_CHARGE) {
                        smsurl = "http://mobile.sms123go.com/http.aspx?guid=7a81f722-2eda-4b43-92f4-f81af69b5b41&username=parsu@sms123go.com&password=parsu@123&mobilenumber=<to>&countryCode=NP&message=<msg>";
                        if (smsmsg.getMobileNumber() != null && smsmsg.getSmsText() != null) {
                            boolean sendnow = false;
                            if (smsmsg.getSendOnDate() == null) {
                                sendnow = true;
                            } else {
                                if (DateUtils.isSameDay(smsmsg.getSendOnDate(), new Date())) {
                                    sendnow = true;
                                } else {
                                    sendnow = false;
                                }
                            }

                            if (sendnow) {
                                try {
                                    System.out.println("smsinfo table id processing " + smsmsg.getId());
                                    String encodedmsg = URLEncoder.encode(smsmsg.getSmsText());
                                    smsurl = smsurl.replaceAll("<to>", "%2B977" + smsmsg.getMobileNumber());
                                    smsurl = smsurl.replaceAll("<msg>", encodedmsg);
                                    URL url = new URL(smsurl);
                                    URLConnection conn = url.openConnection();
                                    BufferedReader in = new BufferedReader(
                                            new InputStreamReader(conn.getInputStream()));
                                    String smsStatus = "";
                                    String f = "";
                                    while ((f = in.readLine()) != null) {
                                        smsStatus = smsStatus + f;
                                    }
                                    System.out.println("smsStatus  :" + smsStatus);
                                    if (smsStatus == null || smsStatus.length() == 0) {
                                        smsmsg.setSentStatus(SmsInfoStatus.FAILED);
                                    } else if (smsStatus.contains("+OK")) {
                                        smsmsg.setSentStatus(SmsInfoStatus.SENT);
                                        org.setSmsBalance(org.getSmsBalance() - PER_SMS_CHARGE);
                                        em.merge(org);
                                    } else {
                                        smsmsg.setSentStatus(SmsInfoStatus.FAILED);
                                    }
                                    smsmsg.setSentDate(new Date());
                                    em.merge(smsmsg);
                                } catch (MalformedURLException ex) {
                                    Logger.getLogger(SmsInfoSessionBean.class.getName()).log(Level.SEVERE, null,
                                            ex);
                                } catch (IOException ex) {
                                    Logger.getLogger(SmsInfoSessionBean.class.getName()).log(Level.SEVERE, null,
                                            ex);
                                }
                            }

                        }
                    }
                }
            }
        }
    }
}