Example usage for java.util Date getMinutes

List of usage examples for java.util Date getMinutes

Introduction

In this page you can find the example usage for java.util Date getMinutes.

Prototype

@Deprecated
public int getMinutes() 

Source Link

Document

Returns the number of minutes past the hour represented by this date, as interpreted in the local time zone.

Usage

From source file:uk.co.senab.photoview.sample.ViewPagerActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.item1:
        ////from  w w  w. j  av  a 2 s .c  o m
        //
        //mViewPager.setCurrentItem((new PageProvider().getPageCount()-1));
        // 1. Instantiate an AlertDialog.Builder with its constructor

        String[] pages = new String[850];
        for (int i = 0; i < 850; i++) {
            pages[i] = i + 1 + "";
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(ViewPagerActivity.this);

        // 2. Chain together various setter methods to set the dialog characteristics
        builder.setTitle("Go To Page").setItems(pages, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                mViewPager.setCurrentItem(849 - which);

                // The 'which' argument contains the index position
                // of the selected item
            }
        });

        // 3. Get the AlertDialog from create()
        AlertDialog dialog = builder.create();
        dialog.show();
        return true;
    case R.id.item2:
        //
        //
        //mViewPager.setCurrentItem((new PageProvider().getPageCount()-1));
        // 1. Instantiate an AlertDialog.Builder with its constructor
        AlertDialog.Builder builder2 = new AlertDialog.Builder(ViewPagerActivity.this);

        String[] juz = getResources().getStringArray(R.array.juz);

        // 2. Chain together various setter methods to set the dialog characteristics
        builder2.setTitle("Go To Juz (Parah)").setItems(juz, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                if (which == 0) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 1);

                }
                if (which == 1) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 31);

                }
                if (which == 2) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 59);

                }
                if (which == 3) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 87);

                }
                if (which == 4) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 115);

                }
                if (which == 5) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 143);

                }
                if (which == 6) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 171);

                }
                if (which == 7) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 199);

                }
                if (which == 8) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 227);

                }
                if (which == 9) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 255);

                }
                if (which == 10) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 283);

                }
                if (which == 11) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 311);

                }
                if (which == 12) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 339);

                }
                if (which == 13) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 367);

                }
                if (which == 14) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 395);

                }
                if (which == 15) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 423);

                }
                if (which == 16) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 451);

                }
                if (which == 17) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 479);

                }
                if (which == 18) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 507);

                }
                if (which == 19) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 535);

                }
                if (which == 20) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 561);

                }
                if (which == 21) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 589);

                }
                if (which == 22) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 615);

                }
                if (which == 23) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 643);

                }
                if (which == 24) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 669);

                }
                if (which == 25) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 699);

                }
                if (which == 26) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 729);

                }
                if (which == 27) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 759);

                }
                if (which == 28) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 789);

                }
                if (which == 29) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 821);

                }

                // The 'which' argument contains the index position
                // of the selected item
            }
        });

        // 3. Get the AlertDialog from create()
        AlertDialog dialog2 = builder2.create();
        dialog2.show();
        return true;
    case R.id.item3:
        //
        //
        //mViewPager.setCurrentItem((new PageProvider().getPageCount()-1));
        // 1. Instantiate an AlertDialog.Builder with its constructor
        AlertDialog.Builder builder3 = new AlertDialog.Builder(ViewPagerActivity.this);

        String[] surah = getResources().getStringArray(R.array.surah);

        // 2. Chain together various setter methods to set the dialog characteristics
        builder3.setTitle("Go To Surah").setItems(surah, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                if (which == 0) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(620 - 4);
                }
                if (which == 1) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(620 - 5);
                }
                if (which == 2) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 70);
                }
                if (which == 3) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 108);
                }
                if (which == 4) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 149);
                }
                if (which == 5) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 179);
                }
                if (which == 6) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 211);
                }
                if (which == 7) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 247);
                }
                if (which == 8) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 262);
                }
                if (which == 9) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 290);
                }
                if (which == 10) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 310);
                }
                if (which == 11) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 330);
                }
                if (which == 12) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 348);
                }
                if (which == 13) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 357);
                }
                if (which == 14) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 366);
                }
                if (which == 15) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 374);
                }
                if (which == 16) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 390);
                }
                if (which == 17) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 410);
                }
                if (which == 18) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 427);
                }
                if (which == 19) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 437);
                }
                if (which == 20) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 451);
                }
                if (which == 21) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 464);
                }
                if (which == 22) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 479);
                }
                if (which == 23) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 489);
                }
                if (which == 24) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 503);
                }
                if (which == 25) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 513);
                }
                if (which == 26) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 527);
                }
                if (which == 27) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 539);
                }
                if (which == 28) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 554);
                }
                if (which == 29) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 564);
                }
                if (which == 30) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 573);
                }
                if (which == 31) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 579);
                }
                if (which == 32) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 583);
                }
                if (which == 33) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 597);
                }
                if (which == 34) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 605);
                }
                if (which == 35) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 613);
                }
                if (which == 36) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 620);
                }
                if (which == 37) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 630);
                }
                if (which == 38) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 637);
                }
                if (which == 39) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 649);
                }
                if (which == 40) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 661);
                }
                if (which == 41) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 670);
                }
                if (which == 42) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 679);
                }
                if (which == 43) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 688);
                }
                if (which == 44) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 693);
                }
                if (which == 45) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 699);
                }
                if (which == 46) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 706);
                }
                if (which == 47) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 712);
                }
                if (which == 48) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 718);
                }
                if (which == 49) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 723);
                }
                if (which == 50) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 728);
                }
                if (which == 51) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 731);
                }
                if (which == 52) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 734);
                }
                if (which == 53) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 738);
                }
                if (which == 54) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 742);
                }
                if (which == 55) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 747);
                }
                if (which == 56) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 752);
                }
                if (which == 57) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 759);
                }
                if (which == 58) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 763);
                }
                if (which == 59) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 768);
                }
                if (which == 60) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 772);
                }
                if (which == 61) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 775);
                }
                if (which == 62) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 777);
                }
                if (which == 63) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 779);
                }
                if (which == 64) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 782);
                }
                if (which == 65) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 785);
                }
                if (which == 66) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 789);
                }
                if (which == 67) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 792);
                }
                if (which == 68) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 796);
                }
                if (which == 69) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 799);
                }
                if (which == 70) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 802);
                }
                if (which == 71) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 805);
                }
                if (which == 72) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 808);
                }
                if (which == 73) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 810);
                }
                if (which == 74) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 813);
                }
                if (which == 75) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 815);
                }
                if (which == 76) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 818);
                }
                if (which == 77) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 821);
                }
                if (which == 78) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 822);
                }
                if (which == 79) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 824);
                }
                if (which == 80) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 826);
                }
                if (which == 81) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 827);
                }
                if (which == 82) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 828);
                }
                if (which == 83) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 830);
                }
                if (which == 84) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 831);
                }
                if (which == 85) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 832);
                }
                if (which == 86) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 833);
                }
                if (which == 87) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 834);
                }
                if (which == 88) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 835);
                }
                if (which == 89) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 837);
                }
                if (which == 90) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 838);
                }
                if (which == 91) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 839);
                }
                if (which == 92) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 840);
                }
                if (which == 93) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 840);
                }
                if (which == 94) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 841);
                }
                if (which == 95) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 841);
                }
                if (which == 96) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 842);
                }
                if (which == 97) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 842);
                }
                if (which == 98) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 843);
                }
                if (which == 99) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 844);
                }
                if (which == 100) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 845);
                }
                if (which == 101) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 845);
                }
                if (which == 102) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 846);
                }
                if (which == 103) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 846);
                }
                if (which == 104) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 846);
                }
                if (which == 105) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 847);
                }
                if (which == 106) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 847);
                }
                if (which == 107) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 848);
                }
                if (which == 108) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 848);
                }
                if (which == 109) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 848);
                }
                if (which == 110) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 849);
                }
                if (which == 111) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 849);
                }
                if (which == 112) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 849);
                }
                if (which == 113) {
                    dialog.dismiss();

                    mViewPager.setCurrentItem(850 - 850);
                }

                // The 'which' argument contains the index position
                // of the selected item
            }
        });

        // 3. Get the AlertDialog from create()
        AlertDialog dialog3 = builder3.create();
        dialog3.show();
        return true;
    case R.id.item4:
        Builder builderr = new Builder(this);
        Date cDate = new Date();
        final String fDate = new SimpleDateFormat("MM/dd/yy").format(cDate);
        Date dt = new Date();
        int hours = dt.getHours();
        int minutes = dt.getMinutes();

        SimpleDateFormat sdf = new SimpleDateFormat("hh:mmaa");
        String time1 = sdf.format(dt);

        final EditText input = new EditText(this);
        InputFilter[] FilterArray = new InputFilter[1];
        FilterArray[0] = new InputFilter.LengthFilter(18);
        input.setFilters(FilterArray);

        input.setText(fDate + " " + time1.toLowerCase());
        builderr.setTitle("Bookmark").setMessage("Name your Bookmark").setView(input)
                .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {

                        if (!input.getText().toString().equals(""))
                            saveState(input.getText().toString());
                        else
                            saveState(fDate);
                        setResult(RESULT_OK);
                    }
                }).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                    }

                });

        builderr.show();

        return true;
    case R.id.item5:
        Intent i = new Intent(ViewPagerActivity.this, Notepadv3.class);

        startActivity(i);
        return true;
    case R.id.item6:
        try {
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=pub:Qazi+Musab")));
        } catch (android.content.ActivityNotFoundException anfe) {
            startActivity(new Intent(Intent.ACTION_VIEW,
                    Uri.parse("http://play.google.com/store/apps/developer?id=Qazi+Musab")));
        }
        return true;
    case R.id.item7:
        String appName2 = "com.qaziconsultancy.13linequran";
        try {
            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appName2)));
        } catch (android.content.ActivityNotFoundException anfe) {
            startActivity(new Intent(Intent.ACTION_VIEW,
                    Uri.parse("http://play.google.com/store/apps/details?id=" + appName2)));
        }
        return true;
    case R.id.item8:
        mViewPager.setCurrentItem(mViewPager.getCurrentItem() - 1);
        return true;
    case R.id.item9:
        mViewPager.setCurrentItem(mViewPager.getCurrentItem() + 1);
        return true;
    case R.id.item10:
        String[] items = new String[9];
        items[0] = "$1";
        items[1] = "$2";
        items[2] = "$3";
        items[3] = "$4";
        items[4] = "$5";
        items[5] = "$10";
        items[6] = "$20";
        items[7] = "$50";
        items[8] = "$100";

        AlertDialog.Builder chooser = new AlertDialog.Builder(ViewPagerActivity.this);
        chooser.setTitle("Contribute").setItems(items, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                case 0:
                    contributeOneDollar();
                    break;
                case 1:
                    contributetwoDollars();
                    break;
                case 2:
                    contributeThreeDollars();
                    break;
                case 3:
                    contributeFourDollars();
                    break;
                case 4:
                    contributeFiveDollars();
                    break;
                case 5:
                    contributeTenDollars();
                    break;
                case 6:
                    contributeTwentyDollars();
                    break;
                case 7:
                    contributeFiftyDollars();
                    break;
                case 8:
                    contributeHundredDollars();
                    break;

                }
            }
        });

        // 3. Get the AlertDialog from create()
        AlertDialog myChooser = chooser.create();
        myChooser.show();
        return true;
    default:
        return true;
    }
}

From source file:org.oscarehr.caseload.CaseloadContentAction.java

private JSONArray generateCaseloadDataForDemographics(HttpServletRequest request, HttpServletResponse response,
        String caseloadProv, List<Integer> demoSearchResult) {
    JSONArray entry;//from   w  ww  . jav  a  2  s  .  c  o m
    String buttons;
    JSONArray data = new JSONArray();
    if (demoSearchResult == null || demoSearchResult.size() < 1)
        return data;

    CaseloadDao caseloadDao = (CaseloadDao) SpringUtils.getBean("caseloadDao");

    HttpSession session = request.getSession();
    WebApplicationContext webApplicationContext = WebApplicationContextUtils
            .getRequiredWebApplicationContext(session.getServletContext());
    String roleName$ = (String) session.getAttribute("userrole") + "," + (String) session.getAttribute("user");

    String curUser_no = (String) session.getAttribute("user");
    String userfirstname = (String) session.getAttribute("userfirstname");
    String userlastname = (String) session.getAttribute("userlastname");

    GregorianCalendar cal = new GregorianCalendar();
    int curYear = cal.get(Calendar.YEAR);
    int curMonth = (cal.get(Calendar.MONTH) + 1);
    int curDay = cal.get(Calendar.DAY_OF_MONTH);

    int year = Integer.parseInt(request.getParameter("year"));
    int month = Integer.parseInt(request.getParameter("month"));
    int day = Integer.parseInt(request.getParameter("day"));

    java.util.Date apptime = new java.util.Date();

    OscarProperties oscarProperties = OscarProperties.getInstance();
    boolean bShortcutForm = oscarProperties.getProperty("appt_formview", "").equalsIgnoreCase("on") ? true
            : false;
    String formName = bShortcutForm ? oscarProperties.getProperty("appt_formview_name") : "";
    String formNameShort = formName.length() > 3 ? (formName.substring(0, 2) + ".") : formName;
    String formName2 = bShortcutForm ? oscarProperties.getProperty("appt_formview_name2", "") : "";
    String formName2Short = formName2.length() > 3 ? (formName2.substring(0, 2) + ".") : formName2;
    boolean bShortcutForm2 = bShortcutForm && !formName2.equals("");
    boolean bShortcutIntakeForm = oscarProperties.getProperty("appt_intake_form", "").equalsIgnoreCase("on")
            ? true
            : false;

    String monthDay = String.format("%02d", month) + "-" + String.format("%02d", day);

    String prov = oscarProperties.getProperty("billregion", "").trim().toUpperCase();

    for (Integer result : demoSearchResult) {
        if (result == null)
            continue;
        String demographic_no = result.toString();
        entry = new JSONArray();
        // name
        String demographicQuery = "cl_demographic_query";
        String[] demographicParam = new String[1];
        demographicParam[0] = demographic_no;
        List<Map<String, Object>> demographicResult = caseloadDao.getCaseloadDemographicData(demographicQuery,
                demographicParam);

        String clLastName = demographicResult.get(0).get("last_name").toString();
        String clFirstName = demographicResult.get(0).get("first_name").toString();
        String clFullName = StringEscapeUtils.escapeJavaScript(clLastName + ", " + clFirstName).toUpperCase();
        entry.add(clFullName);

        // add E button to string
        buttons = "";
        if (hasPrivilege("_eChart", roleName$)) {
            String encType = "";
            try {
                encType = URLEncoder.encode("face to face encounter with client", "UTF-8");
            } catch (UnsupportedEncodingException e) {
                MiscUtils.getLogger().error("Couldn't encode string", e);
            }
            String eURL = "../oscarEncounter/IncomingEncounter.do?providerNo=" + curUser_no
                    + "&appointmentNo=0&demographicNo=" + demographic_no + "&curProviderNo=" + caseloadProv
                    + "&reason=&encType=" + encType + "&userName="
                    + URLEncoder.encode(userfirstname + " " + userlastname) + "&curDate=" + curYear + "-"
                    + curMonth + "-" + curDay + "&appointmentDate=" + year + "-" + month + "-" + day
                    + "&startTime=" + apptime.getHours() + ":" + apptime.getMinutes() + "&status=T"
                    + "&apptProvider_no=" + caseloadProv + "&providerview=" + caseloadProv;
            buttons += "<a href='#' onClick=\"popupPage(710, 1024,'../oscarSurveillance/CheckSurveillance.do?demographicNo="
                    + demographic_no + "&proceed=" + URLEncoder.encode(eURL)
                    + "');return false;\" title='Encounter'>E</a> ";
        }

        // add form links to string
        if (hasPrivilege("_billing", roleName$)) {
            buttons += bShortcutForm
                    ? "| <a href=# onClick='popupPage2( \"../form/forwardshortcutname.jsp?formname=" + formName
                            + "&demographic_no=" + demographic_no + "\")' title='form'>" + formNameShort
                            + "</a> "
                    : "";
            buttons += bShortcutForm2
                    ? "| <a href=# onClick='popupPage2( \"../form/forwardshortcutname.jsp?formname=" + formName2
                            + "&demographic_no=" + demographic_no + "\")' title='form'>" + formName2Short
                            + "</a> "
                    : "";
            buttons += (bShortcutIntakeForm)
                    ? "| <a href='#' onClick='popupPage(700, 1024, \"formIntake.jsp?demographic_no="
                            + demographic_no + "\")'>In</a> "
                    : "";
        }

        // add B button to string
        if (hasPrivilege("_billing", roleName$)) {
            buttons += "| <a href='#' onClick=\"popupPage(700,1000,'../billing.do?skipReload=true&billRegion="
                    + URLEncoder.encode(prov) + "&billForm="
                    + URLEncoder.encode(oscarProperties.getProperty("default_view"))
                    + "&hotclick=&appointment_no=0&demographic_name=" + URLEncoder.encode(clLastName) + "%2C"
                    + URLEncoder.encode(clFirstName) + "&demographic_no=" + demographic_no
                    + "&providerview=1&user_no=" + curUser_no + "&apptProvider_no=none&appointment_date=" + year
                    + "-" + month + "-" + day
                    + "&start_time=0:00&bNewForm=1&status=t');return false;\" title='Billing'>B</a> ";
            buttons += "| <a href='#' onClick=\"popupPage(700,1000,'../billing/CA/ON/billinghistory.jsp?demographic_no="
                    + demographic_no + "&last_name=" + URLEncoder.encode(clLastName) + "&first_name="
                    + URLEncoder.encode(clFirstName)
                    + "&orderby=appointment_date&displaymode=appt_history&dboperation=appt_history&limit1=0&limit2=10');return false;\" title='Billing'>BHx</a> ";
        }

        // add M button to string
        if (hasPrivilege("_masterLink", roleName$)) {
            buttons += "| <a href='#' onClick=\"popupPage(700,1000,'../demographic/demographiccontrol.jsp?demographic_no="
                    + demographic_no
                    + "&displaymode=edit&dboperation=search_detail');return false;\" title='Master File'>M</a> ";
        }

        // add Rx button to string
        if (isModuleLoaded(request, "TORONTO_RFQ", true)
                && hasPrivilege("_appointment.doctorLink", roleName$)) {
            buttons += "| <a href='#' onClick=\"popupOscarRx(700,1027,'../oscarRx/choosePatient.do?providerNo="
                    + curUser_no + "&demographicNo=" + demographic_no + "');return false;\">Rx</a> ";
        }

        // add Tickler button to string
        buttons += "| <a href='#' onclick=\"popupPage('700', '1000', '../tickler/ticklerAdd.jsp?name="
                + URLEncoder.encode(clLastName) + "%2C" + URLEncoder.encode(clFirstName)
                + "&chart_no=&bFirstDisp=false&demographic_no=" + demographic_no + "&messageID=null&doctor_no="
                + curUser_no + "'); return false;\">T</a> ";

        // add Msg button to string
        buttons += "| <a href='#' onclick=\"popupPage('700', '1000', '../oscarMessenger/SendDemoMessage.do?demographic_no="
                + demographic_no + "'); return false;\">Msg</a> ";

        entry.add(buttons);

        // age
        String clAge = demographicResult.get(0).get("age") != null
                ? demographicResult.get(0).get("age").toString()
                : "";
        String clBDay = demographicResult.get(0).get("month_of_birth").toString() + "-"
                + demographicResult.get(0).get("date_of_birth").toString();
        if (isBirthday(monthDay, clBDay)) {
            clAge += " <img src='../images/cake.gif' height='20' />";
        }
        entry.add(clAge);

        // sex
        String clSex = demographicResult.get(0).get("sex").toString();
        entry.add(clSex);

        // last appt
        String lapptQuery = "cl_last_appt";
        List<Map<String, Object>> lapptResult = caseloadDao.getCaseloadDemographicData(lapptQuery,
                demographicParam);
        if ((!lapptResult.isEmpty()) && lapptResult.get(0).get("max(appointment_date)") != null
                && !lapptResult.get(0).get("max(appointment_date)").toString().equals("")) {
            String clLappt = lapptResult.get(0).get("max(appointment_date)").toString();

            entry.add(
                    "<a href='#' onclick=\"popupPage('700', '1000', '../demographic/demographiccontrol.jsp?demographic_no="
                            + demographic_no + "&last_name=" + URLEncoder.encode(clLastName) + "&first_name="
                            + URLEncoder.encode(clFirstName)
                            + "&orderby=appttime&displaymode=appt_history&dboperation=appt_history&limit1=0&limit2=25'); return false;\">"
                            + clLappt + "</a>");
        } else {
            entry.add("&nbsp;");
        }

        // next appt
        String napptQuery = "cl_next_appt";
        List<Map<String, Object>> napptResult = caseloadDao.getCaseloadDemographicData(napptQuery,
                demographicParam);
        if (!napptResult.isEmpty() && napptResult.get(0).get("min(appointment_date)") != null
                && !napptResult.get(0).get("min(appointment_date)").toString().equals("")) {
            String clNappt = napptResult.get(0).get("min(appointment_date)").toString();
            entry.add(
                    "<a href='#' onclick=\"popupPage('700', '1000', '../demographic/demographiccontrol.jsp?demographic_no="
                            + demographic_no + "&last_name=" + URLEncoder.encode(clLastName) + "&first_name="
                            + URLEncoder.encode(clFirstName)
                            + "&orderby=appttime&displaymode=appt_history&dboperation=appt_history&limit1=0&limit2=25'); return false;\">"
                            + clNappt + "</a>");
        } else {
            entry.add("&nbsp;");
        }

        // num appts in last year
        String numApptsQuery = "cl_num_appts";
        List<Map<String, Object>> numApptsResult = caseloadDao.getCaseloadDemographicData(numApptsQuery,
                demographicParam);
        if (!numApptsResult.isEmpty() && numApptsResult.get(0).get("count(*)") != null
                && !numApptsResult.get(0).get("count(*)").toString().equals("")
                && !numApptsResult.get(0).get("count(*)").toString().equals("0")) {
            String clNumAppts = numApptsResult.get(0).get("count(*)").toString();
            entry.add(clNumAppts);
        } else {
            entry.add("&nbsp;");
        }

        // new labs
        String[] userDemoParam = new String[2];
        userDemoParam[0] = curUser_no;
        userDemoParam[1] = demographic_no;
        String newLabQuery = "cl_new_labs";
        List<Map<String, Object>> newLabResult = caseloadDao.getCaseloadDemographicData(newLabQuery,
                userDemoParam);
        if (!newLabResult.isEmpty() && newLabResult.get(0).get("count(*)") != null
                && !newLabResult.get(0).get("count(*)").toString().equals("")
                && !newLabResult.get(0).get("count(*)").toString().equals("0")) {
            String clNewLab = newLabResult.get(0).get("count(*)").toString();

            entry.add(
                    "<a href='#' onclick=\"popupPage('700', '1000', '../dms/inboxManage.do?method=prepareForIndexPage&providerNo="
                            + curUser_no + "&selectedCategory=CATEGORY_PATIENT_SUB&selectedCategoryPatient="
                            + demographic_no + "&selectedCategoryType=CATEGORY_TYPE_HL7'); return false;\">"
                            + clNewLab + "</a>");
        } else {
            entry.add("&nbsp;");
        }

        // new docs
        String newDocQuery = "cl_new_docs";
        List<Map<String, Object>> newDocResult = caseloadDao.getCaseloadDemographicData(newDocQuery,
                userDemoParam);
        if (!newDocResult.isEmpty() && newDocResult.get(0).get("count(*)") != null
                && !newDocResult.get(0).get("count(*)").toString().equals("")
                && !newDocResult.get(0).get("count(*)").toString().equals("0")) {
            String clNewDoc = newDocResult.get(0).get("count(*)").toString();
            entry.add(
                    "<a href='#' onclick=\"popupPage('700', '1000', '../dms/inboxManage.do?method=prepareForIndexPage&providerNo="
                            + curUser_no + "&selectedCategory=CATEGORY_PATIENT_SUB&selectedCategoryPatient="
                            + demographic_no + "&selectedCategoryType=CATEGORY_TYPE_DOC'); return false;\">"
                            + clNewDoc + "</a>");
        } else {
            entry.add("&nbsp;");
        }

        // new ticklers
        String newTicklerQuery = "cl_new_ticklers";
        List<Map<String, Object>> newTicklerResult = caseloadDao.getCaseloadDemographicData(newTicklerQuery,
                demographicParam);
        if (!newTicklerResult.isEmpty() && newTicklerResult.get(0).get("count(*)") != null
                && !newTicklerResult.get(0).get("count(*)").toString().equals("")
                && !newTicklerResult.get(0).get("count(*)").toString().equals("0")) {
            String clNewTickler = newTicklerResult.get(0).get("count(*)").toString();
            entry.add("<a href='#' onclick=\"popupPage('700', '1000', '../tickler/ticklerDemoMain.jsp?demoview="
                    + demographic_no + "'); return false;\">" + clNewTickler + "</a>");
        } else {
            entry.add("&nbsp;");
        }

        // new messages
        String newMsgQuery = "cl_new_msgs";
        List<Map<String, Object>> newMsgResult = caseloadDao.getCaseloadDemographicData(newMsgQuery,
                demographicParam);
        if (!newMsgResult.isEmpty() && newMsgResult.get(0).get("count(*)") != null
                && !newMsgResult.get(0).get("count(*)").toString().equals("")
                && !newMsgResult.get(0).get("count(*)").toString().equals("0")) {
            String clNewMsg = newMsgResult.get(0).get("count(*)").toString();
            entry.add(
                    "<a href='#' onclick=\"popupPage('700', '1000', '../oscarMessenger/DisplayDemographicMessages.do?orderby=date&boxType=3&demographic_no="
                            + demographic_no + "&providerNo=" + curUser_no + "&userName="
                            + URLEncoder.encode(userfirstname + " " + userlastname) + "'); return false;\">"
                            + clNewMsg + "</a>");
        } else {
            entry.add("&nbsp;");
        }

        // measurements
        String msmtQuery = "cl_measurement";
        String[] msmtParam = new String[2];
        msmtParam[1] = demographic_no;

        // BMI
        msmtParam[0] = "BMI";
        List<Map<String, Object>> msmtResult = caseloadDao.getCaseloadDemographicData(msmtQuery, msmtParam);
        if (!msmtResult.isEmpty() && msmtResult.get(0).get("dataField") != null
                && !msmtResult.get(0).get("dataField").toString().equals("")) {
            String clBmi = msmtResult.get(0).get("dataField").toString();
            entry.add(
                    "<a href='#' onclick=\"popupPage('700', '1000', '../oscarEncounter/oscarMeasurements/SetupDisplayHistory.do?demographicNo="
                            + demographic_no + "&type=BMI'); return false;\">" + clBmi + "</a>");
        } else {
            entry.add("&nbsp;");
        }

        // BP
        msmtParam[0] = "BP";
        msmtResult = caseloadDao.getCaseloadDemographicData(msmtQuery, msmtParam);
        if (!msmtResult.isEmpty() && msmtResult.get(0).get("dataField") != null
                && !msmtResult.get(0).get("dataField").toString().equals("")) {
            String clBp = msmtResult.get(0).get("dataField").toString();
            entry.add(
                    "<a href='#' onclick=\"popupPage('700', '1000', '../oscarEncounter/oscarMeasurements/SetupDisplayHistory.do?demographicNo="
                            + demographic_no + "&type=BP'); return false;\">" + clBp + "</a>");
        } else {
            entry.add("&nbsp;");
        }

        // WT
        msmtParam[0] = "WT";
        msmtResult = caseloadDao.getCaseloadDemographicData(msmtQuery, msmtParam);
        if (!msmtResult.isEmpty() && msmtResult.get(0).get("dataField") != null
                && !msmtResult.get(0).get("dataField").toString().equals("")) {
            String clWt = msmtResult.get(0).get("dataField").toString();
            entry.add(
                    "<a href='#' onclick=\"popupPage('700', '1000', '../oscarEncounter/oscarMeasurements/SetupDisplayHistory.do?demographicNo="
                            + demographic_no + "&type=WT'); return false;\">" + clWt + "</a>");
        } else {
            entry.add("&nbsp;");
        }

        // SMK
        msmtParam[0] = "SMK";
        msmtResult = caseloadDao.getCaseloadDemographicData(msmtQuery, msmtParam);
        if (!msmtResult.isEmpty() && msmtResult.get(0).get("dataField") != null
                && !msmtResult.get(0).get("dataField").toString().equals("")) {
            String clSmk = msmtResult.get(0).get("dataField").toString();
            entry.add(
                    "<a href='#' onclick=\"popupPage('700', '1000', '../oscarEncounter/oscarMeasurements/SetupDisplayHistory.do?demographicNo="
                            + demographic_no + "&type=SMK'); return false;\">" + clSmk + "</a>");
        } else {
            entry.add("&nbsp;");
        }

        // A1C
        msmtParam[0] = "A1C";
        msmtResult = caseloadDao.getCaseloadDemographicData(msmtQuery, msmtParam);
        if (!msmtResult.isEmpty() && msmtResult.get(0).get("dataField") != null
                && !msmtResult.get(0).get("dataField").toString().equals("")) {
            String clA1c = msmtResult.get(0).get("dataField").toString();
            entry.add(
                    "<a href='#' onclick=\"popupPage('700', '1000', '../oscarEncounter/oscarMeasurements/SetupDisplayHistory.do?demographicNo="
                            + demographic_no + "&type=A1C'); return false;\">" + clA1c + "</a>");
        } else {
            entry.add("&nbsp;");
        }

        // ACR
        msmtParam[0] = "ACR";
        msmtResult = caseloadDao.getCaseloadDemographicData(msmtQuery, msmtParam);
        if (!msmtResult.isEmpty() && msmtResult.get(0).get("dataField") != null
                && !msmtResult.get(0).get("dataField").toString().equals("")) {
            String clAcr = msmtResult.get(0).get("dataField").toString();
            entry.add(
                    "<a href='#' onclick=\"popupPage('700', '1000', '../oscarEncounter/oscarMeasurements/SetupDisplayHistory.do?demographicNo="
                            + demographic_no + "&type=ACR'); return false;\">" + clAcr + "</a>");
        } else {
            entry.add("&nbsp;");
        }

        // SCR
        msmtParam[0] = "SCR";
        msmtResult = caseloadDao.getCaseloadDemographicData(msmtQuery, msmtParam);
        if (!msmtResult.isEmpty() && msmtResult.get(0).get("dataField") != null
                && !msmtResult.get(0).get("dataField").toString().equals("")) {
            String clScr = msmtResult.get(0).get("dataField").toString();
            entry.add(
                    "<a href='#' onclick=\"popupPage('700', '1000', '../oscarEncounter/oscarMeasurements/SetupDisplayHistory.do?demographicNo="
                            + demographic_no + "&type=SCR'); return false;\">" + clScr + "</a>");
        } else {
            entry.add("&nbsp;");
        }

        // LDL
        msmtParam[0] = "LDL";
        msmtResult = caseloadDao.getCaseloadDemographicData(msmtQuery, msmtParam);
        if (!msmtResult.isEmpty() && msmtResult.get(0).get("dataField") != null
                && !msmtResult.get(0).get("dataField").toString().equals("")) {
            String clLdl = msmtResult.get(0).get("dataField").toString();
            entry.add(
                    "<a href='#' onclick=\"popupPage('700', '1000', '../oscarEncounter/oscarMeasurements/SetupDisplayHistory.do?demographicNo="
                            + demographic_no + "&type=LDL'); return false;\">" + clLdl + "</a>");
        } else {
            entry.add("&nbsp;");
        }

        // HDL
        msmtParam[0] = "HDL";
        msmtResult = caseloadDao.getCaseloadDemographicData(msmtQuery, msmtParam);
        if (!msmtResult.isEmpty() && msmtResult.get(0).get("dataField") != null
                && !msmtResult.get(0).get("dataField").toString().equals("")) {
            String clHdl = msmtResult.get(0).get("dataField").toString();
            entry.add(
                    "<a href='#' onclick=\"popupPage('700', '1000', '../oscarEncounter/oscarMeasurements/SetupDisplayHistory.do?demographicNo="
                            + demographic_no + "&type=HDL'); return false;\">" + clHdl + "</a>");
        } else {
            entry.add("&nbsp;");
        }

        // TCHD
        msmtParam[0] = "TCHD";
        msmtResult = caseloadDao.getCaseloadDemographicData(msmtQuery, msmtParam);
        if (!msmtResult.isEmpty() && msmtResult.get(0).get("dataField") != null
                && !msmtResult.get(0).get("dataField").toString().equals("")) {
            String clTchd = msmtResult.get(0).get("dataField").toString();
            entry.add(
                    "<a href='#' onclick=\"popupPage('700', '1000', '../oscarEncounter/oscarMeasurements/SetupDisplayHistory.do?demographicNo="
                            + demographic_no + "&type=TCHD'); return false;\">" + clTchd + "</a>");
        } else {
            entry.add("&nbsp;");
        }

        // EGFR
        msmtParam[0] = "EGFR";
        msmtResult = caseloadDao.getCaseloadDemographicData(msmtQuery, msmtParam);
        if (!msmtResult.isEmpty() && msmtResult.get(0).get("dataField") != null
                && !msmtResult.get(0).get("dataField").toString().equals("")) {
            String clEgfr = msmtResult.get(0).get("dataField").toString();
            entry.add(
                    "<a href='#' onclick=\"popupPage('700', '1000', '../oscarEncounter/oscarMeasurements/SetupDisplayHistory.do?demographicNo="
                            + demographic_no + "&type=EGFR'); return false;\">" + clEgfr + "</a>");
        } else {
            entry.add("&nbsp;");
        }

        // EYEE
        msmtParam[0] = "EYEE";
        msmtResult = caseloadDao.getCaseloadDemographicData(msmtQuery, msmtParam);
        if (!msmtResult.isEmpty() && msmtResult.get(0).get("dataField") != null
                && !msmtResult.get(0).get("dataField").toString().equals("")) {
            String clEyee = msmtResult.get(0).get("dataField").toString();
            entry.add(
                    "<a href='#' onclick=\"popupPage('700', '1000', '../oscarEncounter/oscarMeasurements/SetupDisplayHistory.do?demographicNo="
                            + demographic_no + "&type=EYEE'); return false;\">" + clEyee + "</a>");
        } else {
            entry.add("&nbsp;");
        }

        data.add(entry);
    }
    return data;
}

From source file:org.openmrs.module.kenyaemr.fragment.controller.patient.ImportPatientsListFragmentController.java

@SuppressWarnings("deprecation")
public Object submit(HttpServletRequest request) throws Exception {
    // Constant values used across all the code

    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile multipartModuleFile = multipartRequest.getFile("upload");
    InputStream inputStream = multipartModuleFile.getInputStream();
    Workbook workbook = new XSSFWorkbook(inputStream);

    Sheet firstSheet = workbook.getSheetAt(0);
    Iterator<Row> iterator = firstSheet.iterator();
    int rowCount = 0;

    while (iterator.hasNext()) {
        Row nextRow = iterator.next();//www .ja  v  a  2 s. c  om
        Iterator<Cell> cellIterator = nextRow.cellIterator();
        try {
            if (rowCount > 0) {

                ArrayList<String> legacyData = new ArrayList<String>();
                int columnCount = 0;

                while (cellIterator.hasNext() && columnCount < 31) {
                    Cell cell = cellIterator.next();
                    switch (cell.getCellType()) {
                    case Cell.CELL_TYPE_STRING:
                        legacyData.add(cell.getColumnIndex(), cell.getStringCellValue().trim());
                        break;
                    case Cell.CELL_TYPE_NUMERIC:
                        if (HSSFDateUtil.isCellDateFormatted(cell)) {
                            legacyData.add(cell.getColumnIndex(), String.valueOf(cell.getDateCellValue()));

                        } else {

                            legacyData.add(cell.getColumnIndex(),
                                    NumberToTextConverter.toText(cell.getNumericCellValue()));
                        }
                        break;
                    case Cell.CELL_TYPE_BLANK:
                        legacyData.add(cell.getColumnIndex(), null);
                        break;
                    }
                    columnCount++;
                }
                int i = 0;
                for (String s : legacyData) {
                    i++;
                }
                /*
                 * Start Patient Creation
                 */
                try {
                    if (legacyData.get(0) != null) {
                        Patient toSave = new Patient(); // Creating a new
                        // patient
                        // and
                        // person
                        PersonName personName = new PersonName();
                        PersonAddress personAddress = new PersonAddress();
                        Location location;

                        SimpleDateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
                        Date dateBith = new Date();
                        try {
                            dateBith = (Date) formatter.parse(legacyData.get(2));

                        } catch (ParseException e) {
                            e.printStackTrace();
                        }

                        toSave.setGender(legacyData.get(3));
                        toSave.setBirthdate(dateBith);
                        toSave.setBirthdateEstimated(false);
                        toSave.setDead(false);
                        /*
                         * toSave.setDeathDate(deathDate);
                         * toSave.setCauseOfDeath(dead ? Dictionary
                         * .getConcept(CAUSE_OF_DEATH_PLACEHOLDER) : null);
                         */

                        if (legacyData.get(1) != "") {
                            personName.setGivenName(legacyData.get(1));

                            personName.setFamilyName("(NULL)");
                            toSave.addName(personName);
                        }

                        // toSave.
                        personAddress.setAddress1(legacyData.get(9));
                        personAddress.setCountyDistrict(legacyData.get(10));
                        toSave.addAddress(personAddress);

                        PatientWrapper wrapper = new PatientWrapper(toSave);

                        wrapper.getPerson().setTelephoneContact(legacyData.get(8));

                        location = Context.getService(KenyaEmrService.class).getDefaultLocation();

                        if (legacyData.get(4) != null) {
                            wrapper.setPreArtRegistrationNumber(legacyData.get(4), location);
                        }

                        if (legacyData.get(6) != null) {
                            wrapper.setArtRegistrationNumber(legacyData.get(6), location);
                        }

                        if (legacyData.get(5) != null) {
                            wrapper.setNapArtRegistrationNumber(legacyData.get(5), location);
                        }

                        // Algorithm to generate system generated patient
                        // Identifier
                        Calendar now = Calendar.getInstance();
                        String shortName = Context.getAdministrationService()
                                .getGlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_PATIENT_IDENTIFIER_PREFIX);

                        String noCheck = shortName + String.valueOf(now.get(Calendar.YEAR)).substring(2, 4)
                                + String.valueOf(now.get(Calendar.MONTH) + 1)
                                + String.valueOf(now.get(Calendar.DATE))

                                + String.valueOf(now.get(Calendar.HOUR))
                                + String.valueOf(now.get(Calendar.MINUTE))
                                + String.valueOf(now.get(Calendar.SECOND))
                                + String.valueOf(new Random().nextInt(9999 - 999 + 1));

                        wrapper.setSystemPatientId(noCheck + "-" + generateCheckdigit(noCheck), location);

                        wrapper.setNextOfKinName(legacyData.get(11));
                        wrapper.setNextOfKinContact(legacyData.get(12));

                        if (legacyData.get(13) != null) {
                            wrapper.setPreviousHivTestStatus("Yes");
                            wrapper.setPreviousHivTestPlace(legacyData.get(14));

                            Date capturedTestDate = new Date();
                            try {
                                capturedTestDate = formatter.parse(legacyData.get(13));

                            } catch (ParseException e) {
                                e.printStackTrace();
                            }

                            DateFormat testDate = new SimpleDateFormat("dd-MMMM-yyyy");
                            wrapper.setPreviousHivTestDate(testDate.format(capturedTestDate));
                        } else {
                            wrapper.setPreviousHivTestStatus("No");
                        }

                        wrapper.setPreviousClinicName(legacyData.get(16));

                        // Make sure everyone gets an OpenMRS ID
                        PatientIdentifierType openmrsIdType = MetadataUtils.existing(
                                PatientIdentifierType.class, CommonMetadata._PatientIdentifierType.OPENMRS_ID);
                        PatientIdentifier openmrsId = toSave.getPatientIdentifier(openmrsIdType);

                        if (openmrsId == null) {
                            String generated = Context.getService(IdentifierSourceService.class)
                                    .generateIdentifier(openmrsIdType, "Registration");
                            openmrsId = new PatientIdentifier(generated, openmrsIdType, location);
                            toSave.addIdentifier(openmrsId);

                            if (!toSave.getPatientIdentifier().isPreferred()) {
                                openmrsId.setPreferred(true);
                            }
                        }

                        Patient ret = Context.getPatientService().savePatient(toSave);

                        // Explicitly save all identifier objects including
                        // voided
                        for (PatientIdentifier identifier : toSave.getIdentifiers()) {
                            Context.getPatientService().savePatientIdentifier(identifier);
                        }

                        /*
                         * End Patient Creation
                         */

                        /**
                         ** Start : Visit, Encounter and Program creation for
                         * Patient entered as Legacy Data Visit start date
                         **/
                        Date curDate = new Date();
                        Date dateVisit = null;
                        try {
                            dateVisit = formatter.parse(legacyData.get(18));

                        } catch (ParseException e) {
                            e.printStackTrace();
                        }

                        DateFormat visitDateInExcel = new SimpleDateFormat("dd-MMM-yyyy");
                        String dateCheck = visitDateInExcel.format(dateVisit);
                        SimpleDateFormat mysqlDateTimeFormatter = new SimpleDateFormat("dd-MMM-yy HH:mm:ss");

                        if (legacyData.get(18) != null) {
                            try {
                                dateVisit = mysqlDateTimeFormatter.parse(dateCheck + " " + curDate.getHours()
                                        + ":" + curDate.getMinutes() + ":" + curDate.getSeconds());
                            } catch (ParseException e) {
                                dateVisit = curDate;
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }
                        }

                        Visit visit = new Visit();
                        visit.setPatient(ret);
                        visit.setStartDatetime(dateVisit);
                        visit.setVisitType(
                                MetadataUtils.existing(VisitType.class, CommonMetadata._VisitType.OUTPATIENT));
                        visit.setLocation(Context.getService(KenyaEmrService.class).getDefaultLocation());

                        VisitAttributeType attrType = Context.getService(VisitService.class)
                                .getVisitAttributeTypeByUuid(CommonMetadata._VisitAttributeType.NEW_PATIENT);
                        if (attrType != null) {
                            VisitAttribute attr = new VisitAttribute();
                            attr.setAttributeType(attrType);
                            attr.setVisit(visit);
                            attr.setDateCreated(curDate);
                            attr.setValue(true);
                            visit.addAttribute(attr);
                        }

                        Visit visitSave = Context.getVisitService().saveVisit(visit);

                        // With value text and Date
                        if (legacyData.get(15) != null) {

                            Date dateTransfer = null;
                            if (legacyData.get(17) != null) {
                                try {
                                    dateTransfer = formatter.parse(legacyData.get(17));

                                } catch (ParseException e) {
                                    e.printStackTrace();
                                }
                            }

                            Concept enrollementConcept = Context.getConceptService()
                                    .getConcept(Integer.parseInt(legacyData.get(15)));

                            handleOncePerPatientObs(ret, Dictionary.getConcept(Dictionary.METHOD_OF_ENROLLMENT),
                                    enrollementConcept, "", dateTransfer, null, visitSave);
                        }

                        if (legacyData.get(7) != null) {
                            Concept ingoConcept = Context.getConceptService()
                                    .getConcept(Integer.parseInt(legacyData.get(7)));
                            handleOncePerPatientObs(ret, Dictionary.getConcept(Dictionary.INGO_NAME),
                                    ingoConcept, "", null, null, visitSave);
                        }

                        EncounterType hivEnrollEncType = MetadataUtils.existing(EncounterType.class,
                                HivMetadata._EncounterType.HIV_ENROLLMENT);

                        EncounterType registrationEncType = MetadataUtils.existing(EncounterType.class,
                                CommonMetadata._EncounterType.REGISTRATION);

                        Encounter hivEnrollmentEncounter = new Encounter();

                        hivEnrollmentEncounter.setEncounterType(hivEnrollEncType);
                        hivEnrollmentEncounter.setPatient(ret);
                        hivEnrollmentEncounter
                                .setLocation(Context.getService(KenyaEmrService.class).getDefaultLocation());

                        hivEnrollmentEncounter.setDateCreated(curDate);
                        hivEnrollmentEncounter.setEncounterDatetime(dateVisit);

                        hivEnrollmentEncounter
                                .setForm(MetadataUtils.existing(Form.class, HivMetadata._Form.HIV_ENROLLMENT));
                        hivEnrollmentEncounter.setVisit(visitSave);
                        hivEnrollmentEncounter.setVoided(false);
                        Encounter enHivNew = Context.getEncounterService()
                                .saveEncounter(hivEnrollmentEncounter);

                        PatientProgram patientProgram = new PatientProgram();
                        patientProgram.setPatient(ret);
                        patientProgram
                                .setProgram(MetadataUtils.existing(Program.class, HivMetadata._Program.HIV));
                        patientProgram.setDateEnrolled(enHivNew.getEncounterDatetime());
                        patientProgram.setDateCreated(curDate);
                        Context.getProgramWorkflowService().savePatientProgram(patientProgram);

                        Encounter personalEncounter = new Encounter();

                        personalEncounter.setEncounterType(hivEnrollEncType);
                        personalEncounter.setPatient(ret);

                        personalEncounter.setDateCreated(curDate);
                        personalEncounter.setEncounterDatetime(dateVisit);
                        personalEncounter
                                .setLocation(Context.getService(KenyaEmrService.class).getDefaultLocation());

                        personalEncounter.setForm(
                                MetadataUtils.existing(Form.class, Metadata.Form.HIV_PERSONAL_HISTORY));
                        personalEncounter.setVisit(visitSave);
                        personalEncounter.setVoided(false);
                        Encounter enpersonalrecordresultNew = Context.getEncounterService()
                                .saveEncounter(personalEncounter);
                        if (legacyData.get(19) != null) {

                            Concept literate = Context.getConceptService()
                                    .getConcept(Integer.parseInt(legacyData.get(19)));
                            handleOncePerPatientObs(ret, Dictionary.getConcept(Dictionary.LITERATE), literate,
                                    "", null, null, enpersonalrecordresultNew, null, visitSave);

                        }
                        if (legacyData.get(21) != null) {

                            String value = legacyData.get(21);

                            String[] valueList = value.split("\\s*,\\s*");

                            for (String riskname : valueList) {

                                Concept riskConcept = Context.getConceptService().getConcept(riskname);

                                handleOncePerPatientObs(ret, Dictionary.getConcept(Dictionary.HIV_RISK_FACTOR),
                                        riskConcept, "", null, null, enpersonalrecordresultNew, null,
                                        visitSave);

                            }

                        }
                        if (legacyData.get(22) != null) {

                            Concept idssubstituion = Context.getConceptService()
                                    .getConcept(Integer.parseInt(legacyData.get(22)));
                            handleOncePerPatientObs(ret, Dictionary.getConcept(Dictionary.IDU_PERSONAL_HISTORY),
                                    idssubstituion, "", null, null, enpersonalrecordresultNew, null, visitSave);

                        }

                        if (legacyData.get(23) != null) {

                            Concept idssubstituionvalue = Context.getConceptService()
                                    .getConcept(Integer.parseInt(legacyData.get(23)));
                            handleOncePerPatientObs(ret,
                                    Dictionary.getConcept(Dictionary.IDU_NAME_PERSONAL_HISTORY),
                                    idssubstituionvalue, "", null, null, enpersonalrecordresultNew, null,
                                    visitSave);

                        }
                        if (legacyData.get(29) != null) {

                            Concept employedvalue = Context.getConceptService()
                                    .getConcept(Integer.parseInt(legacyData.get(29)));
                            handleOncePerPatientObs(ret, Dictionary.getConcept(Dictionary.EMPLOYED),
                                    employedvalue, "", null, null, enpersonalrecordresultNew, null, visitSave);
                        }

                        if (legacyData.get(30) != null) {

                            Concept alcoholicvalue = Context.getConceptService()
                                    .getConcept(Integer.parseInt(legacyData.get(30)));
                            handleOncePerPatientObs(ret, Dictionary.getConcept(Dictionary.ALCOHOLIC_TYPE),
                                    alcoholicvalue, "", null, null, enpersonalrecordresultNew, null, visitSave);
                        }

                        Encounter familyEncounter = new Encounter();

                        familyEncounter.setEncounterType(registrationEncType);
                        familyEncounter.setPatient(ret);

                        familyEncounter.setDateCreated(curDate);
                        familyEncounter.setEncounterDatetime(dateVisit);
                        familyEncounter
                                .setLocation(Context.getService(KenyaEmrService.class).getDefaultLocation());

                        familyEncounter
                                .setForm(MetadataUtils.existing(Form.class, Metadata.Form.HIV_FAMILY_HISTORY));
                        familyEncounter.setVisit(visitSave);
                        familyEncounter.setVoided(false);
                        Encounter enfamilyrecordresultNew = Context.getEncounterService()
                                .saveEncounter(familyEncounter);
                        if (legacyData.get(20) != null) {

                            Concept martalstatus = Context.getConceptService()
                                    .getConcept(Integer.parseInt(legacyData.get(20)));
                            handleOncePerPatientObs(ret, Dictionary.getConcept(Dictionary.CIVIL_STATUS),
                                    martalstatus, "", null, null, enfamilyrecordresultNew, null, visitSave);
                        }

                        Encounter drugEncounter = new Encounter();

                        drugEncounter.setEncounterType(hivEnrollEncType);
                        drugEncounter.setPatient(ret);

                        drugEncounter.setDateCreated(curDate);
                        drugEncounter.setEncounterDatetime(dateVisit);
                        drugEncounter
                                .setLocation(Context.getService(KenyaEmrService.class).getDefaultLocation());

                        drugEncounter
                                .setForm(MetadataUtils.existing(Form.class, Metadata.Form.HIV_DRUG_HISTORY));
                        drugEncounter.setVisit(visitSave);
                        drugEncounter.setVoided(false);
                        Encounter endrugrecordresultNew = Context.getEncounterService()
                                .saveEncounter(drugEncounter);

                        if (legacyData.get(24) != null) {

                            Concept drughistoryart = Context.getConceptService()
                                    .getConcept(Integer.parseInt(legacyData.get(24)));

                            handleOncePerPatientObs(ret,
                                    Dictionary.getConcept(Dictionary.DRUG_HISTORY_ART_RECEIVED), drughistoryart,
                                    "", null, null, endrugrecordresultNew, null, visitSave);

                        }

                        if (legacyData.get(25) != null) {

                            Concept drughistoryarttype = Context.getConceptService()
                                    .getConcept(Integer.parseInt(legacyData.get(25)));

                            handleOncePerPatientObs(ret,
                                    Dictionary.getConcept(Dictionary.DRUG_HISTORY_ART_RECEIVED_TYPE),
                                    drughistoryarttype, "", null, null, endrugrecordresultNew, null, visitSave);

                        }

                        if (legacyData.get(26) != null && legacyData.get(27) != null
                                && legacyData.get(28) != null) {

                            boolean value = false;
                            Obs drugtreatmentGroup = new Obs();
                            drugtreatmentGroup.setPerson(ret);
                            drugtreatmentGroup.setConcept(Dictionary.getConcept(Dictionary.DRUG_HISTORY_GROUP));

                            drugtreatmentGroup.setObsDatetime(endrugrecordresultNew.getEncounterDatetime());

                            // Added value coded as per default obs object
                            // format.
                            //drugtreatmentGroup.setValueCoded(null);
                            // drugtreatmentGroup.setValueText(text);
                            drugtreatmentGroup.setLocation(
                                    Context.getService(KenyaEmrService.class).getDefaultLocation());

                            drugtreatmentGroup.setEncounter(endrugrecordresultNew);

                            drugtreatmentGroup.setValueBoolean(value);
                            Obs drugtreat = Context.getObsService().saveObs(drugtreatmentGroup,
                                    "KenyaEMR History Details");
                            if (legacyData.get(26) != null) {

                                Concept place = Context.getConceptService()
                                        .getConcept(Integer.parseInt(legacyData.get(26)));
                                handleOncePerPatientObs(ret,
                                        Dictionary.getConcept(Dictionary.DRUG_HISTORY_ART_RECEIVED_PLACE),
                                        place, "", null, null, endrugrecordresultNew, drugtreat, visitSave);
                            }

                            if (legacyData.get(27) != null) {

                                Concept drugarv = Context.getConceptService()
                                        .getConcept(Integer.parseInt(legacyData.get(27)));
                                handleOncePerPatientObs(ret,
                                        Dictionary.getConcept(Dictionary.DRUG_REGIMEN_DRUG_HISTORY), drugarv,
                                        "", null, null, endrugrecordresultNew, drugtreat, visitSave);
                            }

                            if (legacyData.get(28) != null) {

                                Double dur = 0.0;
                                Integer durationreslt = 0;

                                durationreslt = Integer.parseInt(legacyData.get(28));
                                dur = durationreslt.doubleValue();
                                handleOncePerPatientObs(ret, Dictionary.getConcept(Dictionary.DRUG_DURATION),
                                        null, null, null, dur, endrugrecordresultNew, drugtreat, visitSave);

                            }

                        }

                        /*
                         * End : Visit, Encounter and Program creation for
                         * Patient entered as Legacy Data
                         */

                    }
                } catch (IndexOutOfBoundsException e) {
                    break;
                }
            }
        } catch (IndexOutOfBoundsException e) {
            break;
        }

        rowCount++;
    }

    int noOfSheets = workbook.getNumberOfSheets();

    if (noOfSheets > 1) {
        Sheet secondSheet = workbook.getSheetAt(1);
        Iterator<Row> iteratorSecond = secondSheet.iterator();
        int rowCountVisit = 0;
        while (iteratorSecond.hasNext()) {
            Row nextRow = iteratorSecond.next();
            Iterator<Cell> cellIterator = nextRow.cellIterator();
            try {

                if (rowCountVisit > 0) {
                    ArrayList<String> legacyData = new ArrayList<String>();
                    int columnCount = 0;
                    while (cellIterator.hasNext() && columnCount < 44) {
                        Cell cell = cellIterator.next();

                        switch (cell.getCellType()) {
                        case Cell.CELL_TYPE_STRING:
                            legacyData.add(cell.getColumnIndex(), cell.getStringCellValue().trim());
                            break;
                        case Cell.CELL_TYPE_NUMERIC:
                            if (HSSFDateUtil.isCellDateFormatted(cell)) {
                                legacyData.add(cell.getColumnIndex(), String.valueOf(cell.getDateCellValue()));

                            } else {

                                legacyData.add(cell.getColumnIndex(),
                                        NumberToTextConverter.toText(cell.getNumericCellValue()));

                            }
                            break;
                        case Cell.CELL_TYPE_BLANK:
                            legacyData.add(cell.getColumnIndex(), "");
                            break;
                        }
                        columnCount++;
                    }

                    int i = 0;
                    for (String s : legacyData) {
                        i++;
                    }
                    Person person = null;
                    Patient patient = null;
                    PatientWrapper wrapper = null;
                    int count = 0;
                    Location location;
                    location = Context.getService(KenyaEmrService.class).getDefaultLocation();

                    if (legacyData.get(3) != null && legacyData.get(3) != "") {
                        try {

                            if (!legacyData.get(0).isEmpty()) {
                                PatientIdentifierType pt = Context.getPatientService()
                                        .getPatientIdentifierTypeByUuid("d59d0f67-4a05-4e41-bfad-342da68feb6f");

                                List<PatientIdentifier> patList = Context.getPatientService()
                                        .getPatientIdentifiers(legacyData.get(0).toString(), pt);

                                for (PatientIdentifier p : patList) {
                                    patient = Context.getPatientService()
                                            .getPatient(p.getPatient().getPatientId());
                                    wrapper = new PatientWrapper(patient);
                                    person = Context.getPersonService().getPerson(patient);
                                }
                            }

                            else if (!legacyData.get(1).isEmpty()) {
                                PatientIdentifierType pt = Context.getPatientService()
                                        .getPatientIdentifierTypeByUuid("3e5493e8-e76e-4d3f-a166-9a88b40747fa");

                                List<PatientIdentifier> patList = Context.getPatientService()
                                        .getPatientIdentifiers(legacyData.get(1).toString(), pt);

                                for (PatientIdentifier p : patList) {

                                    patient = Context.getPatientService()
                                            .getPatient(p.getPatient().getPatientId());
                                    wrapper = new PatientWrapper(patient);
                                    person = Context.getPersonService().getPerson(patient);
                                }

                            } else if (!legacyData.get(2).isEmpty()) {
                                PatientIdentifierType pt = Context.getPatientService()
                                        .getPatientIdentifierTypeByUuid("9e10c5d6-a58c-4236-8b65-b6b932beff1a");
                                List<PatientIdentifier> patList = Context.getPatientService()
                                        .getPatientIdentifiers(legacyData.get(2).toString(), pt);
                                for (PatientIdentifier p : patList) {
                                    patient = Context.getPatientService()
                                            .getPatient(p.getPatient().getPatientId());
                                    wrapper = new PatientWrapper(patient);
                                    person = Context.getPersonService().getPerson(patient);
                                }
                            } else {
                                break;
                            }

                            SimpleDateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
                            Date curDate = new Date();
                            Date dateVisit = null;
                            try {
                                if (legacyData.get(3) != null && legacyData.get(3) != "") {
                                    dateVisit = formatter.parse(legacyData.get(3));
                                }

                            } catch (ParseException e) {

                                e.printStackTrace();
                            }
                            DateFormat visitDateInExcel = new SimpleDateFormat("dd-MMM-yyyy");
                            String dateCheck = "";
                            SimpleDateFormat mysqlDateTimeFormatter = new SimpleDateFormat(
                                    "dd-MMM-yy HH:mm:ss");
                            if (legacyData.get(3) != null && legacyData.get(3) != "") {
                                Date curDatenew = new Date();
                                dateCheck = visitDateInExcel.format(dateVisit);
                                try {
                                    dateVisit = mysqlDateTimeFormatter
                                            .parse(dateCheck + " " + curDatenew.getHours() + ":"
                                                    + curDatenew.getMinutes() + ":" + curDatenew.getSeconds());

                                } catch (ParseException e) {
                                    dateVisit = curDatenew;
                                    e.printStackTrace();
                                }
                            }

                            List<Visit> visits = Context.getVisitService().getActiveVisitsByPatient(patient);

                            Visit v = new Visit();
                            if (visits.isEmpty()) {
                                Visit visit = new Visit();
                                visit.setPatient(patient);
                                visit.setStartDatetime(dateVisit);
                                visit.setVisitType(MetadataUtils.existing(VisitType.class,
                                        CommonMetadata._VisitType.OUTPATIENT));
                                visit.setLocation(
                                        Context.getService(KenyaEmrService.class).getDefaultLocation());
                                if (person.getDead() == false) {
                                    v = Context.getVisitService().saveVisit(visit);
                                }

                            } else {
                                for (Visit vLoop : visits) {
                                    v = vLoop;

                                }
                            }

                            if (v.getId() != null) {
                                EncounterType artEnrollEncType = MetadataUtils.existing(EncounterType.class,
                                        ArtMetadata._EncounterType.INITIATE_ART);
                                Encounter artEncounter = new Encounter();

                                artEncounter.setEncounterType(artEnrollEncType);
                                artEncounter.setPatient(patient);
                                artEncounter.setLocation(
                                        Context.getService(KenyaEmrService.class).getDefaultLocation());

                                artEncounter.setDateCreated(curDate);
                                artEncounter.setEncounterDatetime(dateVisit);

                                artEncounter.setForm(
                                        MetadataUtils.existing(Form.class, ArtMetadata._Form.INITIATE_ART));
                                artEncounter.setVisit(v);

                                artEncounter.setVoided(false);
                                if (!legacyData.get(9).isEmpty()) {

                                    Encounter enartNew = Context.getEncounterService()
                                            .saveEncounter(artEncounter);
                                }
                                PatientProgram pp = new PatientProgram();
                                if (!legacyData.get(9).isEmpty()) {

                                    pp.setPatient(patient);
                                    pp.setProgram(
                                            MetadataUtils.existing(Program.class, ArtMetadata._Program.ART));

                                    Date artStartDate = null;
                                    Date curDatenew = new Date();

                                    try {
                                        artStartDate = (Date) formatter.parse(legacyData.get(9));
                                        dateCheck = visitDateInExcel.format(artStartDate);
                                        artStartDate = mysqlDateTimeFormatter.parse(dateCheck + " "
                                                + curDatenew.getHours() + ":" + curDatenew.getMinutes() + ":"
                                                + curDatenew.getSeconds());
                                        pp.setDateEnrolled(artStartDate);
                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                    }

                                    if (pp.getDateEnrolled() != null && pp.getDateCompleted() == null) {
                                        PatientProgram program = Context.getProgramWorkflowService()
                                                .savePatientProgram(pp);
                                    }

                                }

                                /*
                                 * Changes code
                                 */
                                String reg = "";

                                if (!legacyData.get(4).isEmpty()) {

                                    Concept regimenConcept = Context.getConceptService()
                                            .getConcept(Integer.parseInt(legacyData.get(4)));
                                    reg = reg.concat(regimenConcept.getName().toString());

                                    KenyaEmrService kes = (KenyaEmrService) Context
                                            .getService(KenyaEmrService.class);

                                    List<DrugOrderProcessed> dopp = kes.getDrugOrderProcessedByPatient(patient);

                                    // Created drug order processed
                                    DrugOrderProcessed orderprocess = new DrugOrderProcessed();

                                    orderprocess.setPatient(patient);
                                    orderprocess.setDrugRegimen(reg);
                                    orderprocess.setCreatedDate(dateVisit);
                                    orderprocess.setStartDate(dateVisit);
                                    orderprocess.setVisit(v);
                                    orderprocess.setRoute(Context.getConceptService()
                                            .getConceptByUuid("160240AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
                                    Integer tablet = 0;

                                    if (legacyData.get(4).equals("163494") || legacyData.get(4).equals("163495")
                                            || legacyData.get(4).equals("163496")
                                            || legacyData.get(4).equals("162959")
                                            || legacyData.get(4).equals("163503")
                                            || legacyData.get(4).equals("163505")
                                            || legacyData.get(4).equals("163506")
                                            || legacyData.get(4).equals(" 163507")
                                            || legacyData.get(4).equals("163508")
                                            || legacyData.get(4).equals("163510")) {

                                        orderprocess.setNoOfTablet(1);
                                        tablet = Integer.parseInt(legacyData.get(6));
                                    } else {
                                        tablet = Integer.parseInt(legacyData.get(6)) * 2;
                                        orderprocess.setNoOfTablet(2);
                                    }

                                    if (!legacyData.get(6).isEmpty()) {
                                        orderprocess.setDurationPreProcess(Integer.parseInt(legacyData.get(6)));

                                        orderprocess.setQuantityPostProcess(tablet);

                                        orderprocess.setProcessedStatus(true);
                                        try {
                                            Date curDat = new Date();

                                            dateVisit = mysqlDateTimeFormatter
                                                    .parse(dateCheck + " " + curDat.getHours() + ":"
                                                            + curDat.getMinutes() + ":" + curDat.getSeconds());

                                            orderprocess.setProcessedDate(dateVisit);

                                        } catch (ParseException e) {
                                            e.printStackTrace();
                                        }
                                    }

                                    if (!legacyData.get(5).isEmpty()) {
                                        orderprocess.setDose(legacyData.get(5));
                                        orderprocess.setDoseRegimen(legacyData.get(5));
                                    }
                                    String cahngeRegimenType = "";
                                    if (patient.getAge() > 14) {
                                        for (String firstline : firstlineConcept) {
                                            if (legacyData.get(4).equals(firstline)) {
                                                orderprocess
                                                        .setTypeOfRegimen("First line Anti-retoviral drugs");
                                                cahngeRegimenType = "First line Anti-retoviral drugs";
                                            }
                                        }
                                        for (String secndline : secondlineConcept) {
                                            if (legacyData.get(4).equals(secndline)) {
                                                orderprocess.setTypeOfRegimen("Second line ART");
                                                cahngeRegimenType = "Second line ART";
                                            }
                                        }
                                        for (String thirdline : thirdlineConcept) {
                                            if (legacyData.get(4).equals(thirdline)) {
                                                orderprocess.setTypeOfRegimen("HIV/HBV co-infection");
                                                cahngeRegimenType = "HIV/HBV co-infection";
                                            }
                                        }
                                    } else {
                                        for (String child : childArvConcept) {
                                            if (legacyData.get(4).equals(child)) {
                                                orderprocess.setTypeOfRegimen("ARV drugs for child");
                                                cahngeRegimenType = "ARV drugs for child";

                                            }
                                        }
                                    }

                                    if (dopp.size() == 0) {
                                        orderprocess.setRegimenChangeType("Start");
                                        // Encounter Created
                                        EncounterType regEnrollEncType = MetadataUtils.existing(
                                                EncounterType.class,
                                                CommonMetadata._EncounterType.REGIMEN_ORDER);

                                        Encounter regEncounter = new Encounter();
                                        regEncounter.setEncounterType(regEnrollEncType);
                                        regEncounter.setPatient(patient);
                                        regEncounter.setLocation(Context.getLocationService()
                                                .getLocationByUuid("8d6c993e-c2cc-11de-8d13-0010c6dffd0f"));

                                        regEncounter.setDateCreated(curDate);
                                        regEncounter.setEncounterDatetime(dateVisit);
                                        regEncounter.setVisit(v);

                                        regEncounter.setVoided(false);

                                        // Save encounter
                                        Encounter enregNew = Context.getEncounterService()
                                                .saveEncounter(regEncounter);

                                        // Create order
                                        Order ordersave = new Order();

                                        // Create Drug order
                                        DrugOrder dod = new DrugOrder();

                                        dod.setOrderType(Context.getOrderService().getOrderType(2));
                                        dod.setConcept(Context.getConceptService()
                                                .getConcept(Integer.parseInt(legacyData.get(4))));
                                        dod.setEncounter(enregNew);

                                        dod.setStartDate(dateVisit);
                                        dod.setDateCreated(curDate);
                                        dod.setPatient(patient);
                                        dod.setUnits("tab");
                                        if (legacyData.get(4).equals("163494")
                                                || legacyData.get(4).equals("163495")
                                                || legacyData.get(4).equals("163496")
                                                || legacyData.get(4).equals("162959")
                                                || legacyData.get(4).equals("163503")
                                                || legacyData.get(4).equals("163505")
                                                || legacyData.get(4).equals("163506")
                                                || legacyData.get(4).equals(" 163507")
                                                || legacyData.get(4).equals("163508")
                                                || legacyData.get(4).equals("163510")) {

                                            dod.setFrequency("od");
                                        } else {
                                            dod.setFrequency("bd");
                                        }

                                        // /Save drug order
                                        ordersave = Context.getOrderService().saveOrder(dod);

                                        orderprocess.setDrugOrder(dod);

                                    }

                                    if (dopp.size() > 0) {
                                        DrugOrderProcessed dd = dopp.get(dopp.size() - 1);
                                        // for (DrugOrderProcessed dd :
                                        // dopp) {
                                        if (dd.getDrugRegimen().equals(reg) && !legacyData.get(5).isEmpty()
                                                && dd.getDoseRegimen().equals(legacyData.get(5))
                                                && dd.getTypeOfRegimen().equals(cahngeRegimenType)) {
                                            orderprocess.setRegimenChangeType("Continue");
                                            orderprocess.setDrugOrder(dd.getDrugOrder());

                                        } else {
                                            if (dd.getTypeOfRegimen().equals(cahngeRegimenType)) {
                                                orderprocess.setRegimenChangeType("Substitue");
                                            } else if (dd.getTypeOfRegimen().equals(cahngeRegimenType)) {
                                                orderprocess.setRegimenChangeType("Switch");
                                            }
                                            // Encounter Created
                                            EncounterType regEnrollEncType = MetadataUtils.existing(
                                                    EncounterType.class,
                                                    CommonMetadata._EncounterType.REGIMEN_ORDER);

                                            Encounter regEncounter = new Encounter();
                                            regEncounter.setEncounterType(regEnrollEncType);
                                            regEncounter.setPatient(patient);
                                            regEncounter.setLocation(Context.getLocationService()
                                                    .getLocationByUuid("8d6c993e-c2cc-11de-8d13-0010c6dffd0f"));

                                            regEncounter.setDateCreated(curDate);
                                            regEncounter.setEncounterDatetime(dateVisit);
                                            regEncounter.setVisit(v);

                                            regEncounter.setVoided(false);

                                            // Save encounter
                                            Encounter enregNew = Context.getEncounterService()
                                                    .saveEncounter(regEncounter);

                                            // Create order
                                            Order ordersave = new Order();

                                            // Create Drug order
                                            DrugOrder dod = new DrugOrder();

                                            dod.setOrderType(Context.getOrderService().getOrderType(2));
                                            dod.setConcept(Context.getConceptService()
                                                    .getConcept(Integer.parseInt(legacyData.get(4))));
                                            dod.setEncounter(enregNew);

                                            dod.setStartDate(dateVisit);
                                            dod.setDateCreated(curDate);
                                            dod.setPatient(patient);
                                            dod.setUnits("tab");
                                            if (legacyData.get(4).equals("163494")
                                                    || legacyData.get(4).equals("163495")
                                                    || legacyData.get(4).equals("163496")
                                                    || legacyData.get(4).equals("162959")
                                                    || legacyData.get(4).equals("163503")
                                                    || legacyData.get(4).equals("163505")
                                                    || legacyData.get(4).equals("163506")
                                                    || legacyData.get(4).equals(" 163507")
                                                    || legacyData.get(4).equals("163508")
                                                    || legacyData.get(4).equals("163510")) {

                                                dod.setFrequency("od");
                                            } else {
                                                dod.setFrequency("bd");
                                            }

                                            // /Save drug order
                                            ordersave = Context.getOrderService().saveOrder(dod);

                                            orderprocess.setDrugOrder(dod);

                                        }

                                    }

                                    kes.saveDrugOrderProcessed(orderprocess);

                                    Order oo = new Order();
                                    DrugOrderProcessed drugoo = new DrugOrderProcessed();

                                    for (DrugOrderProcessed ooo : dopp) {
                                        if (!legacyData.get(36).isEmpty()) {
                                            Date discontinuedDate = new Date();
                                            discontinuedDate = (Date) formatter.parse(legacyData.get(36));
                                            String dtechk = visitDateInExcel.format(discontinuedDate);
                                            try {
                                                Date curDat = new Date();
                                                List<Visit> visitdrug = Context.getVisitService()
                                                        .getVisitsByPatient(patient);

                                                for (Visit visdr : visitdrug) {
                                                    if (visdr.getStopDatetime() != null) {
                                                        if (drugoo.getDiscontinuedDate() == null) {
                                                            discontinuedDate = mysqlDateTimeFormatter
                                                                    .parse(dtechk + " " + curDat.getHours()
                                                                            + ":" + curDat.getMinutes() + ":"
                                                                            + curDat.getSeconds());

                                                            drugoo.setDiscontinuedDate(discontinuedDate);
                                                        }
                                                    }
                                                }

                                            } catch (ParseException e) {
                                                e.printStackTrace();
                                            }

                                        }
                                        if (!legacyData.get(35).isEmpty()) {
                                            List<Visit> visitdrug = Context.getVisitService()
                                                    .getVisitsByPatient(patient);
                                            Concept discontinuedReason = Context.getConceptService()
                                                    .getConcept(Integer.parseInt(legacyData.get(35)));

                                            for (Visit visdr : visitdrug) {
                                                if (visdr.getStopDatetime() != null) {
                                                    if (oo.getDiscontinuedReason() == null) {
                                                        if (!ooo.getDrugRegimen()
                                                                .equals(drugoo.getDrugRegimen())) {
                                                            drugoo.setDiscontinuedReason(discontinuedReason);
                                                        }
                                                    }
                                                }
                                            }
                                        }

                                        drugoo = ooo;

                                        kes.saveDrugOrderProcessed(drugoo);
                                    }
                                }

                                EncounterType labEnrollEncType = MetadataUtils.existing(EncounterType.class,
                                        CommonMetadata._EncounterType.LAB_ORDERS);
                                Encounter labEncounter = new Encounter();

                                labEncounter.setEncounterType(labEnrollEncType);
                                labEncounter.setPatient(patient);
                                labEncounter.setLocation(
                                        Context.getService(KenyaEmrService.class).getDefaultLocation());

                                labEncounter.setDateCreated(curDate);
                                labEncounter.setEncounterDatetime(dateVisit);

                                labEncounter.setForm(
                                        MetadataUtils.existing(Form.class, CommonMetadata._Form.LAB_ORDERS));
                                labEncounter.setVisit(v);

                                labEncounter.setVoided(false);

                                Encounter enlabNew = Context.getEncounterService().saveEncounter(labEncounter);

                                if (!legacyData.get(7).isEmpty()) {
                                    Concept labOrder = Dictionary.getConcept(Dictionary.CD4_COUNT);

                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.lABORATORY_ORDER), labOrder, "",
                                            null, null, enlabNew, null, v);

                                }
                                if (!legacyData.get(39).isEmpty()) {
                                    Concept labOrder = Context.getConceptService()
                                            .getConceptByUuid("122858AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");

                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.lABORATORY_ORDER), labOrder, "",
                                            null, null, enlabNew, null, v);

                                }
                                if (!legacyData.get(38).isEmpty()) {
                                    Concept labOrder = Context.getConceptService()
                                            .getConceptByUuid("654AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");

                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.lABORATORY_ORDER), labOrder, "",
                                            null, null, enlabNew, null, v);

                                }
                                if (!legacyData.get(8).isEmpty()) {

                                    Concept labviralOrder = Dictionary.getConcept(Dictionary.HIV_VIRAL_LOAD);

                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.lABORATORY_ORDER), labviralOrder,
                                            "", null, null, enlabNew, null, v);

                                }

                                if (!legacyData.get(37).isEmpty()) {

                                    Concept labhaemoOrder = Context.getConceptService()
                                            .getConceptByUuid("1019AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");

                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.lABORATORY_ORDER), labhaemoOrder,
                                            "", null, null, enlabNew, null, v);

                                }
                                if (!legacyData.get(40).isEmpty()) {

                                    Concept labcreatinineOrder = Context.getConceptService()
                                            .getConceptByUuid("790AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.lABORATORY_ORDER),
                                            labcreatinineOrder, "", null, null, enlabNew, null, v);

                                }
                                EncounterType labresultEnrollEncType = MetadataUtils.existing(
                                        EncounterType.class, CommonMetadata._EncounterType.LAB_RESULTS);
                                Encounter labresultEncounter = new Encounter();

                                labresultEncounter.setEncounterType(labresultEnrollEncType);
                                labresultEncounter.setPatient(patient);

                                labresultEncounter.setDateCreated(curDate);
                                labresultEncounter.setEncounterDatetime(dateVisit);
                                labresultEncounter.setVisit(v);

                                labresultEncounter.setVoided(false);
                                Encounter enlabresultNew = Context.getEncounterService()
                                        .saveEncounter(labresultEncounter);

                                if (!legacyData.get(7).isEmpty()) {

                                    String cd4Result = legacyData.get(7);
                                    Double cd4Count = Double.parseDouble(cd4Result);
                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.CD4_COUNT), null,
                                            legacyData.get(7), null, cd4Count, enlabresultNew, null, v);

                                }
                                if (!legacyData.get(37).isEmpty()) {

                                    String labResult = legacyData.get(37);

                                    handleOncePerPatientObs(patient,
                                            Context.getConceptService()
                                                    .getConceptByUuid("1019AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"),
                                            null, labResult, null, null, enlabresultNew, null, v);

                                }
                                if (!legacyData.get(38).isEmpty()) {

                                    String labResult = legacyData.get(38);
                                    Double lab = Double.parseDouble(labResult);

                                    handleOncePerPatientObs(patient,
                                            Context.getConceptService()
                                                    .getConceptByUuid("122858AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"),
                                            null, labResult, null, lab, enlabresultNew, null, v);

                                }
                                if (!legacyData.get(39).isEmpty()) {

                                    String labResult = legacyData.get(39);
                                    Double lab = Double.parseDouble(labResult);

                                    handleOncePerPatientObs(patient,
                                            Context.getConceptService()
                                                    .getConceptByUuid("654AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"),
                                            null, labResult, null, lab, enlabresultNew, null, v);

                                }
                                if (!legacyData.get(8).isEmpty()) {

                                    String labResult = legacyData.get(8);
                                    Double lab = Double.parseDouble(labResult);

                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.HIV_VIRAL_LOAD), null, labResult,
                                            null, lab, enlabresultNew, null, v);

                                }
                                if (!legacyData.get(40).isEmpty()) {

                                    String labResult = legacyData.get(40);
                                    Double lab = Double.parseDouble(labResult);

                                    handleOncePerPatientObs(patient,
                                            Context.getConceptService()
                                                    .getConceptByUuid("790AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"),
                                            null, labResult, null, lab, enlabresultNew, null, v);

                                }
                                EncounterType tbOIEnrollEncType = MetadataUtils.existing(EncounterType.class,
                                        CommonMetadata._EncounterType.CONSULTATION);
                                Encounter tbOIEncounter = new Encounter();

                                tbOIEncounter.setEncounterType(tbOIEnrollEncType);
                                tbOIEncounter.setPatient(patient);

                                tbOIEncounter.setDateCreated(curDate);
                                tbOIEncounter.setEncounterDatetime(dateVisit);
                                tbOIEncounter.setLocation(
                                        Context.getService(KenyaEmrService.class).getDefaultLocation());

                                tbOIEncounter.setForm(
                                        MetadataUtils.existing(Form.class, CommonMetadata._Form.TB_SCREENING));
                                tbOIEncounter.setVisit(v);
                                tbOIEncounter.setVoided(false);
                                Encounter entbOIresultNew = Context.getEncounterService()
                                        .saveEncounter(tbOIEncounter);
                                Obs o = null;
                                if (!legacyData.get(27).isEmpty()) {
                                    String text = "";
                                    Obs OIGroup = new Obs();
                                    OIGroup.setPerson(patient);
                                    OIGroup.setConcept(Dictionary.getConcept(Dictionary.OI_GROUP_TB_FORM));

                                    OIGroup.setObsDatetime(entbOIresultNew.getEncounterDatetime());
                                    // Added value coded as per default obs
                                    // object
                                    // format.
                                    OIGroup.setValueCoded(null);
                                    OIGroup.setValueText(text);
                                    OIGroup.setLocation(
                                            Context.getService(KenyaEmrService.class).getDefaultLocation());

                                    OIGroup.setEncounter(entbOIresultNew);

                                    if (!legacyData.get(27).isEmpty()) {
                                        o = Context.getObsService().saveObs(OIGroup,
                                                "KenyaEMR History Details");
                                    }

                                    if (!legacyData.get(27).isEmpty()) {
                                        String oivalue = legacyData.get(27);
                                        String[] valueList = oivalue.split("\\s*,\\s*");

                                        for (String oiname : valueList) {

                                            Concept oiConcept = Context.getConceptService().getConcept(oiname);

                                            handleOncePerPatientObs(patient,
                                                    Dictionary.getConcept(Dictionary.HIV_CARE_DIAGNOSIS),
                                                    oiConcept, "", null, null, entbOIresultNew, o, v);

                                        }

                                    }

                                }

                                if (!legacyData.get(10).isEmpty()) {

                                    Concept tbStatus = Context.getConceptService()
                                            .getConcept(Integer.parseInt(legacyData.get(10)));

                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.TB_PATIENT), tbStatus, "", null,
                                            null, entbOIresultNew, null, v);

                                }
                                if (!legacyData.get(11).isEmpty()) {

                                    Concept tbDiseaseClassification = Context.getConceptService()
                                            .getConcept(Integer.parseInt(legacyData.get(11)));
                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.SITE_OF_TUBERCULOSIS_DISEASE),
                                            tbDiseaseClassification, "", null, null, entbOIresultNew, null, v);
                                    if (!legacyData.get(12).isEmpty()) {
                                        if (!tbDiseaseClassification.equals("42")) {
                                            Concept tbsiteClassification = Context.getConceptService()
                                                    .getConcept(Integer.parseInt(legacyData.get(12)));
                                            handleOncePerPatientObs(patient,
                                                    Dictionary.getConcept(Dictionary.TB_SITE),
                                                    tbsiteClassification, "", null, null, entbOIresultNew, null,
                                                    v);
                                        }
                                    }
                                }

                                if (!legacyData.get(13).isEmpty()) {

                                    SimpleDateFormat sdf = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
                                    Date tbStartDate = new Date();
                                    try {
                                        tbStartDate = (Date) formatter.parse(legacyData.get(13));

                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                    }

                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(
                                                    Dictionary.TUBERCULOSIS_DRUG_TREATMENT_START_DATE),
                                            null, null, tbStartDate, null, entbOIresultNew, null, v);
                                }
                                if (!legacyData.get(14).isEmpty()) {

                                    Concept tbTownship = Context.getConceptService()
                                            .getConcept(Integer.parseInt(legacyData.get(14)));
                                    handleOncePerPatientObs(patient, Dictionary.getConcept(Dictionary.TOWNSHIP),
                                            tbTownship, "", null, null, entbOIresultNew, null, v);
                                }
                                if (!legacyData.get(15).isEmpty()) {

                                    String tbclinicName = "";
                                    tbclinicName = legacyData.get(15);

                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.TB_CLINIC_NAME), null,
                                            tbclinicName, null, null, entbOIresultNew, null, v);
                                }
                                if (!legacyData.get(16).isEmpty()) {

                                    String tbregistrationNumber = "";
                                    tbregistrationNumber = legacyData.get(16);

                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.TUBERCULOSIS_TREATMENT_NUMBER),
                                            null, tbregistrationNumber, null, null, entbOIresultNew, null, v);
                                }
                                if (!legacyData.get(17).isEmpty()) {
                                    Concept tbRegimen = Context.getConceptService()
                                            .getConcept(Integer.parseInt(legacyData.get(17)));
                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.TB_FORM_REGIMEN), tbRegimen, "",
                                            null, null, entbOIresultNew, null, v);

                                }
                                if (!legacyData.get(18).isEmpty()) {

                                    Concept tbOutcome = Context.getConceptService()
                                            .getConcept(Integer.parseInt(legacyData.get(18)));

                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.TUBERCULOSIS_TREATMENT_OUTCOME),
                                            tbOutcome, null, null, null, entbOIresultNew, null, v);
                                }

                                if (!legacyData.get(19).isEmpty()) {

                                    Date tbOutcomeDate = null;
                                    Date curDatenew = new Date();
                                    try {
                                        tbOutcomeDate = (Date) formatter.parse(legacyData.get(19));
                                        dateCheck = visitDateInExcel.format(tbOutcomeDate);
                                        tbOutcomeDate = mysqlDateTimeFormatter.parse(dateCheck + " "
                                                + curDatenew.getHours() + ":" + curDatenew.getMinutes() + ":"
                                                + curDatenew.getSeconds());
                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                    }

                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.TB_OUTCOME_DATE), null, null,
                                            tbOutcomeDate, null, entbOIresultNew, null, v);
                                }
                                int flag = 0;

                                if (!legacyData.get(20).isEmpty()) {

                                    EncounterType HivdiscontEnrollEncType = MetadataUtils.existing(
                                            EncounterType.class,
                                            HivMetadata._EncounterType.HIV_DISCONTINUATION);
                                    Encounter hivDiscontEncounter = new Encounter();

                                    hivDiscontEncounter.setEncounterType(HivdiscontEnrollEncType);
                                    hivDiscontEncounter.setPatient(patient);

                                    hivDiscontEncounter.setDateCreated(curDate);
                                    hivDiscontEncounter.setEncounterDatetime(dateVisit);
                                    hivDiscontEncounter.setLocation(
                                            Context.getService(KenyaEmrService.class).getDefaultLocation());

                                    hivDiscontEncounter.setForm(MetadataUtils.existing(Form.class,
                                            HivMetadata._Form.HIV_DISCONTINUATION));
                                    hivDiscontEncounter.setVisit(v);
                                    hivDiscontEncounter.setVoided(false);
                                    Encounter enhivDiscontresultNew = Context.getEncounterService()
                                            .saveEncounter(hivDiscontEncounter);

                                    Concept endOfFollowup = Context.getConceptService()
                                            .getConcept(Integer.parseInt(legacyData.get(20)));
                                    if (legacyData.get(20).equals("160034")) {
                                        handleOncePerPatientObs(patient,
                                                Dictionary.getConcept(
                                                        Dictionary.REASON_FOR_PROGRAM_DISCONTINUATION),
                                                endOfFollowup, null, null, null, enhivDiscontresultNew, null,
                                                v);
                                        handleOncePerPatientObs(patient,
                                                Dictionary.getConcept(Dictionary.DEATH_DATE), null, null,
                                                dateVisit, null, enhivDiscontresultNew, null, v);
                                        flag = 1;

                                    } else if (legacyData.get(20).equals("159492")) {
                                        handleOncePerPatientObs(patient,
                                                Dictionary.getConcept(
                                                        Dictionary.REASON_FOR_PROGRAM_DISCONTINUATION),
                                                endOfFollowup, null, null, null, enhivDiscontresultNew, null,
                                                v);
                                        if (!legacyData.get(22).isEmpty()) {
                                            String transferdto = legacyData.get(22);

                                            handleOncePerPatientObs(patient,
                                                    Dictionary.getConcept(Dictionary.TRANSFERRED_OUT_TO), null,
                                                    transferdto, null, null, enhivDiscontresultNew, null, v);

                                        }
                                        handleOncePerPatientObs(patient,
                                                Dictionary.getConcept(Dictionary.DATE_TRANSFERRED_OUT), null,
                                                null, dateVisit, null, enhivDiscontresultNew, null, v);

                                    } else {
                                        handleOncePerPatientObs(patient,
                                                Dictionary.getConcept(
                                                        Dictionary.REASON_FOR_PROGRAM_DISCONTINUATION),
                                                endOfFollowup, null, null, null, enhivDiscontresultNew, null,
                                                v);

                                    }

                                    if (!legacyData.get(21).isEmpty()) {
                                        Date programcmpleteDate = null;
                                        Date curDatenew = new Date();
                                        try {
                                            programcmpleteDate = (Date) formatter.parse(legacyData.get(21));
                                            dateCheck = visitDateInExcel.format(programcmpleteDate);
                                            programcmpleteDate = mysqlDateTimeFormatter.parse(dateCheck + " "
                                                    + curDatenew.getHours() + ":" + curDatenew.getMinutes()
                                                    + ":" + curDatenew.getSeconds());
                                            Collection<PatientProgram> hivprogram = Context
                                                    .getProgramWorkflowService().getPatientPrograms(patient);
                                            for (PatientProgram prog : hivprogram) {
                                                if (prog.getPatient().equals(patient)) {
                                                    if (prog.getProgram().getUuid()
                                                            .equals("dfdc6d40-2f2f-463d-ba90-cc97350441a8")
                                                            && prog.getDateCompleted() == null) {
                                                        prog.setDateCompleted(programcmpleteDate);
                                                        Context.getProgramWorkflowService()
                                                                .savePatientProgram(prog);
                                                    }

                                                }
                                            }
                                        } catch (ParseException e) {
                                            e.printStackTrace();
                                        }

                                    }

                                }

                                if (!legacyData.get(23).isEmpty() && !legacyData.get(24).isEmpty()) {
                                    PatientProgram activeArtProgram = null;
                                    Collection<PatientProgram> artProgram = Context.getProgramWorkflowService()
                                            .getPatientPrograms(patient);
                                    for (PatientProgram artProg : artProgram) {
                                        if (artProg.getProgram().getUuid()
                                                .equals("96ec813f-aaf0-45b2-add6-e661d5bf79d6")
                                                && artProg.getDateCompleted() == null) {
                                            activeArtProgram = artProg;
                                        }
                                    }

                                    EncounterType ArtdiscontEnrollEncType = MetadataUtils
                                            .existing(EncounterType.class, ArtMetadata._EncounterType.STOP_ART);
                                    Encounter artDiscontEncounter = new Encounter();

                                    artDiscontEncounter.setEncounterType(ArtdiscontEnrollEncType);
                                    artDiscontEncounter.setPatient(patient);

                                    artDiscontEncounter.setDateCreated(curDate);
                                    artDiscontEncounter.setEncounterDatetime(dateVisit);
                                    artDiscontEncounter.setLocation(
                                            Context.getService(KenyaEmrService.class).getDefaultLocation());

                                    artDiscontEncounter.setForm(
                                            MetadataUtils.existing(Form.class, ArtMetadata._Form.STOP_ART));
                                    artDiscontEncounter.setVisit(v);
                                    artDiscontEncounter.setVoided(false);
                                    Encounter enartDiscontresultNew = Context.getEncounterService()
                                            .saveEncounter(artDiscontEncounter);
                                    Date programcmpleteDate = null;
                                    Date curDatenew = new Date();
                                    try {
                                        programcmpleteDate = (Date) formatter.parse(legacyData.get(23));
                                        dateCheck = visitDateInExcel.format(programcmpleteDate);
                                        programcmpleteDate = mysqlDateTimeFormatter.parse(dateCheck + " "
                                                + curDatenew.getHours() + ":" + curDatenew.getMinutes() + ":"
                                                + curDatenew.getSeconds());
                                        if (activeArtProgram != null) {
                                            activeArtProgram.setDateCompleted(programcmpleteDate);
                                        }
                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                    }

                                    Context.getProgramWorkflowService().savePatientProgram(activeArtProgram);

                                    if (!legacyData.get(24).isEmpty()) {
                                        Concept endOfArt = Context.getConceptService()
                                                .getConcept(Integer.parseInt(legacyData.get(24)));

                                        handleOncePerPatientObs(patient,
                                                Context.getConceptService().getConceptByUuid(
                                                        "1252AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"),
                                                endOfArt, null, null, null, enartDiscontresultNew, null, v);

                                    }
                                }

                                EncounterType consultEnrollEncType = MetadataUtils.existing(EncounterType.class,
                                        CommonMetadata._EncounterType.CONSULTATION);
                                Encounter consultEncounter = new Encounter();

                                consultEncounter.setEncounterType(consultEnrollEncType);
                                consultEncounter.setPatient(patient);

                                consultEncounter.setDateCreated(curDate);
                                consultEncounter.setEncounterDatetime(dateVisit);
                                consultEncounter.setLocation(
                                        Context.getService(KenyaEmrService.class).getDefaultLocation());

                                consultEncounter.setForm(MetadataUtils.existing(Form.class,
                                        CommonMetadata._Form.CONSULTATION_ENCOUNTER));
                                consultEncounter.setVisit(v);
                                consultEncounter.setVoided(false);
                                Encounter enconsultresultNew = Context.getEncounterService()
                                        .saveEncounter(consultEncounter);
                                if (!legacyData.get(30).isEmpty()) {

                                    Concept sideffectsOfArt = Context.getConceptService()
                                            .getConcept(Integer.parseInt(legacyData.get(30)));

                                    handleOncePerPatientObs(patient,
                                            Context.getConceptService()
                                                    .getConceptByUuid("159935AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"),
                                            Dictionary.getConcept(Dictionary.YES), null, null, null,
                                            enconsultresultNew, null, v);
                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.ART_SIDE_EFFECTS_VALUES),
                                            sideffectsOfArt, null, null, null, enconsultresultNew, null, v);

                                }
                                if (!legacyData.get(31).isEmpty()) {

                                    String levelOfAdherence = legacyData.get(31);

                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.ART_ADHERENCE), null,
                                            levelOfAdherence, null, null, enconsultresultNew, null, v);

                                }
                                if (!legacyData.get(41).isEmpty()) {

                                    Concept temporaryreferal = Context.getConceptService()
                                            .getConcept(Integer.parseInt(legacyData.get(41)));

                                    handleOncePerPatientObs(patient,
                                            Context.getConceptService()
                                                    .getConceptByUuid("5e05d243-e039-4f04-9988-18d5a499329e"),
                                            Dictionary.getConcept(Dictionary.YES), null, null, null,
                                            enconsultresultNew, null, v);
                                    handleOncePerPatientObs(patient,
                                            Context.getConceptService()
                                                    .getConceptByUuid("c648f69b-7065-4255-9af2-6076348c87dc"),
                                            temporaryreferal, null, null, null, enconsultresultNew, null, v);

                                }
                                if (!legacyData.get(28).isEmpty()) {

                                    Concept tbOutcome = new Concept();
                                    String performance = legacyData.get(28);
                                    if (performance.equals("A")) {
                                        tbOutcome = Dictionary.getConcept(Dictionary.PERFSCALE_A);
                                    } else if (performance.equals("B")) {
                                        tbOutcome = Dictionary.getConcept(Dictionary.PERFSCALE_B);
                                    } else {
                                        tbOutcome = Dictionary.getConcept(Dictionary.PERFSCALE_C);
                                    }
                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.PERFORMANCE), tbOutcome, null,
                                            null, null, entbOIresultNew, null, v);
                                }

                                if (!legacyData.get(29).isEmpty()) {

                                    Concept tbOutcome = new Concept();
                                    String stage = legacyData.get(29);
                                    if (stage.equals("IV")) {
                                        tbOutcome = Dictionary.getConcept(Dictionary.WHO_STAGE_4_ADULT);
                                    } else if (stage.equals("III")) {
                                        tbOutcome = Dictionary.getConcept(Dictionary.WHO_STAGE_3_ADULT);
                                    } else if (stage.equals("II")) {
                                        tbOutcome = Dictionary.getConcept(Dictionary.WHO_STAGE_2_ADULT);
                                    } else {
                                        tbOutcome = Dictionary.getConcept(Dictionary.WHO_STAGE_1_ADULT);
                                    }
                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.CURRENT_WHO_STAGE), tbOutcome,
                                            null, null, null, entbOIresultNew, null, v);

                                }
                                EncounterType nextAppointEncType = MetadataUtils.existing(EncounterType.class,
                                        CommonMetadata._EncounterType.CONSULTATION);
                                Encounter nextAppointEncounter = new Encounter();

                                nextAppointEncounter.setEncounterType(nextAppointEncType);
                                nextAppointEncounter.setPatient(patient);

                                nextAppointEncounter.setDateCreated(curDate);
                                nextAppointEncounter.setEncounterDatetime(dateVisit);
                                nextAppointEncounter.setLocation(
                                        Context.getService(KenyaEmrService.class).getDefaultLocation());
                                nextAppointEncounter.setVisit(v);
                                nextAppointEncounter.setVoided(false);
                                Encounter ennextAppointresultNew = new Encounter();
                                if (!legacyData.get(32).isEmpty()) {
                                    ennextAppointresultNew = Context.getEncounterService()
                                            .saveEncounter(nextAppointEncounter);
                                }
                                if (!legacyData.get(32).isEmpty()) {
                                    SimpleDateFormat sdf = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
                                    Date nextAppointDate = new Date();
                                    try {
                                        nextAppointDate = (Date) formatter.parse(legacyData.get(32));

                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                    }

                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.RETURN_VISIT_DATE), null, null,
                                            nextAppointDate, null, ennextAppointresultNew, null, v);
                                }

                                // For OI or PROPHYLAXIS
                                if (!legacyData.get(33).isEmpty() || !legacyData.get(34).isEmpty()) {

                                    // For Duration of Medication
                                    if (!legacyData.get(6).isEmpty()) {

                                        EncounterType otherMedicationEnrollEncType = MetadataUtils.existing(
                                                EncounterType.class,
                                                CommonMetadata._EncounterType.CONSULTATION);
                                        Encounter otherMedEncounter = new Encounter();

                                        otherMedEncounter.setEncounterType(otherMedicationEnrollEncType);
                                        otherMedEncounter.setPatient(patient);

                                        otherMedEncounter.setDateCreated(curDate);
                                        otherMedEncounter.setEncounterDatetime(dateVisit);
                                        otherMedEncounter.setLocation(
                                                Context.getService(KenyaEmrService.class).getDefaultLocation());

                                        otherMedEncounter.setForm(MetadataUtils.existing(Form.class,
                                                CommonMetadata._Form.OTHER_MEDICATIONS));
                                        otherMedEncounter.setVisit(v);
                                        otherMedEncounter.setVoided(false);
                                        Encounter enotherresultNew = Context.getEncounterService()
                                                .saveEncounter(otherMedEncounter);

                                        String duration = legacyData.get(6);
                                        Double durationDouble = Double.parseDouble(duration);
                                        int durationInteger = Integer.parseInt(legacyData.get(6));

                                        /*
                                         * PROPHYLAXIS start
                                         */

                                        if (!legacyData.get(33).isEmpty()) {

                                            String value = legacyData.get(33);

                                            String[] valueList = value.split("\\s*,\\s*");

                                            for (String prop : valueList) {
                                                // Group for each Drug
                                                String text = "";
                                                Obs prophylGroup = new Obs();
                                                prophylGroup.setPerson(patient);
                                                prophylGroup.setConcept(
                                                        Context.getConceptService().getConceptByUuid(
                                                                "163022AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
                                                prophylGroup.setObsDatetime(
                                                        enotherresultNew.getEncounterDatetime());
                                                prophylGroup.setValueCoded(null);
                                                prophylGroup.setValueText(text);
                                                prophylGroup
                                                        .setLocation(Context.getService(KenyaEmrService.class)
                                                                .getDefaultLocation());

                                                prophylGroup.setEncounter(enotherresultNew);
                                                prophylGroup.setComment("1");
                                                Obs prophyl = Context.getObsService().saveObs(prophylGroup,
                                                        "KenyaEMR History Details");

                                                Concept oivalue = Context.getConceptService().getConcept(prop);

                                                // CPT for CTX
                                                if (oivalue.getUuid().toString()
                                                        .equals("105281AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")) {
                                                    handleOncePerPatientObs(patient,
                                                            Dictionary.getConcept(Dictionary.CPT_VALUE),
                                                            Context.getConceptService().getConcept(1065), "",
                                                            null, null, enotherresultNew, null, v);
                                                }

                                                // IPT for Isoniazid
                                                if (oivalue.getUuid().toString()
                                                        .equals("78280AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")) {
                                                    handleOncePerPatientObs(patient,
                                                            Dictionary.getConcept(Dictionary.IPT_VALUE),
                                                            Context.getConceptService().getConcept(1065), "",
                                                            null, null, enotherresultNew, null, v);
                                                }

                                                handleOncePerPatientObs(patient,
                                                        Dictionary.getConcept(Dictionary.PROPHYLAXIS), oivalue,
                                                        "", null, null, enotherresultNew, prophyl, v);

                                                handleOncePerPatientObs(patient,
                                                        Dictionary.getConcept(Dictionary.MEDICATION_DURATION),
                                                        null, "", null, durationDouble, enotherresultNew,
                                                        prophyl, v);

                                                // Capture Drug in Drug obs
                                                // processed
                                                DrugObsProcessed dop = new DrugObsProcessed();
                                                dop.setObs(prophyl);
                                                dop.setCreatedDate(curDate);
                                                dop.setPatient(patient);
                                                dop.setProcessedDate(dateVisit);
                                                dop.setQuantityPostProcess(durationInteger);

                                                KenyaEmrService kes = (KenyaEmrService) Context
                                                        .getService(KenyaEmrService.class);
                                                kes.saveDrugObsProcessed(dop);
                                            }

                                        }

                                        /*
                                         * PROPHYLAXIS End
                                         */

                                        if (!legacyData.get(34).isEmpty()) {

                                            String value = legacyData.get(34);

                                            String[] valueList = value.split("\\s*,\\s*");

                                            for (String oil : valueList) {
                                                // Group for each Drug
                                                String text = "";
                                                Obs oitreatmentGroup = new Obs();
                                                oitreatmentGroup.setPerson(patient);
                                                oitreatmentGroup.setConcept(
                                                        Context.getConceptService().getConceptByUuid(
                                                                "163021AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));

                                                oitreatmentGroup.setObsDatetime(
                                                        enotherresultNew.getEncounterDatetime());

                                                oitreatmentGroup.setValueCoded(null);
                                                oitreatmentGroup.setValueText(text);
                                                oitreatmentGroup
                                                        .setLocation(Context.getService(KenyaEmrService.class)
                                                                .getDefaultLocation());

                                                oitreatmentGroup.setEncounter(enotherresultNew);
                                                oitreatmentGroup.setComment("1");
                                                Obs oitreat = Context.getObsService().saveObs(oitreatmentGroup,
                                                        "KenyaEMR History Details");

                                                Concept oivalue = Context.getConceptService().getConcept(oil);

                                                handleOncePerPatientObs(patient,
                                                        Dictionary.getConcept(Dictionary.OI_TREATMENT_DRUG),
                                                        oivalue, "", null, null, enotherresultNew, oitreat, v);

                                                handleOncePerPatientObs(patient,
                                                        Dictionary.getConcept(Dictionary.MEDICATION_DURATION),
                                                        null, "", null, durationDouble, enotherresultNew,
                                                        oitreat, v);

                                                // Capture Drug in Drug obs
                                                // processed
                                                DrugObsProcessed dop = new DrugObsProcessed();
                                                dop.setObs(oitreat);
                                                dop.setCreatedDate(curDate);
                                                dop.setPatient(patient);
                                                dop.setProcessedDate(dateVisit);
                                                dop.setQuantityPostProcess(durationInteger);

                                                KenyaEmrService kes = (KenyaEmrService) Context
                                                        .getService(KenyaEmrService.class);
                                                kes.saveDrugObsProcessed(dop);
                                            }
                                        }
                                    }
                                }

                                EncounterType recordEncType = MetadataUtils.existing(EncounterType.class,
                                        CommonMetadata._EncounterType.CONSULTATION);
                                Encounter recordEncounter = new Encounter();

                                recordEncounter.setEncounterType(recordEncType);
                                recordEncounter.setPatient(patient);

                                recordEncounter.setDateCreated(curDate);
                                recordEncounter.setEncounterDatetime(dateVisit);
                                recordEncounter.setLocation(
                                        Context.getService(KenyaEmrService.class).getDefaultLocation());

                                recordEncounter.setForm(
                                        MetadataUtils.existing(Form.class, CommonMetadata._Form.TRIAGE));
                                recordEncounter.setVisit(v);
                                recordEncounter.setVoided(false);
                                Encounter enrecordvitalresultNew = Context.getEncounterService()
                                        .saveEncounter(recordEncounter);
                                if (!legacyData.get(25).isEmpty()) {

                                    String labResult = legacyData.get(25);
                                    Double lab = Double.parseDouble(labResult);

                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.WEIGHT_KG), null, null, null, lab,
                                            enrecordvitalresultNew, null, v);

                                }

                                if (!legacyData.get(26).isEmpty()) {

                                    String labResult = legacyData.get(26);
                                    Double lab = Double.parseDouble(labResult);

                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.HEIGHT_CM), null, null, null, lab,
                                            enrecordvitalresultNew, null, v);

                                }

                                EncounterType hivEnrollEncType = MetadataUtils.existing(EncounterType.class,
                                        HivMetadata._EncounterType.HIV_ENROLLMENT);
                                EncounterType registrationEncType = MetadataUtils.existing(EncounterType.class,
                                        CommonMetadata._EncounterType.REGISTRATION);
                                Encounter obstericEncounter = new Encounter();

                                obstericEncounter.setEncounterType(registrationEncType);
                                obstericEncounter.setPatient(patient);

                                obstericEncounter.setDateCreated(curDate);
                                obstericEncounter.setEncounterDatetime(dateVisit);
                                obstericEncounter.setLocation(
                                        Context.getService(KenyaEmrService.class).getDefaultLocation());

                                obstericEncounter.setForm(
                                        MetadataUtils.existing(Form.class, Metadata.Form.OBSTETRIC_HISTORY));
                                obstericEncounter.setVisit(v);
                                obstericEncounter.setVoided(false);
                                Encounter enobstericrecordresultNew = Context.getEncounterService()
                                        .saveEncounter(obstericEncounter);
                                if (!legacyData.get(42).isEmpty()) {

                                    Concept pregstatus = Context.getConceptService()
                                            .getConcept(Integer.parseInt(legacyData.get(42)));
                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.PREGNANCY_STATUS), pregstatus, "",
                                            null, null, enobstericrecordresultNew, null, v);

                                }
                                if (!legacyData.get(43).isEmpty()) {

                                    Concept familyplanningstatus = Dictionary.getConcept(Dictionary.YES);

                                    handleOncePerPatientObs(patient,
                                            Context.getConceptService()
                                                    .getConceptByUuid("5271AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"),
                                            familyplanningstatus, "", null, null, enobstericrecordresultNew,
                                            null, v);

                                }
                                if (!legacyData.get(43).isEmpty()) {

                                    Concept familyplanningvalue = Context.getConceptService()
                                            .getConcept(Integer.parseInt(legacyData.get(43)));

                                    handleOncePerPatientObs(patient,
                                            Dictionary.getConcept(Dictionary.METHOD_OF_FAMILY_PLANNING),
                                            familyplanningvalue, "", null, null, enobstericrecordresultNew,
                                            null, v);

                                }

                                DateFormat visitDatesInExcel = new SimpleDateFormat("dd-MMM-yyyy");
                                String dateChecks = visitDatesInExcel.format(dateVisit);
                                if (legacyData.get(3) != null) {
                                    Date Datenew = new Date();
                                    try {
                                        dateVisit = mysqlDateTimeFormatter
                                                .parse(dateChecks + " " + Datenew.getHours() + ":"
                                                        + Datenew.getMinutes() + ":" + Datenew.getSeconds());

                                    } catch (ParseException e) {
                                        dateVisit = Datenew;

                                        e.printStackTrace();
                                    }
                                }

                                v.setStopDatetime(dateVisit);

                                Context.getVisitService().saveVisit(v);

                                if (flag == 1) {
                                    person.setDead(true);
                                    person.setDeathDate(dateVisit);
                                    person.setCauseOfDeath(Dictionary.getConcept(Dictionary.UNKNOWN));
                                    Context.getPersonService().savePerson(person);
                                }
                            }

                        }

                        catch (IndexOutOfBoundsException e) {
                            e.printStackTrace();
                        }
                    } else {
                        break;
                    }
                }
            } catch (IndexOutOfBoundsException e) {
                break;
            }

            rowCountVisit++;
        }
    }

    inputStream.close();
    // workbook.close();
    return new SuccessResult("Saved Patient Data");
}