Example usage for java.util ArrayList clear

List of usage examples for java.util ArrayList clear

Introduction

In this page you can find the example usage for java.util ArrayList clear.

Prototype

public void clear() 

Source Link

Document

Removes all of the elements from this list.

Usage

From source file:com.krawler.spring.hrms.rec.job.hrmsRecJobController.java

public ModelAndView getAllUserDetails(HttpServletRequest request, HttpServletResponse response)
        throws JSONException {
    JSONObject jobj = new JSONObject();
    int count;//from w w w.j av  a  2s .c om
    HashMap<String, Object> requestParams = new HashMap<String, Object>();
    KwlReturnObject result = null;
    try {

        ArrayList params = new ArrayList();
        ArrayList filter_names = new ArrayList();
        ArrayList order_by = new ArrayList();
        ArrayList order_type = new ArrayList();
        filter_names.add("ua.user.company.companyID");
        filter_names.add("ua.user.deleteflag");
        params.add(sessionHandlerImplObj.getCompanyid(request));
        params.add(0);

        // @@ useraccount

        //            if(!StringUtil.isNullOrEmpty(request.getParameter("combo"))){
        //
        //                order_by.add("u.firstName");
        //                order_type.add("asc");
        //            }else{
        //
        //                order_by.add("u.employeeid");
        //                order_type.add("asc");
        //            }
        requestParams.put("filter_names", filter_names);
        requestParams.put("filter_values", params);
        requestParams.put("order_by", order_by);
        requestParams.put("order_type", order_type);
        requestParams.put("ss", request.getParameter("ss"));
        requestParams.put("searchcol", new String[] { "u.firstName", "u.lastName" });
        //            requestParams.put("start", Integer.valueOf(request.getParameter("start")));
        //            requestParams.put("limit", Integer.valueOf(request.getParameter("limit")));
        result = hrmsCommonDAOObj.getEmpprofileuser(requestParams);
        List list = result.getEntityList();
        count = result.getRecordTotalCount();
        for (int ctr = 0; ctr < count; ctr++) {
            Object[] row = (Object[]) list.get(ctr);
            JSONObject obj = new JSONObject();
            Empprofile e = null;
            Useraccount ua = (Useraccount) row[1];
            User u = ua.getUser();
            if (row[0] != null) {
                e = (Empprofile) row[0];
                if (!StringUtil.isNullOrEmpty(e.getStatus())) {
                    obj.put("status", e.getStatus());
                } else {
                    obj.put("status", "Pending");
                }
            } else {
                obj.put("status", "Incomplete");
            }
            obj.put("department", (ua.getDepartment() == null ? "" : ua.getDepartment().getId()));
            obj.put("departmentname", (ua.getDepartment() == null ? "" : ua.getDepartment().getValue()));
            obj.put("role", (ua.getRole() == null ? "" : ua.getRole().getID()));
            String name = "";
            if (ua.getRole() != null && ua.getRole().getCompany() != null) {
                name = ua.getRole().getName();
            } else {
                name = messageSource.getMessage("hrms.common.role." + ua.getRole().getID(), null,
                        ua.getRole().getName(), RequestContextUtils.getLocale(request));
            }
            obj.put("rolename", (ua.getRole() == null ? "" : name));
            obj.put("userid", u.getUserID());
            obj.put("username", u.getUserLogin().getUserName());
            obj.put("fname", u.getFirstName());
            obj.put("lname", u.getLastName());
            obj.put("fullname", u.getFirstName() + " " + (u.getLastName() == null ? "" : u.getLastName()));
            obj.put("image", u.getImage());
            obj.put("emailid", u.getEmailID());
            obj.put("lastlogin",
                    (u.getUserLogin().getLastActivityDate() == null ? ""
                            : sessionHandlerImplObj.getDateFormatter(request)
                                    .format(u.getUserLogin().getLastActivityDate())));
            obj.put("aboutuser", u.getAboutUser());
            obj.put("address", u.getAddress());
            obj.put("contactno", u.getContactNumber());
            obj.put("designation", ua.getDesignationid() == null ? "" : ua.getDesignationid().getValue());
            obj.put("designationid", ua.getDesignationid() == null ? "" : ua.getDesignationid().getId());
            obj.put("salary", ua.getSalary());
            obj.put("accno", ua.getAccno());
            obj.put("templateid", ua.getTemplateid() != null ? ua.getTemplateid() : "");
            requestParams.clear();
            requestParams.put("companyid", sessionHandlerImplObj.getCompanyid(request));
            requestParams.put("empid", ua.getEmployeeid());
            //                result = profileHandlerDAOObj.getEmpidFormatEdit(requestParams);
            obj.put("employeeid", ua.getEmployeeid() == null ? ""
                    : profileHandlerDAOObj.getEmpidFormatEdit(requestParams).getEntityList().get(0));

            //                List lst1 = HibernateUtil.executeQuery(session, "from  Assignmanager where assignemp.userID=? and managerstatus=1", u.getUserID());
            //                Iterator itr1 = lst1.iterator();
            requestParams.clear();
            //                requestParams.put("userid", u.getUserID());
            //                requestParams.put("managerstatus", 1);
            filter_names.clear();
            params.clear();
            filter_names.add("assignemp.userID");
            params.add(u.getUserID());

            filter_names.add("managerstatus");
            params.add(1);

            requestParams.put("filter_names", filter_names);
            requestParams.put("filter_values", params);

            result = hrmsCommonDAOObj.getAssignmanager(requestParams);
            List lst1 = result.getEntityList();
            for (int cnt = 0; cnt < lst1.size(); cnt++) {
                Assignmanager asm = (Assignmanager) lst1.get(cnt);
                if (asm.getAssignman() != null) {
                    obj.append("managerid", asm.getAssignman().getUserID());
                    obj.append("manager",
                            asm.getAssignman().getFirstName() + " " + asm.getAssignman().getLastName());
                }
            }
            if (lst1.size() == 0) {
                obj.put("manager", " ");
                obj.put("managerid", " ");
            }
            jobj.append("data", obj);
            //                jArr.put(obj);
            //                lst1 = HibernateUtil.executeQuery(session, "from  Assignreviewer where employee.userID=? and reviewerstatus=1", u.getUserID());
            //                itr1 = lst1.iterator();
            requestParams.clear();
            requestParams.put("userid", u.getUserID());
            requestParams.put("reviewerstatus", 1);
            result = hrmsCommonDAOObj.getAssignreviewer(requestParams);
            lst1 = result.getEntityList();
            for (int cnt1 = 0; cnt1 < lst1.size(); cnt1++) {
                Assignreviewer rev = (Assignreviewer) lst1.get(cnt1);
                if (rev.getReviewer() != null) {
                    obj.append("reviewerid", rev.getReviewer().getUserID());
                    obj.append("reviewer",
                            rev.getReviewer().getFirstName() + " " + rev.getReviewer().getLastName());
                }
            }
            if (lst1.size() == 0) {
                obj.put("reviewer", " ");
                obj.put("reviewerid", " ");
            }
            jobj.append("data", obj);
        }
        jobj.put("count", count);

    } catch (Exception e) {
        System.out.print(e);

    } finally {
        if (!jobj.has("data")) {
            jobj.put("count", 0);
            jobj.put("data", "");
        }
        JSONObject jobj1 = new JSONObject();
        jobj1.put("valid", true);
        jobj1.put("data", jobj);
        return new ModelAndView("jsonView", "model", jobj1.toString());
    }
}

From source file:com.rickendirk.rsgwijzigingen.ZoekService.java

private ArrayList<String> checkerKlas() {
    ArrayList<String> tempList = new ArrayList<>();
    //String halen uit SP
    String klasTextS = PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
            .getString("pref_klas", "");
    //Checken of klas niet leeg is
    if (klasTextS.equals("")) {
        tempList.add("geenKlas");
        return tempList;
    }/*from  w  w  w .  ja  v  a 2 s .  co m*/
    //Eerste teken klas mag geen letter zijn
    if (Character.isLetter(klasTextS.charAt(0))) {
        tempList.add("EersteTekenLetter");
        return tempList;
    }
    //String opsplitsen in 2 delen, om naar hoofdletters te converteren
    char charcijfer = klasTextS.charAt(0);
    String klascijfer = String.valueOf(charcijfer);
    char charafdeling = klasTextS.charAt(1);
    String klasafdelingBig = String.valueOf(charafdeling).toUpperCase();
    //Onderstaand voor hoofdlettercorrectie
    String klasCorrect; //KlasCorrect is klas na hoofdlettercorrectie
    switch (klasTextS.length()) {
    case 2:
        klasCorrect = klascijfer + klasafdelingBig;
        break;
    case 3:
        char klasabc = klasTextS.charAt(2);
        String klasabcSmall = String.valueOf(klasabc).toLowerCase();
        klasCorrect = klascijfer + klasafdelingBig + klasabcSmall;
        break;
    case 4:
        char klasafdeling2 = klasTextS.charAt(2);
        String klasafdeling2Big = String.valueOf(klasafdeling2).toUpperCase();
        klasabc = klasTextS.charAt(3);
        klasabcSmall = String.valueOf(klasabc).toLowerCase();

        klasCorrect = klascijfer + klasafdelingBig + klasafdeling2Big + klasabcSmall;
        break;
    default:
        tempList.add("klasMeerDan4Tekens");
        return tempList;
    }

    //Try en catch in het geval dat de internetverbinding mist
    try {
        String url = "http://www.rsgtrompmeesters.nl/roosters/roosterwijzigingen/Lijsterbesstraat/subst_001.htm";
        Document doc = Jsoup.connect(url).get();
        Elements tables = doc.select("table");
        if (tables.size() < 2) {
            //Geen geschikte tabel aanwezig
            tempList.add("geenTabel");
            return tempList;
        }
        Element table = tables.get(1);
        Elements rows = table.select("tr");
        //Loop genereren, voor elke row kijken of het de goede tekst bevat
        //Beginnen bij 4e, bovenstaande is niet belangrijk
        for (int i = 2; i < rows.size(); i++) {
            Element row = rows.get(i);
            Elements cols = row.select("td");

            if (cols.get(0).text().contains(klasCorrect)) {
                String vakOud = Jsoup.parse(cols.get(2).toString()).text();
                String docentOud = Jsoup.parse(cols.get(3).toString()).text();
                String vakNieuw = Jsoup.parse(cols.get(4).toString()).text();
                String docentNieuw = Jsoup.parse(cols.get(5).toString()).text();
                //If in geval van uitval, else ingeval van wijziging
                if (Jsoup.parse(cols.get(6).toString()).text().contains("--")) {
                    //2 opties: wordt verplaatst of valt uit
                    if (Jsoup.parse(cols.get(8).toString()).text().contains("Uitval")) {
                        String wijziging = Jsoup.parse(cols.get(1).toString()).text() + "e uur "
                                + Jsoup.parse(cols.get(2).toString()).text() + " valt uit";
                        tempList.add(wijziging);
                    } else {
                        //Uur wordt verplaatst
                        String wijziging = Jsoup.parse(cols.get(1).toString()).text() + "e uur "
                                + "wordt verplaatst naar " + Jsoup.parse(cols.get(8).toString()).text();
                        tempList.add(wijziging);
                    }
                } else if (vakOud.equals(vakNieuw) && docentOud.equals(docentNieuw)) {
                    String wijziging = Jsoup.parse(cols.get(1).toString()).text() + "e uur " + vakOud
                            + " wordt verplaatst naar " + Jsoup.parse(cols.get(6).toString()).text();
                    tempList.add(wijziging);
                } else {
                    String wijzigingKaal;
                    if (vakOud.equals(vakNieuw) && !docentOud.equals(docentNieuw)) {
                        // Opvang door andere docent: dit staat alleen bij klas omdat
                        // dit amper gebeurt bij clusters
                        wijzigingKaal = Jsoup.parse(cols.get(1).toString()).text() + "e uur " + docentOud
                                + " wordt opgevangen door " + docentNieuw;
                    } else { //Geen opvang door andere docent, lokaalwijziging oid
                        wijzigingKaal =
                                // Voegt alle kolommen samen tot 1 string
                                // .text() zorgt voor leesbare text
                                // Spaties voor leesbaarheid
                                Jsoup.parse(cols.get(1).toString()).text() + "e uur "
                                        + Jsoup.parse(cols.get(2).toString()).text() + " "
                                        + Jsoup.parse(cols.get(3).toString()).text() + " wordt "
                                        + Jsoup.parse(cols.get(4).toString()).text() + " "
                                        + Jsoup.parse(cols.get(5).toString()).text() + " in "
                                        + Jsoup.parse(cols.get(6).toString()).text();
                    }
                    //ipv en naar bevatten een "/" ivm uren (ma 12-04 / 4)
                    String ipv = "";
                    if (Jsoup.parse(cols.get(7).toString()).text().contains("/")) {
                        ipv = "ipv " + Jsoup.parse(cols.get(7).toString()).text();
                    }
                    String naar = "";
                    if (Jsoup.parse(cols.get(8).toString()).text().contains("/")) {
                        naar = "naar " + Jsoup.parse(cols.get(8).toString()).text() + " ";
                    }
                    String vervangingsTekst = "";
                    //&nbsp; staat in lege cell, encoding enz, zie volgende link:
                    // http://stackoverflow.com/questions/26837034/how-to-tell-if-a-html-table-has-an-empty-cell-nbsp-using-jsoup
                    //Soms veregeten ze de opmerkingen, dan krijg je size = 9 en error
                    if (cols.size() > 9) {
                        if (!Jsoup.parse(cols.get(9).toString()).text().equals("\u00a0")) {
                            vervangingsTekst = "(" + Jsoup.parse(cols.get(9).toString()).text() + ")";
                        }
                    }
                    String wijziging = wijzigingKaal + " " + ipv + " " + naar + " " + vervangingsTekst;
                    tempList.add(wijziging);

                }

            }
            //Geen wijzigingen pas bij laatste rij
            if (i == rows.size() - 1) {
                //Checken of tempList leeg is, zo ja 1 ding toevoegen
                if (tempList.isEmpty()) {
                    tempList.add("Er zijn geen wijzigingen");
                }
                //Dag waarvoor wijzigingen zijn ophalen
                Element dag = doc.select("body > div > div:nth-child(2) > p > b > span").first();
                //Compatibiliteit met andere opmaak, om NPE te voorkomen
                if (dag == null) {
                    dag = doc.select("body > center:nth-child(2) > div").first();
                }
                String dagStr = dag.text().toLowerCase();
                // Woorden staan verkeerd om: omwisselen
                int indexVanSpatie = dagStr.indexOf(" ");
                String datum = dagStr.substring(0, indexVanSpatie);
                String rest = dagStr.substring(indexVanSpatie + 1);
                String dagGoed = rest + " " + datum;
                tempList.add(dagGoed);

                //Stand ophalen: staat in 1e tabel van HTML
                Element tableDate = doc.select("table").get(0);
                String dateFullText = tableDate.getElementsContainingOwnText("Stand:").text();
                //Deel achter "Stand:" pakken
                String FullTextSplit[] = dateFullText.split("Stand:");
                tempList.add(FullTextSplit[1]);
                return tempList;
            }
        }
    } catch (java.io.IOException e) {
        //Error toevoegen aan tempList, dat wordt weergegeven in messagebox
        tempList.clear();
        tempList.add("verbindFout");
        return tempList;
    }
    //Zover hoort de method NOOIT te komen
    tempList.add("andereFout");
    return tempList;
}

From source file:base.BasePlayer.FileRead.java

static void readGFF(File infile, String outfile, SAMSequenceDictionary dict) {
    BufferedReader reader = null;
    GZIPInputStream gzip = null;//from   w  ww  .  jav a2  s. c om
    FileReader freader = null;
    String line = "", chrom = "-1";
    HashMap<String, String> lineHash;
    HashMap<String, Gene> genes = new HashMap<String, Gene>();
    HashMap<String, Transcript> transcripts = new HashMap<String, Transcript>();
    Gene addgene;
    Transcript addtranscript;

    try {

        if (infile.getName().endsWith(".gz")) {
            gzip = new GZIPInputStream(new FileInputStream(infile));
            reader = new BufferedReader(new InputStreamReader(gzip));
        } else {
            freader = new FileReader(infile);
            reader = new BufferedReader(freader);
        }
        //   line = reader.readLine();
        while ((line = reader.readLine()) != null) {

            if (line.startsWith("#")) {
                continue;
            }

            lineHash = makeHash(line.split("\t"));
            if (lineHash.get("type").startsWith("region")) {

                if (line.contains("unlocalized")) {
                    chrom = "unlocalized";
                } else if (lineHash.get("chromosome") != null) {
                    chrom = lineHash.get("chromosome").replace("chr", "");
                } else if (lineHash.get("name") != null) {
                    chrom = lineHash.get("name").replace("chr", "");
                }

                continue;
            }

            if (!lineHash.containsKey("parent")) {
                /*if(!lineHash.get("type").contains("gene")) {
                        
                   continue;
                }*/

                Gene gene = new Gene(chrom, lineHash);

                genes.put(getInfoValue(lineHash, "id"), gene);

                continue;
            }
            if (genes.containsKey(lineHash.get("parent"))) {

                addgene = genes.get(lineHash.get("parent"));
                transcripts.put(getInfoValue(lineHash, "id"), new Transcript(lineHash, addgene));
                if (lineHash.get("type").equals("exon")) {
                    addtranscript = transcripts.get(getInfoValue(lineHash, "id"));
                    addtranscript.addExon(lineHash, addtranscript);
                }
                if (addgene.getDescription().equals("-")) {
                    if (lineHash.containsKey("product")) {
                        addgene.setDescription(lineHash.get("product"));
                    }
                }
                continue;
            }
            if (transcripts.containsKey(lineHash.get("parent"))) {

                addtranscript = transcripts.get(lineHash.get("parent"));
                addtranscript.addExon(lineHash, addtranscript);
                continue;
            }

        }

    } catch (Exception e) {
        System.out.println(line);
        e.printStackTrace();
        System.exit(0);
    }
    try {

        Transcript transcript;
        Gene gene;
        StringBuffer exStarts, exEnds, exPhases;
        Iterator<Map.Entry<String, Gene>> it = genes.entrySet().iterator();
        ArrayList<String[]> geneArray = new ArrayList<String[]>();

        while (it.hasNext()) {
            Map.Entry<String, Gene> pair = (Map.Entry<String, Gene>) it.next();
            gene = pair.getValue();

            for (int i = 0; i < gene.getTranscripts().size(); i++) {
                transcript = gene.getTranscripts().get(i);
                exStarts = new StringBuffer("");
                exEnds = new StringBuffer("");
                exPhases = new StringBuffer("");
                for (int e = 0; e < transcript.exonArray.size(); e++) {
                    exStarts.append(transcript.exonArray.get(e).getStart() + ",");
                    exEnds.append(transcript.exonArray.get(e).getEnd() + ",");
                    exPhases.append(transcript.exonArray.get(e).getStartPhase() + ",");
                }

                String[] row = { gene.getChrom(), "" + transcript.getStart(), "" + transcript.getEnd(),
                        gene.getName(), "" + transcript.exonArray.size(),
                        MethodLibrary.getStrand(gene.getStrand()), gene.getID(), transcript.getENST(),
                        transcript.getUniprot(), "-", transcript.getBiotype(), "" + transcript.getCodingStart(),
                        "" + transcript.getCodingEnd(), exStarts.toString(), exEnds.toString(),
                        exPhases.toString(), transcript.getDescription() };
                geneArray.add(row);
            }

            it.remove();
        }

        gffSorter gffsorter = new gffSorter();
        Collections.sort(geneArray, gffsorter);

        if (outfile != null) {
            MethodLibrary.blockCompressAndIndex(geneArray, outfile, false, dict);
        }

        geneArray.clear();
        if (freader != null) {
            freader.close();
        }
        reader.close();

        if (gzip != null) {
            gzip.close();
        }

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

}

From source file:com.sentaroh.android.SMBExplorer.SMBExplorerMain.java

private void startFileioTask(FileListAdapter fla, final int op_cd, final ArrayList<FileIoLinkParm> alp,
        String item_name, final NotifyEvent p_ntfy, final String lmp) {
    setAllFilelistItemUnChecked(fla);//from   w  w w  .j  av  a 2 s.c o m

    @SuppressWarnings("unused")
    String dst = "";
    String dt = null;
    @SuppressWarnings("unused")
    String nitem = item_name;
    mGp.fileIoWifiLockRequired = false;
    switch (op_cd) {
    case FILEIO_PARM_REMOTE_CREATE:
        mGp.fileIoWifiLockRequired = true;
    case FILEIO_PARM_LOCAL_CREATE:
        dt = "Create";
        dst = item_name + " was created.";
        nitem = "";
        break;
    case FILEIO_PARM_REMOTE_RENAME:
        mGp.fileIoWifiLockRequired = true;
    case FILEIO_PARM_LOCAL_RENAME:
        dt = "Rename";
        dst = item_name + " was renamed.";
        nitem = "";
        break;
    case FILEIO_PARM_REMOTE_DELETE:
        mGp.fileIoWifiLockRequired = true;
    case FILEIO_PARM_LOCAL_DELETE:
        dt = "Delete";
        dst = "Following dirs/files were deleted.";
        break;
    case FILEIO_PARM_COPY_REMOTE_TO_LOCAL:
    case FILEIO_PARM_COPY_REMOTE_TO_REMOTE:
    case FILEIO_PARM_COPY_LOCAL_TO_REMOTE:
        mGp.fileIoWifiLockRequired = true;
    case FILEIO_PARM_COPY_LOCAL_TO_LOCAL:
        dt = "Copy";
        dst = "Following dirs/files were copied.";
        break;
    case FILEIO_PARM_MOVE_REMOTE_TO_REMOTE:
    case FILEIO_PARM_MOVE_LOCAL_TO_REMOTE:
    case FILEIO_PARM_MOVE_REMOTE_TO_LOCAL:
        mGp.fileIoWifiLockRequired = true;
    case FILEIO_PARM_MOVE_LOCAL_TO_LOCAL:
        dt = "Move";
        dst = "Following dirs/files were moved.";
        break;
    case FILEIO_PARM_DOWLOAD_REMOTE_FILE:
        mGp.fileIoWifiLockRequired = true;
        dt = "Download";
        dst = "";
    default:
        break;
    }

    mTcFileIoTask = new ThreadCtrl();
    mTcFileIoTask.setEnabled();

    if (currentTabName.equals(SMBEXPLORER_TAB_LOCAL)) {
        mGp.progressMsgView = mLocalProgressMsg;
        mGp.progressCancelBtn = mLocalProgressCancel;
        showLocalProgressView();
    } else if (currentTabName.equals(SMBEXPLORER_TAB_REMOTE)) {
        mGp.progressMsgView = mRemoteProgressMsg;
        mGp.progressCancelBtn = mRemoteProgressCancel;
        showRemoteProgressView();
    }
    mGp.progressMsgView.setText(dt);

    mGp.progressCancelBtn.setEnabled(true);
    mGp.progressCancelBtn.setText("Cancel");
    mProgressOnClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            mTcFileIoTask.setDisabled();
            mGp.progressCancelBtn.setEnabled(false);
            mGp.progressCancelBtn.setText("Cancelling");
        }
    };
    mGp.progressCancelBtn.setOnClickListener(mProgressOnClickListener);

    NotifyEvent ne = new NotifyEvent(mContext);
    ne.setListener(new NotifyEventListener() {
        @Override
        public void positiveResponse(Context c, Object[] o) {
            hideRemoteProgressView();
            hideLocalProgressView();
            if (!mTcFileIoTask.isThreadResultSuccess()) {
                if (p_ntfy != null)
                    p_ntfy.notifyToListener(false, null);
                if (mTcFileIoTask.isThreadResultCancelled()) {
                    //                  commonDlg.showCommonDialog(false,"W","File I/O task was cancelled.","",null);
                    showDialogMsg("W", "File I/O task was cancelled.", "");
                    sendLogMsg("W", "File I/O task was cancelled.");
                    //                  refreshFilelistView();
                } else {
                    //                  commonDlg.showCommonDialog(false,"E","File I/O task was failed."+"\n"+
                    //                              mTcFileIoTask.getThreadMessage(),"",null);
                    showDialogMsg("E", "File I/O task was failed." + "\n" + mTcFileIoTask.getThreadMessage(),
                            "");
                    sendLogMsg("E", "File I/O task was failed.");
                    //                  refreshFilelistView();
                }
            } else {
                if (p_ntfy != null)
                    p_ntfy.notifyToListener(true, null);
                else
                    refreshFilelistView();
            }
            alp.clear();
            if (isTaskDataExisted())
                saveTaskData();
        }

        @Override
        public void negativeResponse(Context c, Object[] o) {
            hideRemoteProgressView();
            hideLocalProgressView();
        }
    });

    Thread th = new Thread(new FileIo(mGp, op_cd, alp, mTcFileIoTask, ne, this, lmp));
    mTcFileIoTask.initThreadCtrl();
    th.setPriority(Thread.MIN_PRIORITY);
    th.start();
}

From source file:edu.harvard.i2b2.adminTool.dataModel.PatientMappingFactory.java

@SuppressWarnings("unchecked")
public String generateTimelineData(String result, ArrayList<TimelineRow> rows, boolean writeFile,
        boolean displayAll, boolean displayDemographics, final MainComposite explorer) {

    try {/*from   w w  w  . j a  v a  2s .  c o m*/
        PDOResponseMessageModel pdoresponsefactory = new PDOResponseMessageModel();
        StatusType statusType = pdoresponsefactory.getStatusFromResponseXML(result);
        if (!statusType.getType().equalsIgnoreCase("DONE")) {
            return "error";
        }

        JAXBUtil jaxbUtil = PatientMappingJAXBUtil.getJAXBUtil();

        JAXBElement jaxbElement = jaxbUtil.unMashallFromString(result);
        ResponseMessageType messageType = (ResponseMessageType) jaxbElement.getValue();
        BodyType bodyType = messageType.getMessageBody();
        PatientDataResponseType responseType = (PatientDataResponseType) new JAXBUnWrapHelper()
                .getObjectByClass(bodyType.getAny(), PatientDataResponseType.class);
        PageType pageType = responseType.getPage();
        if (pageType != null) {
            final int returnLastIndex = pageType.getPagingByPatients().getPatientsReturned().getLastIndex()
                    .intValue();
            final int returnFirstIndex = pageType.getPagingByPatients().getPatientsReturned().getFirstIndex()
                    .intValue();
            final int requestLastIndex = pageType.getPagingByPatients().getPatientsRequested().getLastIndex()
                    .intValue();
            if (returnLastIndex < requestLastIndex) {
                // System.out.println("Can't return all the requested "+
                // requestIndex+" patients, only "+returnIndex+" patients returned");
                explorer.getDisplay().syncExec(new Runnable() {
                    public void run() {
                        // MessageBox mBox = new MessageBox(explorer
                        // .getShell(), SWT.ICON_INFORMATION
                        // | SWT.OK );
                        // mBox.setText("Please Note ...");
                        // mBox.setMessage("Only "+(returnLastIndex-returnFirstIndex+1)+" patients returned");
                        // mBox.open();
                        if (explorer.runMode() >= 0) {
                            explorer.setIncrementNumber(returnLastIndex - returnFirstIndex + 1);
                        } else if (explorer.runMode() == -1) {
                            explorer.setDecreaseNumber(returnLastIndex - returnFirstIndex + 1);
                        }
                    }
                });
                explorer.returnedNumber(returnLastIndex - returnFirstIndex + 1);
            } else {
                explorer.returnedNumber(-1);
            }
        } else {
            explorer.getDisplay().syncExec(new Runnable() {
                public void run() {
                    // MessageBox mBox = new MessageBox(explorer
                    // .getShell(), SWT.ICON_INFORMATION
                    // | SWT.OK );
                    // mBox.setText("Please Note ...");
                    // mBox.setMessage("Only "+(returnLastIndex-returnFirstIndex+1)+" patients returned");
                    // mBox.open();
                    if (explorer.runMode() >= 0) {
                        explorer.setIncrementNumber(-1);
                    } else if (explorer.runMode() == -1) {
                        explorer.setDecreaseNumber(-1);
                    }
                }
            });
        }

        StringBuilder resultFile = new StringBuilder();
        resultFile.append(GetTimelineHeader());

        PatientSet patientDimensionSet = pdoresponsefactory.getPatientSetFromResponseXML(result);
        if (patientDimensionSet != null) {
            log.debug("Total patient: " + patientDimensionSet.getPatient().size());
            // for(int i=0;
            // i<patientDimensionSet.getPatientDimension().size();i++) {
            // PatientDimensionType patientType =
            // patientDimensionSet.getPatientDimension().get(i);
            // System.out.println("PatientNum: " +
            // patientType.getPatientNum());
            // }
        } else {
            return "error";
        }

        // / testing the visit set
        // PatientDataType.VisitDimensionSet visitSet =
        // pdoresponsefactory.getVisitSetFromResponseXML(result);
        // System.out.println("Total visits: "+visitSet.getVisitDimension().
        // size());

        List<ObservationSet> factSets = pdoresponsefactory.getFactSetsFromResponseXML(result);

        log.debug("\nGenerate lld:");

        String curPNum = "-1";
        for (int i = 0; i < patientDimensionSet.getPatient().size(); i++) {
            PatientType patientType = patientDimensionSet.getPatient().get(i);
            String pnum = patientType.getPatientId().getValue();
            // Integer pnum = new Integer(snum);
            // log.debug("PatientNum: " + snum);
            //if(curPNum.equals("-1")) {
            curPNum = new String(pnum);
            //}

            if (displayDemographics) {
                resultFile.append(getTimelinePatientString(pnum.toString(), patientType));
            } else {
                resultFile.append(getTimelinePatientString(pnum.toString()));
            }

            String path = null;
            TimelineRow currentRow = null;
            ObservationSet observationFactSet = null;

            for (int j = 0; j < rows.size(); j++) {
                TimelineRow row = rows.get(j);
                int total = 0;
                StringBuilder resultString = new StringBuilder();

                XMLGregorianCalendar curStartDate = null;
                //int currentInstanceNum = 0;
                //String currentConcept = "";
                ArrayList<ObservationType> facts = new ArrayList<ObservationType>();
                ObservationType curFact = null;
                boolean recorded = false;
                String sStart_date = null;
                String sEnd_date = null;

                // loop thru all the pdo sets for this row here
                for (int s = 0; s < row.pdoItems.size(); s++) {
                    PDOItem pset = row.pdoItems.get(s);
                    observationFactSet = null;

                    for (int m = 0; m < factSets.size(); m++) {
                        ObservationSet tmpFactSet = factSets.get(m);
                        if (tmpFactSet.getPanelName().equalsIgnoreCase(pset.panelName())) {
                            observationFactSet = tmpFactSet;
                            path = observationFactSet.getPanelName();
                            currentRow = row;
                            break;
                        }
                    }

                    if (observationFactSet == null) {
                        continue;
                    }

                    for (int k = 0; k < observationFactSet.getObservation().size(); k++) {
                        ObservationType obsFactType = observationFactSet.getObservation().get(k);
                        //if(curFact == null) {
                        //curFact = obsFactType;
                        //}

                        //facts.add(obsFactType);

                        if (pnum.equals(obsFactType.getPatientId().getValue())) {
                            /*
                             * if ((curStartDate != null) &&
                             * (obsFactType.getStartDate().compare(
                             * curStartDate) == DatatypeConstants.EQUAL)) {
                             * continue; }
                             */
                            if (curFact == null) {
                                curFact = obsFactType;
                            }

                            if (curStartDate == null) {
                                curStartDate = obsFactType.getStartDate();
                            }

                            sStart_date = obsFactType.getStartDate().getMonth() + "-"
                                    + obsFactType.getStartDate().getDay() + "-"
                                    + obsFactType.getStartDate().getYear() + " 12:00";

                            if (obsFactType.getEndDate() == null) {
                                sEnd_date = sStart_date;
                            } else {
                                sEnd_date = obsFactType.getEndDate().getMonth() + "-"
                                        + obsFactType.getEndDate().getDay() + "-"
                                        + obsFactType.getEndDate().getYear() + " 12:00";
                            }

                            double nval = -1;
                            if (obsFactType.getNvalNum().getValue() != null) {
                                nval = obsFactType.getNvalNum().getValue().doubleValue();
                            }
                            PDOValueModel valdp = null;

                            if (false) {//pset.hasValueDisplayProperty) {
                                for (int n = 0; n < pset.valDisplayProperties.size(); n++) {
                                    PDOValueModel tmpvaldp = pset.valDisplayProperties.get(n);
                                    // if (tmpvaldp.inRange(nval)) {
                                    valdp = tmpvaldp;
                                    // break;
                                    // }
                                }

                                String sValue = getSValue(obsFactType.getConceptCd().getName(), obsFactType,
                                        true);
                                if ((curStartDate != null) && (obsFactType.getStartDate()
                                        .compare(curStartDate) == DatatypeConstants.EQUAL)) {
                                    resultString.append(getTimelineDateStringHeight(sStart_date, sEnd_date,
                                            "slateblue", valdp.height, sValue));
                                } else {
                                    resultString.append(getTimelineDateStringHeight(sStart_date, sEnd_date,
                                            valdp.color, valdp.height, sValue));
                                }
                            } else {
                                //////////////////////
                                String sValue = "";
                                if (sameInstance(curFact, obsFactType)) {
                                    //if(recorded) {
                                    facts.add(obsFactType);
                                    //recorded = false;
                                    continue;
                                    //}
                                    /*sValue = getSValueSame(obsFactType.getConceptCd().getName(),
                                          obsFactType, false);
                                    if ((curStartDate != null)
                                          && (obsFactType.getStartDate()
                                                .compare(curStartDate) == DatatypeConstants.EQUAL)) {
                                       resultString
                                             .append(getTimelineDateStringHeightSame(
                                     sStart_date, sEnd_date,
                                     "slateblue",
                                     pset.height, sValue));
                                    } else {
                                       resultString
                                             .append(getTimelineDateStringHeightSame(
                                     sStart_date, sEnd_date,
                                     pset.color,
                                     pset.height, sValue));
                                    }*/
                                }
                                //else {
                                sValue = getSValue(curFact.getConceptCd().getName(), facts, false);
                                //}

                                sStart_date = curFact.getStartDate().getMonth() + "-"
                                        + curFact.getStartDate().getDay() + "-"
                                        + curFact.getStartDate().getYear() + " 12:00";

                                if (curFact.getEndDate() == null) {
                                    sEnd_date = sStart_date;
                                } else {
                                    sEnd_date = curFact.getEndDate().getMonth() + "-"
                                            + curFact.getEndDate().getDay() + "-"
                                            + curFact.getEndDate().getYear() + " 12:00";
                                }

                                //if ((curStartDate != null)
                                //      && (obsFactType.getStartDate()
                                //      .compare(curStartDate) == DatatypeConstants.EQUAL)) {
                                //resultString
                                //.append(getTimelineDateStringHeight(
                                //sStart_date, sEnd_date,
                                //"slateblue",
                                //pset.height, sValue));
                                //} else {
                                resultString.append(getTimelineDateStringHeight(sStart_date, sEnd_date,
                                        pset.color, pset.height, sValue));
                                //}
                            }

                            total++;
                            recorded = false;
                            facts.clear();
                            facts.add(obsFactType);
                            curStartDate = obsFactType.getStartDate();
                            curFact = obsFactType;
                        } else {
                            if (recorded || facts.size() == 0) {
                                curPNum = new String(pnum);
                                continue;
                            }
                            sStart_date = curStartDate.getMonth() + "-" + curStartDate.getDay() + "-"
                                    + curStartDate.getYear() + " 12:00";

                            //if (obsFactType.getEndDate() == null) {
                            //sEnd_date = sStart_date;
                            //} else {
                            sEnd_date = curStartDate.getMonth() + "-" + curStartDate.getDay() + "-"
                                    + curStartDate.getYear() + " 12:00";
                            //}
                            //curFact = null;
                            String sValue = getSValue(curFact.getConceptCd().getName(), facts, false);
                            //if ((curStartDate != null)
                            //&& (obsFactType.getStartDate()
                            //.compare(curStartDate) == DatatypeConstants.EQUAL)) {
                            //resultString
                            //.append(getTimelineDateStringHeight(
                            //sStart_date, sEnd_date,
                            //"slateblue",
                            //pset.height, sValue));
                            //} else {
                            resultString.append(getTimelineDateStringHeight(sStart_date, sEnd_date, pset.color,
                                    pset.height, sValue));
                            //}
                            total++;
                            recorded = true;
                            facts.clear();
                            curStartDate = null;//obsFactType.getStartDate();
                            curFact = null;//obsFactType;
                            curPNum = new String(pnum);
                        }
                    }
                }

                if (total > 0) {
                    // log.debug("-- "+path+" has "+total+" events");
                    resultFile.append(getTimelineConceptString(row.displayName, total));

                    // log.debug(resultString.toString());
                    resultFile.append(resultString);
                    total = 0;
                    ////rdtr
                } else {
                    // display all
                    if (displayAll) {
                        // log.debug("-- "+path+" has "+total+" events");
                        resultFile.append(getTimelineConceptString(row.displayName, 1));

                        // log.debug(getTimelineEmptyDateString());
                        resultFile.append(getTimelineEmptyDateString());
                    }
                }

                if (recorded || facts.size() == 0) {
                    curPNum = new String(pnum);
                    continue;
                }
                sStart_date = curStartDate.getMonth() + "-" + curStartDate.getDay() + "-"
                        + curStartDate.getYear() + " 12:00";

                //if (obsFactType.getEndDate() == null) {
                //sEnd_date = sStart_date;
                //} else {
                sEnd_date = curStartDate.getMonth() + "-" + curStartDate.getDay() + "-" + curStartDate.getYear()
                        + " 12:00";
                //}
                //curFact = null;
                String sValue = getSValue(curFact.getConceptCd().getName(), facts, false);

                resultString
                        .append(getTimelineDateStringHeight(sStart_date, sEnd_date, "navyblue", "p10", sValue));

                total++;
                recorded = true;
                facts.clear();
                //curStartDate = obsFactType.getStartDate();
                //curFact = obsFactType;
                curPNum = new String(pnum);
                if (total > 0) {
                    // log.debug("-- "+path+" has "+total+" events");
                    resultFile.append(getTimelineConceptString(row.displayName, total));

                    // log.debug(resultString.toString());
                    resultFile.append(resultString);
                }
            }
        }

        resultFile.append(GetTimelineFooter());

        if (writeFile) {
            String i2b2File = System.getProperty("user.dir") + "/temp/" + "i2b2xml.lld";
            File oDelete = new File(i2b2File);
            if (oDelete != null)
                oDelete.delete();
            RandomAccessFile f = new RandomAccessFile(i2b2File, "rw");
            append(f, resultFile.toString());
            f.close();
        }

        // log.debug("\nThe lld file: \n"+resultFile.toString());
        return resultFile.toString();
    } catch (org.apache.axis2.AxisFault e) {
        e.printStackTrace();
        log.error(e.getMessage());
        return null;
    } catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
        return "error";
    }
}

From source file:oscar.dms.actions.DmsInboxManageAction.java

public ActionForward prepareForContentPage(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {/*  w w  w .ja v  a  2  s . c o  m*/
    HttpSession session = request.getSession();
    try {
        if (session.getAttribute("userrole") == null)
            response.sendRedirect("../logout.jsp");
    } catch (Exception e) {
        logger.error("Error", e);
    }

    // can't use userrole from session, because it changes if provider A search for provider B's documents

    // oscar.oscarMDS.data.MDSResultsData mDSData = new oscar.oscarMDS.data.MDSResultsData();
    CommonLabResultData comLab = new CommonLabResultData();
    // String providerNo = request.getParameter("providerNo");
    String providerNo = (String) session.getAttribute("user");
    String searchProviderNo = request.getParameter("searchProviderNo");
    String ackStatus = request.getParameter("status");
    String demographicNo = request.getParameter("demographicNo"); // used when searching for labs by patient instead of provider
    String scannedDocStatus = request.getParameter("scannedDocument");
    Integer page = 0;
    try {
        page = Integer.parseInt(request.getParameter("page"));
        if (page > 0) {
            page--;
        }
    } catch (NumberFormatException nfe) {
        page = 0;
    }
    Integer pageSize = 20;
    try {
        String tmp = request.getParameter("pageSize");
        pageSize = Integer.parseInt(tmp);
    } catch (NumberFormatException nfe) {
        pageSize = 20;
    }
    scannedDocStatus = "I";

    String startDateStr = request.getParameter("startDate");
    String endDateStr = request.getParameter("endDate");

    String view = request.getParameter("view");
    if (view == null || "".equals(view)) {
        view = "all";
    }

    boolean mixLabsAndDocs = "normal".equals(view) || "all".equals(view);

    Date startDate = null;
    Date endDate = null;

    try {
        if (startDateStr != null && startDateStr.length() > 0) {
            startDateStr = startDateStr.trim();
            startDate = UtilDateUtilities.StringToDate(startDateStr);
        }
        if (endDateStr != null && endDateStr.length() > 0) {
            endDateStr = endDateStr.trim();
            endDate = UtilDateUtilities.StringToDate(endDateStr);
        }
    } catch (Exception e) {
        startDate = null;
        endDate = null;
    }

    Boolean isAbnormal = null;
    if ("abnormal".equals(view))
        isAbnormal = new Boolean(true);
    if ("normal".equals(view))
        isAbnormal = new Boolean(false);

    if (ackStatus == null) {
        ackStatus = "N";
    } // default to new labs only
    if (providerNo == null) {
        providerNo = "";
    }
    if (searchProviderNo == null) {
        searchProviderNo = providerNo;
    }
    String roleName = "";
    List<SecUserRole> roles = secUserRoleDao.getUserRoles(searchProviderNo);
    for (SecUserRole r : roles) {
        if (r != null) {
            if (roleName.length() == 0) {
                roleName = r.getRoleName();

            } else {
                roleName += "," + r.getRoleName();
            }
        }
    }
    roleName += "," + searchProviderNo;
    // mDSData.populateMDSResultsData2(searchProviderNo, demographicNo, request.getParameter("fname"), request.getParameter("lname"), request.getParameter("hnum"), ackStatus);
    // HashMap<String,String> docQueue=comLab.getDocumentQueueLinks();
    List<QueueDocumentLink> qd = queueDocumentLinkDAO.getQueueDocLinks();
    HashMap<String, String> docQueue = new HashMap();
    for (QueueDocumentLink qdl : qd) {
        Integer i = qdl.getDocId();
        Integer n = qdl.getQueueId();
        docQueue.put(i.toString(), n.toString());
    }

    InboxResultsDao inboxResultsDao = (InboxResultsDao) SpringUtils.getBean("inboxResultsDao");
    String patientFirstName = request.getParameter("fname");
    String patientLastName = request.getParameter("lname");
    String patientHealthNumber = request.getParameter("hnum");

    ArrayList<LabResultData> labdocs = new ArrayList<LabResultData>();

    if (!"labs".equals(view) && !"abnormal".equals(view)) {
        labdocs = inboxResultsDao.populateDocumentResultsData(searchProviderNo, demographicNo, patientFirstName,
                patientLastName, patientHealthNumber, ackStatus, true, page, pageSize, mixLabsAndDocs,
                isAbnormal);
    }
    if (!"documents".equals(view)) {
        labdocs.addAll(comLab.populateLabResultsData(searchProviderNo, demographicNo, patientFirstName,
                patientLastName, patientHealthNumber, ackStatus, scannedDocStatus, true, page, pageSize,
                mixLabsAndDocs, isAbnormal));
    }

    labdocs = (ArrayList<LabResultData>) filterLabDocsForSuperSite(labdocs, providerNo);

    ArrayList<LabResultData> validlabdocs = new ArrayList<LabResultData>();

    DocumentResultsDao documentResultsDao = (DocumentResultsDao) SpringUtils.getBean("documentResultsDao");
    // check privilege for documents only
    for (LabResultData data : labdocs) {
        if (data.isDocument()) {
            String docid = data.getSegmentID();

            String queueid = docQueue.get(docid);
            if (queueid != null) {
                queueid = queueid.trim();

                int queueIdInt = Integer.parseInt(queueid);

                // if doc sent to default queue and no valid provider, do NOT include it
                if (queueIdInt == Queue.DEFAULT_QUEUE_ID && !documentResultsDao.isSentToValidProvider(docid)
                        && isSegmentIDUnique(validlabdocs, data)) {
                    // validlabdocs.add(data);
                }
                // if doc sent to default queue && valid provider, check if it's sent to this provider, if yes include it
                else if (queueIdInt == Queue.DEFAULT_QUEUE_ID && documentResultsDao.isSentToValidProvider(docid)
                        && documentResultsDao.isSentToProvider(docid, searchProviderNo)
                        && isSegmentIDUnique(validlabdocs, data)) {
                    validlabdocs.add(data);
                }
                // if doc setn to non-default queue and valid provider, check if provider is in the queue or equal to the provider
                else if (queueIdInt != Queue.DEFAULT_QUEUE_ID
                        && documentResultsDao.isSentToValidProvider(docid)) {
                    Vector vec = OscarRoleObjectPrivilege.getPrivilegeProp("_queue." + queueid);
                    if (OscarRoleObjectPrivilege.checkPrivilege(roleName, (Properties) vec.get(0),
                            (Vector) vec.get(1))
                            || documentResultsDao.isSentToProvider(docid, searchProviderNo)) {
                        // labs is in provider's queue,do nothing
                        if (isSegmentIDUnique(validlabdocs, data)) {
                            validlabdocs.add(data);
                        }
                    }
                }
                // if doc sent to non default queue and no valid provider, check if provider is in the non default queue
                else if (!queueid.equals(Queue.DEFAULT_QUEUE_ID)
                        && !documentResultsDao.isSentToValidProvider(docid)) {
                    Vector vec = OscarRoleObjectPrivilege.getPrivilegeProp("_queue." + queueid);
                    if (OscarRoleObjectPrivilege.checkPrivilege(roleName, (Properties) vec.get(0),
                            (Vector) vec.get(1))) {
                        // labs is in provider's queue,do nothing
                        if (isSegmentIDUnique(validlabdocs, data)) {
                            validlabdocs.add(data);
                        }

                    }
                }
            }
        } else {// add lab
            if (isSegmentIDUnique(validlabdocs, data)) {
                validlabdocs.add(data);
            }
        }
    }

    // Find the oldest lab returned in labdocs, use that as the limit date for the HRM query
    Date oldestLab = null;
    Date newestLab = null;
    if (request.getParameter("newestDate") != null) {
        try {
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            newestLab = formatter.parse(request.getParameter("newestDate"));
        } catch (Exception e) {
            logger.error("Couldn't parse date + " + request.getParameter("newestDate"), e);
        }
    }

    for (LabResultData result : labdocs) {
        if (result != null && result.getDateObj() != null) {
            if (oldestLab == null || oldestLab.compareTo(result.getDateObj()) > 0)
                oldestLab = result.getDateObj();
            if (request.getParameter("newestDate") != null
                    && (newestLab == null || newestLab.compareTo(result.getDateObj()) < 0))
                newestLab = result.getDateObj();
        }
    }

    HRMResultsData hrmResult = new HRMResultsData();

    Collection<LabResultData> hrmDocuments = hrmResult.populateHRMdocumentsResultsData(searchProviderNo,
            ackStatus, newestLab, oldestLab);
    if (oldestLab == null) {
        for (LabResultData hrmDocument : hrmDocuments) {
            if (oldestLab == null
                    || (hrmDocument.getDateObj() != null && oldestLab.compareTo(hrmDocument.getDateObj()) > 0))
                oldestLab = hrmDocument.getDateObj();
        }
    }

    //labdocs is already filtered for super site access.. not just filter hrmDocuments
    hrmDocuments = filterLabDocsForSuperSite(hrmDocuments, providerNo);

    labdocs.addAll(hrmDocuments);
    Collections.sort(labdocs);

    HashMap<String, LabResultData> labMap = new HashMap<String, LabResultData>();
    LinkedHashMap<String, ArrayList<String>> accessionMap = new LinkedHashMap<String, ArrayList<String>>();

    int accessionNumCount = 0;
    for (LabResultData result : labdocs) {
        if (startDate != null && startDate.after(result.getDateObj())) {
            continue;
        }

        if (endDate != null && endDate.before(result.getDateObj())) {
            continue;
        }

        String segmentId = result.getSegmentID();
        if (result.isDocument())
            segmentId += "d";
        else if (result.isHRM())
            segmentId += "h";

        labMap.put(segmentId, result);
        ArrayList<String> labNums = new ArrayList<String>();

        if (result.accessionNumber == null || result.accessionNumber.equals("")) {
            labNums.add(segmentId);
            accessionNumCount++;
            accessionMap.put("noAccessionNum" + accessionNumCount + result.labType, labNums);
        } else if (!accessionMap.containsKey(result.accessionNumber + result.labType)) {
            labNums.add(segmentId);
            accessionMap.put(result.accessionNumber + result.labType, labNums);

            // Different MDS Labs may have the same accession Number if they are seperated
            // by two years. So accession numbers are limited to matching only if their
            // labs are within one year of eachother
        } else {
            labNums = accessionMap.get(result.accessionNumber + result.labType);
            boolean matchFlag = false;
            for (int j = 0; j < labNums.size(); j++) {
                LabResultData matchingResult = labMap.get(labNums.get(j));

                Date dateA = result.getDateObj();
                Date dateB = matchingResult.getDateObj();
                int monthsBetween = 0;
                if (dateA == null || dateB == null) {
                    monthsBetween = 5;
                } else if (dateA.before(dateB)) {
                    monthsBetween = UtilDateUtilities.getNumMonths(dateA, dateB);
                } else {
                    monthsBetween = UtilDateUtilities.getNumMonths(dateB, dateA);
                }

                if (monthsBetween < 4) {
                    matchFlag = true;
                    break;
                }
            }
            if (!matchFlag) {
                labNums.add(segmentId);
                accessionMap.put(result.accessionNumber + result.labType, labNums);
            }
        }
    }

    labdocs.clear();

    for (ArrayList<String> labNums : accessionMap.values()) {
        // must sort through in reverse to keep the labs in the correct order
        for (int j = labNums.size() - 1; j >= 0; j--) {
            labdocs.add(labMap.get(labNums.get(j)));
        }
    }
    logger.debug("labdocs.size()=" + labdocs.size());

    /* find all data for the index.jsp page */
    Hashtable patientDocs = new Hashtable();
    Hashtable patientIdNames = new Hashtable();
    String patientIdNamesStr = "";
    Hashtable docStatus = new Hashtable();
    Hashtable docType = new Hashtable();
    Hashtable<String, List<String>> ab_NormalDoc = new Hashtable();

    for (int i = 0; i < labdocs.size(); i++) {
        LabResultData data = labdocs.get(i);

        List<String> segIDs = new ArrayList<String>();
        String labPatientId = data.getLabPatientId();
        if (labPatientId == null || labPatientId.equals("-1"))
            labPatientId = "-1";

        if (data.isAbnormal()) {
            List<String> abns = ab_NormalDoc.get("abnormal");
            if (abns == null) {
                abns = new ArrayList<String>();
                abns.add(data.getSegmentID());
            } else {
                abns.add(data.getSegmentID());
            }
            ab_NormalDoc.put("abnormal", abns);
        } else {
            List<String> ns = ab_NormalDoc.get("normal");
            if (ns == null) {
                ns = new ArrayList<String>();
                ns.add(data.getSegmentID());
            } else {
                ns.add(data.getSegmentID());
            }
            ab_NormalDoc.put("normal", ns);
        }
        if (patientDocs.containsKey(labPatientId)) {

            segIDs = (List) patientDocs.get(labPatientId);
            segIDs.add(data.getSegmentID());
            patientDocs.put(labPatientId, segIDs);
        } else {
            segIDs.add(data.getSegmentID());
            patientDocs.put(labPatientId, segIDs);
            patientIdNames.put(labPatientId, data.patientName);
            patientIdNamesStr += ";" + labPatientId + "=" + data.patientName;
        }
        docStatus.put(data.getSegmentID(), data.getAcknowledgedStatus());
        docType.put(data.getSegmentID(), data.labType);
    }

    Integer totalDocs = 0;
    Integer totalHL7 = 0;
    Hashtable<String, List<String>> typeDocLab = new Hashtable();
    Enumeration keys = docType.keys();
    while (keys.hasMoreElements()) {
        String keyDocLabId = ((String) keys.nextElement());
        String valType = (String) docType.get(keyDocLabId);

        if (valType.equalsIgnoreCase("DOC")) {
            if (typeDocLab.containsKey("DOC")) {
                List<String> docids = typeDocLab.get("DOC");
                docids.add(keyDocLabId);// add doc id to list
                typeDocLab.put("DOC", docids);
            } else {
                List<String> docids = new ArrayList<String>();
                docids.add(keyDocLabId);
                typeDocLab.put("DOC", docids);
            }
            totalDocs++;
        } else if (valType.equalsIgnoreCase("HL7")) {
            if (typeDocLab.containsKey("HL7")) {
                List<String> hl7ids = typeDocLab.get("HL7");
                hl7ids.add(keyDocLabId);
                typeDocLab.put("HL7", hl7ids);
            } else {
                List<String> hl7ids = new ArrayList<String>();
                hl7ids.add(keyDocLabId);
                typeDocLab.put("HL7", hl7ids);
            }
            totalHL7++;
        }
    }

    Hashtable patientNumDoc = new Hashtable();
    Enumeration patientIds = patientDocs.keys();
    String patientIdStr = "";
    Integer totalNumDocs = 0;
    while (patientIds.hasMoreElements()) {
        String key = (String) patientIds.nextElement();
        patientIdStr += key;
        patientIdStr += ",";
        List<String> val = (List<String>) patientDocs.get(key);
        Integer numDoc = val.size();
        patientNumDoc.put(key, numDoc);
        totalNumDocs += numDoc;
    }

    List<String> normals = ab_NormalDoc.get("normal");
    List<String> abnormals = ab_NormalDoc.get("abnormal");

    logger.debug("labdocs.size()=" + labdocs.size());

    // set attributes
    request.setAttribute("pageNum", page);
    request.setAttribute("docType", docType);
    request.setAttribute("patientDocs", patientDocs);
    request.setAttribute("providerNo", providerNo);
    request.setAttribute("searchProviderNo", searchProviderNo);
    request.setAttribute("patientIdNames", patientIdNames);
    request.setAttribute("docStatus", docStatus);
    request.setAttribute("patientIdStr", patientIdStr);
    request.setAttribute("typeDocLab", typeDocLab);
    request.setAttribute("demographicNo", demographicNo);
    request.setAttribute("ackStatus", ackStatus);
    request.setAttribute("labdocs", labdocs);
    request.setAttribute("patientNumDoc", patientNumDoc);
    request.setAttribute("totalDocs", totalDocs);
    request.setAttribute("totalHL7", totalHL7);
    request.setAttribute("normals", normals);
    request.setAttribute("abnormals", abnormals);
    request.setAttribute("totalNumDocs", totalNumDocs);
    request.setAttribute("patientIdNamesStr", patientIdNamesStr);
    request.setAttribute("oldestLab",
            oldestLab != null ? DateUtils.formatDate(oldestLab, "yyyy-MM-dd HH:mm:ss") : null);

    return mapping.findForward("dms_page");
}

From source file:base.BasePlayer.FileRead.java

static void readGTF(File infile, String outfile, SAMSequenceDictionary dict) {
    BufferedReader reader = null;
    GZIPInputStream gzip = null;//  www .  j  a v a2 s  .  com
    FileReader freader = null;
    String line = "", chrom = "-1";
    HashMap<String, String> lineHash;
    HashMap<String, Gene> genes = new HashMap<String, Gene>();
    HashMap<String, Transcript> transcripts = new HashMap<String, Transcript>();
    Gene addgene;
    //Boolean found = false;
    Transcript addtranscript;

    try {

        if (infile.getName().endsWith(".gz")) {
            gzip = new GZIPInputStream(new FileInputStream(infile));
            reader = new BufferedReader(new InputStreamReader(gzip));
        } else {
            freader = new FileReader(infile);
            reader = new BufferedReader(freader);
        }
        //   line = reader.readLine();
        while ((line = reader.readLine()) != null) {

            if (line.startsWith("#")) {
                continue;
            }
            /*
            if(!line.contains("Rp1h")) {
               if(found) {
                  break;
               }
               continue;
            }
            found = true;
            */

            lineHash = makeHash(line.split("\t"));
            chrom = lineHash.get("seqid");

            if (!genes.containsKey(lineHash.get("gene_id"))) {
                /*if(genes.size() > 1) {
                   break;
                }*/
                Gene gene = new Gene(chrom, lineHash, true);

                genes.put(lineHash.get("gene_id"), gene);
                if (lineHash.get("transcript_id") == null) {
                    continue;
                }
                //continue;
            }
            if (!transcripts.containsKey(lineHash.get("transcript_id"))) {

                addgene = genes.get(lineHash.get("gene_id"));
                transcripts.put(getInfoValue(lineHash, "transcript_id"), new Transcript(lineHash, addgene));
                if (lineHash.get("type").equals("exon")) {
                    addtranscript = transcripts.get(getInfoValue(lineHash, "transcript_id"));
                    addtranscript.addExon(lineHash, addtranscript);
                }
                if (addgene.getDescription().equals("-")) {
                    if (lineHash.containsKey("gene_symbol")) {
                        addgene.setDescription(lineHash.get("gene_symbol"));
                    }
                }
                continue;
            }
            if (transcripts.containsKey(lineHash.get("transcript_id"))) {
                if (lineHash.get("type").contains("UTR")) {
                    continue;
                }
                addtranscript = transcripts.get(lineHash.get("transcript_id"));
                addtranscript.addExon(lineHash, addtranscript);

                continue;
            }

        }

    } catch (Exception e) {
        System.out.println(line);
        e.printStackTrace();
        System.exit(0);
    }
    try {

        Transcript transcript;
        Gene gene;
        StringBuffer exStarts, exEnds, exPhases;
        Iterator<Map.Entry<String, Gene>> it = genes.entrySet().iterator();
        ArrayList<String[]> geneArray = new ArrayList<String[]>();

        while (it.hasNext()) {
            Map.Entry<String, Gene> pair = (Map.Entry<String, Gene>) it.next();
            gene = pair.getValue();

            for (int i = 0; i < gene.getTranscripts().size(); i++) {
                transcript = gene.getTranscripts().get(i);
                exStarts = new StringBuffer("");
                exEnds = new StringBuffer("");
                exPhases = new StringBuffer("");
                for (int e = 0; e < transcript.exonArray.size(); e++) {
                    exStarts.append(transcript.exonArray.get(e).getStart() + ",");
                    exEnds.append(transcript.exonArray.get(e).getEnd() + ",");
                    exPhases.append(transcript.exonArray.get(e).getStartPhase() + ",");
                }

                String[] row = { gene.getChrom(), "" + transcript.getStart(), "" + transcript.getEnd(),
                        gene.getName(), "" + transcript.exonArray.size(),
                        MethodLibrary.getStrand(gene.getStrand()), gene.getID(), transcript.getENST(),
                        transcript.getUniprot(), "-", transcript.getBiotype(), "" + transcript.getCodingStart(),
                        "" + transcript.getCodingEnd(), exStarts.toString(), exEnds.toString(),
                        exPhases.toString(), transcript.getDescription() };
                if (transcript.getCodingEnd() == -1) {
                    row[11] = "" + gene.getEnd();
                    row[12] = "" + gene.getStart();
                }

                geneArray.add(row);
            }

            it.remove();
        }

        gffSorter gffsorter = new gffSorter();
        Collections.sort(geneArray, gffsorter);

        if (outfile != null) {
            MethodLibrary.blockCompressAndIndex(geneArray, outfile, false, dict);
        }

        geneArray.clear();
        if (freader != null) {
            freader.close();
        }
        reader.close();

        if (gzip != null) {
            gzip.close();
        }

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

}

From source file:edu.harvard.i2b2.explorer.dataModel.TimelineFactory.java

@SuppressWarnings("unchecked")
public String generateTimelineData(String result, ArrayList<TimelineRow> rows, boolean writeFile,
        boolean displayAll, boolean displayDemographics, final MainComposite explorer) {

    try {/*from   w ww .  j  a  v  a  2s .  c  o  m*/
        PDOResponseMessageModel pdoresponsefactory = new PDOResponseMessageModel();
        StatusType statusType = pdoresponsefactory.getStatusFromResponseXML(result);
        if (!statusType.getType().equalsIgnoreCase("DONE")) {
            return "error";
        }

        JAXBUtil jaxbUtil = ExplorerJAXBUtil.getJAXBUtil();

        JAXBElement jaxbElement = jaxbUtil.unMashallFromString(result);
        ResponseMessageType messageType = (ResponseMessageType) jaxbElement.getValue();
        BodyType bodyType = messageType.getMessageBody();
        PatientDataResponseType responseType = (PatientDataResponseType) new JAXBUnWrapHelper()
                .getObjectByClass(bodyType.getAny(), PatientDataResponseType.class);
        PageType pageType = responseType.getPage();
        if (pageType != null) {
            final int returnLastIndex = pageType.getPagingByPatients().getPatientsReturned().getLastIndex()
                    .intValue();
            final int returnFirstIndex = pageType.getPagingByPatients().getPatientsReturned().getFirstIndex()
                    .intValue();
            final int requestLastIndex = pageType.getPagingByPatients().getPatientsRequested().getLastIndex()
                    .intValue();
            if (returnLastIndex < requestLastIndex) {
                // System.out.println("Can't return all the requested "+
                // requestIndex+" patients, only "+returnIndex+" patients returned");
                explorer.getDisplay().syncExec(new Runnable() {
                    public void run() {
                        // MessageBox mBox = new MessageBox(explorer
                        // .getShell(), SWT.ICON_INFORMATION
                        // | SWT.OK );
                        // mBox.setText("Please Note ...");
                        // mBox.setMessage("Only "+(returnLastIndex-returnFirstIndex+1)+" patients returned");
                        // mBox.open();
                        if (explorer.runMode() >= 0) {
                            explorer.setIncrementNumber(returnLastIndex - returnFirstIndex + 1);
                        } else if (explorer.runMode() == -1) {
                            explorer.setDecreaseNumber(returnLastIndex - returnFirstIndex + 1);
                        }
                    }
                });
                explorer.returnedNumber(returnLastIndex - returnFirstIndex + 1);
            } else {
                explorer.returnedNumber(-1);
            }
        } else {
            explorer.getDisplay().syncExec(new Runnable() {
                public void run() {
                    // MessageBox mBox = new MessageBox(explorer
                    // .getShell(), SWT.ICON_INFORMATION
                    // | SWT.OK );
                    // mBox.setText("Please Note ...");
                    // mBox.setMessage("Only "+(returnLastIndex-returnFirstIndex+1)+" patients returned");
                    // mBox.open();
                    if (explorer.runMode() >= 0) {
                        explorer.setIncrementNumber(-1);
                    } else if (explorer.runMode() == -1) {
                        explorer.setDecreaseNumber(-1);
                    }
                }
            });
        }

        StringBuilder resultFile = new StringBuilder();
        resultFile.append(GetTimelineHeader());

        PatientSet patientDimensionSet = pdoresponsefactory.getPatientSetFromResponseXML(result);
        if (patientDimensionSet != null) {
            log.debug("Total patient: " + patientDimensionSet.getPatient().size());
            // for(int i=0;
            // i<patientDimensionSet.getPatientDimension().size();i++) {
            // PatientDimensionType patientType =
            // patientDimensionSet.getPatientDimension().get(i);
            // System.out.println("PatientNum: " +
            // patientType.getPatientNum());
            // }
        } else {
            return "error";
        }

        // / testing the visit set
        // PatientDataType.VisitDimensionSet visitSet =
        // pdoresponsefactory.getVisitSetFromResponseXML(result);
        // System.out.println("Total visits: "+visitSet.getVisitDimension().
        // size());

        List<ObservationSet> factSets = pdoresponsefactory.getFactSetsFromResponseXML(result);

        log.debug("\nGenerate lld:");

        String curPNum = "-1";
        for (int i = 0; i < patientDimensionSet.getPatient().size(); i++) {
            PatientType patientType = patientDimensionSet.getPatient().get(i);
            String pnum = patientType.getPatientId().getValue();
            // Integer pnum = new Integer(snum);
            // log.debug("PatientNum: " + snum);
            //if(curPNum.equals("-1")) {
            curPNum = new String(pnum);
            //}

            if (displayDemographics) {
                resultFile.append(getTimelinePatientString(pnum.toString(), patientType));
            } else {
                resultFile.append(getTimelinePatientString(pnum.toString()));
            }

            String path = null;
            TimelineRow currentRow = null;
            ObservationSet observationFactSet = null;

            for (int j = 0; j < rows.size(); j++) {
                TimelineRow row = rows.get(j);
                int total = 0;
                StringBuilder resultString = new StringBuilder();

                XMLGregorianCalendar curStartDate = null;
                //int currentInstanceNum = 0;
                //String currentConcept = "";
                ArrayList<ObservationType> facts = new ArrayList<ObservationType>();
                ObservationType curFact = null;
                boolean recorded = false;
                String sStart_date = null;
                String sEnd_date = null;

                // loop thru all the pdo sets for this row here
                for (int s = 0; s < row.pdoItems.size(); s++) {
                    PDOItem pset = row.pdoItems.get(s);
                    observationFactSet = null;

                    for (int m = 0; m < factSets.size(); m++) {
                        ObservationSet tmpFactSet = factSets.get(m);
                        if (tmpFactSet.getPanelName().equalsIgnoreCase(pset.panelName())) {
                            observationFactSet = tmpFactSet;
                            path = observationFactSet.getPanelName();
                            currentRow = row;
                            break;
                        }
                    }

                    if (observationFactSet == null) {
                        continue;
                    }

                    for (int k = 0; k < observationFactSet.getObservation().size(); k++) {
                        ObservationType obsFactType = observationFactSet.getObservation().get(k);
                        //if(curFact == null) {
                        //curFact = obsFactType;
                        //}

                        //facts.add(obsFactType);

                        if (pnum.equals(obsFactType.getPatientId().getValue())) {
                            /*
                             * if ((curStartDate != null) &&
                             * (obsFactType.getStartDate().compare(
                             * curStartDate) == DatatypeConstants.EQUAL)) {
                             * continue; }
                             */
                            if (curFact == null) {
                                curFact = obsFactType;
                            }

                            if (curStartDate == null) {
                                curStartDate = obsFactType.getStartDate();
                            }

                            sStart_date = obsFactType.getStartDate().getMonth() + "-"
                                    + obsFactType.getStartDate().getDay() + "-"
                                    + obsFactType.getStartDate().getYear();

                            if (obsFactType.getEndDate() == null) {
                                sEnd_date = sStart_date;
                            } else {
                                sEnd_date = obsFactType.getEndDate().getMonth() + "-"
                                        + obsFactType.getEndDate().getDay() + "-"
                                        + obsFactType.getEndDate().getYear();
                            }

                            double nval = -1;
                            if (obsFactType.getNvalNum().getValue() != null) {
                                nval = obsFactType.getNvalNum().getValue().doubleValue();
                            }
                            PDOValueModel valdp = null;

                            boolean same = sameInstance(curFact, obsFactType);
                            if (false) {//pset.hasValueDisplayProperty) {
                                for (int n = 0; n < pset.valDisplayProperties.size(); n++) {
                                    PDOValueModel tmpvaldp = pset.valDisplayProperties.get(n);
                                    // if (tmpvaldp.inRange(nval)) {
                                    valdp = tmpvaldp;
                                    // break;
                                    // }
                                }

                                String sValue = getSValue(obsFactType.getConceptCd().getName(), obsFactType,
                                        true);
                                if ((curStartDate != null) && (obsFactType.getStartDate()
                                        .compare(curStartDate) == DatatypeConstants.EQUAL)) {
                                    resultString.append(getTimelineDateStringHeight(sStart_date, sEnd_date,
                                            "slateblue", valdp.height, sValue));
                                } else {
                                    resultString.append(getTimelineDateStringHeight(sStart_date, sEnd_date,
                                            valdp.color, valdp.height, sValue));
                                }
                            } else {
                                //////////////////////
                                String sValue = "";
                                if (same && k != observationFactSet.getObservation().size() - 1) {
                                    //if(recorded) {
                                    facts.add(obsFactType);
                                    //recorded = false;
                                    continue;
                                    //}
                                    /*sValue = getSValueSame(obsFactType.getConceptCd().getName(),
                                          obsFactType, false);
                                    if ((curStartDate != null)
                                          && (obsFactType.getStartDate()
                                                .compare(curStartDate) == DatatypeConstants.EQUAL)) {
                                       resultString
                                             .append(getTimelineDateStringHeightSame(
                                     sStart_date, sEnd_date,
                                     "slateblue",
                                     pset.height, sValue));
                                    } else {
                                       resultString
                                             .append(getTimelineDateStringHeightSame(
                                     sStart_date, sEnd_date,
                                     pset.color,
                                     pset.height, sValue));
                                    }*/
                                }
                                //else {
                                if (facts.size() == 0) {
                                    facts.add(obsFactType);
                                }
                                sValue = getSValue(curFact.getConceptCd().getName(), facts, false);
                                //}

                                sStart_date = curFact.getStartDate().getMonth() + "-"
                                        + curFact.getStartDate().getDay() + "-"
                                        + curFact.getStartDate().getYear();

                                if (curFact.getEndDate() == null) {
                                    sEnd_date = sStart_date;
                                } else {
                                    sEnd_date = curFact.getEndDate().getMonth() + "-"
                                            + curFact.getEndDate().getDay() + "-"
                                            + curFact.getEndDate().getYear();
                                }

                                //if ((curStartDate != null)
                                //      && (obsFactType.getStartDate()
                                //      .compare(curStartDate) == DatatypeConstants.EQUAL)) {
                                //resultString
                                //.append(getTimelineDateStringHeight(
                                //sStart_date, sEnd_date,
                                //"slateblue",
                                //pset.height, sValue));
                                //} else {
                                resultString.append(getTimelineDateStringHeight(sStart_date, sEnd_date,
                                        pset.color, pset.height, sValue));
                                //}
                            }

                            total++;
                            recorded = false;
                            facts.clear();
                            facts.add(obsFactType);
                            curStartDate = obsFactType.getStartDate();
                            curFact = obsFactType;

                            /////
                            if (!same && k == observationFactSet.getObservation().size() - 1) {
                                String sValue = "";
                                sValue = getSValue(obsFactType.getConceptCd().getName(), facts, false);
                                //}

                                sStart_date = obsFactType.getStartDate().getMonth() + "-"
                                        + obsFactType.getStartDate().getDay() + "-"
                                        + obsFactType.getStartDate().getYear();

                                if (obsFactType.getEndDate() == null) {
                                    sEnd_date = sStart_date;
                                } else {
                                    sEnd_date = obsFactType.getEndDate().getMonth() + "-"
                                            + obsFactType.getEndDate().getDay() + "-"
                                            + obsFactType.getEndDate().getYear();
                                }

                                //if ((curStartDate != null)
                                //      && (obsFactType.getStartDate()
                                //      .compare(curStartDate) == DatatypeConstants.EQUAL)) {
                                //resultString
                                //.append(getTimelineDateStringHeight(
                                //sStart_date, sEnd_date,
                                //"slateblue",
                                //pset.height, sValue));
                                //} else {
                                resultString.append(getTimelineDateStringHeight(sStart_date, sEnd_date,
                                        pset.color, pset.height, sValue));
                                //}
                                total++;
                            }
                            ////
                        } else {
                            if (recorded || facts.size() == 0) {
                                curPNum = new String(pnum);
                                continue;
                            }
                            sStart_date = curStartDate.getMonth() + "-" + curStartDate.getDay() + "-"
                                    + curStartDate.getYear();

                            //if (obsFactType.getEndDate() == null) {
                            //sEnd_date = sStart_date;
                            //} else {
                            sEnd_date = curStartDate.getMonth() + "-" + curStartDate.getDay() + "-"
                                    + curStartDate.getYear() + " 12:00";
                            //}
                            //curFact = null;
                            String sValue = getSValue(curFact.getConceptCd().getName(), facts, false);
                            //if ((curStartDate != null)
                            //&& (obsFactType.getStartDate()
                            //.compare(curStartDate) == DatatypeConstants.EQUAL)) {
                            //resultString
                            //.append(getTimelineDateStringHeight(
                            //sStart_date, sEnd_date,
                            //"slateblue",
                            //pset.height, sValue));
                            //} else {
                            resultString.append(getTimelineDateStringHeight(sStart_date, sEnd_date, pset.color,
                                    pset.height, sValue));
                            //}
                            total++;
                            recorded = true;
                            facts.clear();
                            curStartDate = null;//obsFactType.getStartDate();
                            curFact = null;//obsFactType;
                            curPNum = new String(pnum);
                        }
                    }
                }

                if (total > 0) {
                    // log.debug("-- "+path+" has "+total+" events");
                    resultFile.append(getTimelineConceptString(row.displayName, total));

                    // log.debug(resultString.toString());
                    resultFile.append(resultString);
                    total = 0;
                    recorded = true;
                } else {
                    // display all
                    if (displayAll) {
                        // log.debug("-- "+path+" has "+total+" events");
                        resultFile.append(getTimelineConceptString(row.displayName, 1));

                        // log.debug(getTimelineEmptyDateString());
                        resultFile.append(getTimelineEmptyDateString());
                    }
                }

                if (recorded || facts.size() == 0) {
                    curPNum = new String(pnum);
                    continue;
                }
                sStart_date = curStartDate.getMonth() + "-" + curStartDate.getDay() + "-"
                        + curStartDate.getYear();

                //if (obsFactType.getEndDate() == null) {
                //sEnd_date = sStart_date;
                //} else {
                sEnd_date = curStartDate.getMonth() + "-" + curStartDate.getDay() + "-"
                        + curStartDate.getYear();
                //}
                //curFact = null;
                String sValue = getSValue(curFact.getConceptCd().getName(), facts, false);

                resultString
                        .append(getTimelineDateStringHeight(sStart_date, sEnd_date, "navyblue", "p10", sValue));

                total++;
                recorded = true;
                facts.clear();
                //curStartDate = obsFactType.getStartDate();
                //curFact = obsFactType;
                curPNum = new String(pnum);
                if (total > 0) {
                    // log.debug("-- "+path+" has "+total+" events");
                    resultFile.append(getTimelineConceptString(row.displayName, total));

                    // log.debug(resultString.toString());
                    resultFile.append(resultString);
                }
            }
        }

        resultFile.append(GetTimelineFooter());

        if (writeFile) {
            String i2b2File = System.getProperty("user.dir") + "/temp/" + "i2b2xml.lld";
            File oDelete = new File(i2b2File);
            if (oDelete != null)
                oDelete.delete();
            RandomAccessFile f = new RandomAccessFile(i2b2File, "rw");
            append(f, resultFile.toString());
            f.close();
        }

        // log.debug("\nThe lld file: \n"+resultFile.toString());
        return resultFile.toString();
    } catch (org.apache.axis2.AxisFault e) {
        e.printStackTrace();
        log.error(e.getMessage());
        return null;
    } catch (Exception e) {
        log.error(e.getMessage());
        e.printStackTrace();
        return "error";
    }
}

From source file:com.hygenics.parser.ParseJSoup.java

/**
 * Runs the Program/*www  .j ava  2s .  c om*/
 */
public void run() {
    int its = 0;

    this.select = Properties.getProperty(this.select);
    this.extracondition = Properties.getProperty(this.extracondition);
    this.column = Properties.getProperty(this.column);

    createTables();
    log.info("Starting Parse via JSoup @ " + Calendar.getInstance().getTime().toString());

    ForkJoinPool fjp = new ForkJoinPool(Runtime.getRuntime().availableProcessors() * procs);
    Set<Callable<ArrayList<String>>> collection;
    List<Future<ArrayList<String>>> futures;
    ArrayList<String> data = new ArrayList<String>((commitsize + 10));
    ArrayList<String> outdata = new ArrayList<String>(((commitsize + 10) * 3));
    int offenderhash = offset;

    boolean run = true;
    int iteration = 0;

    int currpos = 0;
    do {
        collection = new HashSet<Callable<ArrayList<String>>>(qnums);
        log.info("Getting Data");
        // get data
        currpos = iteration * commitsize + offset;
        iteration += 1;
        String query = select;

        if (extracondition != null) {
            query += " " + extracondition;
        }

        if (extracondition != null) {
            query += " WHERE " + extracondition + " AND ";
        } else {
            query += " WHERE ";
        }

        for (int i = 0; i < qnums; i++) {

            if (currpos + (Math.round(commitsize / qnums * (i + 1))) < currpos + commitsize) {
                collection.add(new SplitQuery((query + pullid + " >= "
                        + Integer.toString(currpos + (Math.round(commitsize / qnums * (i)))) + " AND " + pullid
                        + " < " + Integer.toString(currpos + (Math.round(commitsize / qnums * (i + 1)))))));
            } else {
                collection.add(new SplitQuery((query + pullid + " >= "
                        + Integer.toString(currpos + (Math.round(commitsize / qnums * (i)))) + " AND " + pullid
                        + " < " + Integer.toString(currpos + commitsize))));
            }
        }

        if (collection.size() > 0) {

            futures = fjp.invokeAll(collection);

            int w = 0;

            while (fjp.isQuiescent() == false && fjp.getActiveThreadCount() > 0) {
                w++;
            }

            for (Future<ArrayList<String>> f : futures) {
                try {
                    // TODO Get Pages to Parse
                    data.addAll(f.get());
                } catch (NullPointerException e) {
                    log.info("Some Data Returned Null");
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }

        collection = new HashSet<Callable<ArrayList<String>>>(data.size());
        // checkstring
        if (data.size() == 0 && checkstring != null && its <= maxchecks) {
            its++;
            collection.add(new SplitQuery(checkstring));

            futures = fjp.invokeAll(collection);

            int w = 0;
            while (fjp.isQuiescent() == false && fjp.getActiveThreadCount() > 0) {
                w++;
            }

            for (Future<ArrayList<String>> f : futures) {
                try {
                    // TODO Get Pages to Parse
                    data.addAll(f.get());
                } catch (NullPointerException e) {
                    log.info("Some Data Returned Null");
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }

        if (data.size() == 0) {
            // set to stop if size is0
            log.info("No Pages to Parse. Will Terminate");
            run = false;
        } else {
            // parse
            log.info("Starting JSoup Parse @ " + Calendar.getInstance().getTime().toString());
            for (String json : data) {
                // faster json reader is minimal json but faster parser is
                // Simple Json
                Map<String, Json> jMap = Json.read(json).asJsonMap();

                if (jMap.containsKey("offenderhash")) {
                    // string to int in case it is a string and has some
                    // extra space
                    offenderhash = Integer.parseInt(jMap.get("offenderhash").asString().trim());
                }

                boolean allow = true;

                if (mustcontain != null) {
                    if (jMap.get(column).asString().contains(mustcontain) == false) {
                        allow = false;
                    }
                }

                if (cannotcontain != null) {
                    if (jMap.get(column).asString().contains(cannotcontain)) {
                        allow = false;
                    }
                }

                // this is the fastest way. I was learning before and will
                // rewrite when time permits.
                if (allow == true) {
                    if (jMap.containsKey("offenderhash")) {
                        if (this.singlepaths != null) {
                            collection.add(new ParseSingle(Integer.toString(offenderhash), header, footer,
                                    pagenarrow, singlepaths,
                                    StringEscapeUtils.unescapeXml(jMap.get(column).asString()), replace,
                                    replaceSequence));
                        }

                        if (this.multipaths != null) {
                            collection.add(new ParseRows(Integer.toString(offenderhash), header, footer,
                                    pagenarrow, multipaths,
                                    StringEscapeUtils.unescapeXml(jMap.get(column).asString()), replace,
                                    replaceSequence));
                        }

                        if (this.recordpaths != null) {
                            collection.add(new ParseLoop(Integer.toString(offenderhash), header, footer,
                                    pagenarrow, recordpaths,
                                    StringEscapeUtils.unescapeXml(jMap.get(column).asString()), replace,
                                    replaceSequence));
                        }
                    }
                }
                offenderhash += 1;

            }

            // complete parse
            log.info("Waiting for Parsing to Complete.");
            if (collection.size() > 0) {
                futures = fjp.invokeAll(collection);

                int w = 0;
                while (fjp.isQuiescent() && fjp.getActiveThreadCount() > 0) {
                    w++;
                }

                log.info("Waited for " + Integer.toString(w) + " Cycles!");
                for (Future<ArrayList<String>> f : futures) {
                    try {
                        outdata.addAll(f.get());
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch (ExecutionException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }

            }
            log.info("Finished Parsing @ " + Calendar.getInstance().getTime().toString());

            int cp = 0;
            // post data
            log.info("Posting Data @ " + Calendar.getInstance().getTime().toString());
            if (outdata.size() > 0) {

                for (int i = 0; i < qnums; i++) {

                    ArrayList<String> od = new ArrayList<String>(
                            ((cp + (Math.round(outdata.size() / qnums) - cp))));

                    if (cp + (Math.round(outdata.size() / qnums)) < outdata.size()) {
                        od.addAll(outdata.subList(cp, (cp + (Math.round(outdata.size() / qnums)))));
                    } else {
                        od.addAll(outdata.subList(cp, (outdata.size() - 1)));
                    }
                    fjp.execute(new SplitPost(template, od));
                    cp += Math.round(outdata.size() / qnums);
                }

                int w = 0;
                while (fjp.getActiveThreadCount() > 0 && fjp.isQuiescent() == false) {
                    w++;
                }
                log.info("Waited for " + Integer.toString(w) + " cycles!");

            }
            log.info("Finished Posting to DB @ " + Calendar.getInstance().getTime().toString());

            // size should remain same with 10 slot buffer room
            data.clear();
            outdata.clear();
        }

        // my favorite really desperate attempt to actually invoke garbage
        // collection because of MASSIVE STRINGS
        System.gc();
        Runtime.getRuntime().gc();

    } while (run);

    log.info("Shutting Down FJP");
    // shutdown fjp
    if (fjp.isShutdown() == false) {
        fjp.shutdownNow();
    }

    log.info("Finished Parsing @ " + Calendar.getInstance().getTime().toString());

}

From source file:com.sentaroh.android.SMBSync2.SyncTaskUtility.java

public void editFileFilterDlg(final ArrayList<String> file_filter, final NotifyEvent p_ntfy) {
    ArrayList<FilterListItem> filterList = new ArrayList<FilterListItem>();
    final AdapterFilterList filterAdapter;

    // ??// w  w w .j a v a  2s  . co  m
    final Dialog dialog = new Dialog(mContext);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setCanceledOnTouchOutside(false);
    dialog.setContentView(R.layout.filter_list_dlg);

    LinearLayout ll_dlg_view = (LinearLayout) dialog.findViewById(R.id.filter_select_edit_view);
    ll_dlg_view.setBackgroundColor(mGp.themeColorList.dialog_msg_background_color);

    final LinearLayout title_view = (LinearLayout) dialog.findViewById(R.id.filter_select_edit_title_view);
    final TextView title = (TextView) dialog.findViewById(R.id.filter_select_edit_title);
    title_view.setBackgroundColor(mGp.themeColorList.dialog_title_background_color);
    title.setTextColor(mGp.themeColorList.text_color_dialog_title);

    Button dirbtn = (Button) dialog.findViewById(R.id.filter_select_edit_dir_btn);
    dirbtn.setVisibility(Button.GONE);

    filterAdapter = new AdapterFilterList(mContext, R.layout.filter_list_item_view, filterList);
    ListView lv = (ListView) dialog.findViewById(R.id.filter_select_edit_listview);

    for (int i = 0; i < file_filter.size(); i++) {
        String inc = file_filter.get(i).substring(0, 1);
        String filter = file_filter.get(i).substring(1, file_filter.get(i).length());
        boolean b_inc = false;
        if (inc.equals(SMBSYNC_PROF_FILTER_INCLUDE))
            b_inc = true;
        filterAdapter.add(new FilterListItem(filter, b_inc));
    }
    if (filterAdapter.getCount() == 0)
        filterAdapter.add(new FilterListItem(mContext.getString(R.string.msgs_filter_list_no_filter), false));
    lv.setAdapter(filterAdapter);
    //      filterAdapter.getFileFilter().filter("D");
    //      lv.setTextFilterEnabled(false);
    //      lv.setDivider(new ColorDrawable(Color.WHITE));
    title.setText(mContext.getString(R.string.msgs_filter_list_dlg_file_filter));
    final TextView dlg_msg = (TextView) dialog.findViewById(R.id.filter_select_edit_msg);

    CommonDialog.setDlgBoxSizeLimit(dialog, true);
    //      CommonDialog.setDlgBoxSizeCompact(dialog);

    final EditText et_filter = (EditText) dialog.findViewById(R.id.filter_select_edit_new_filter);
    final Button addBtn = (Button) dialog.findViewById(R.id.filter_select_edit_add_btn);
    final Button btn_cancel = (Button) dialog.findViewById(R.id.filter_select_edit_cancel_btn);
    final Button btn_ok = (Button) dialog.findViewById(R.id.filter_select_edit_ok_btn);

    lv.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> items, View view, int idx, long id) {
            FilterListItem fli = filterAdapter.getItem(idx);
            if (fli.getFilter().startsWith("---") || fli.isDeleted())
                return;
            // ????????
            editDirFilter(idx, filterAdapter, fli, fli.getFilter());
        }
    });

    // Add?
    addBtn.setEnabled(false);
    et_filter.addTextChangedListener(new TextWatcher() {
        @Override
        public void afterTextChanged(Editable s) {
            if (s.length() != 0) {
                if (isFilterExists(s.toString().trim(), filterAdapter)) {
                    String mtxt = mContext.getString(R.string.msgs_filter_list_duplicate_filter_specified);
                    dlg_msg.setText(String.format(mtxt, s.toString().trim()));
                    addBtn.setEnabled(false);
                    btn_ok.setEnabled(true);
                } else {
                    dlg_msg.setText("");
                    addBtn.setEnabled(true);
                    btn_ok.setEnabled(false);
                }
            } else {
                addBtn.setEnabled(false);
                btn_ok.setEnabled(true);
            }
            //            et_filter.setText(s);
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    });
    addBtn.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            dlg_msg.setText("");
            String newfilter = et_filter.getText().toString().trim();
            et_filter.setText("");
            if (filterAdapter.getItem(0).getFilter().startsWith("---"))
                filterAdapter.remove(filterAdapter.getItem(0));
            filterAdapter.add(new FilterListItem(newfilter, true));
            filterAdapter.setNotifyOnChange(true);
            filterAdapter.sort(new Comparator<FilterListItem>() {
                @Override
                public int compare(FilterListItem lhs, FilterListItem rhs) {
                    return lhs.getFilter().compareToIgnoreCase(rhs.getFilter());
                };
            });
            btn_ok.setEnabled(true);
        }
    });

    // CANCEL?
    btn_cancel.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            dialog.dismiss();
            //            glblParms.profileListView.setSelectionFromTop(currentViewPosX,currentViewPosY);
        }
    });
    // Cancel?
    dialog.setOnCancelListener(new Dialog.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface arg0) {
            btn_cancel.performClick();
        }
    });
    // OK?
    btn_ok.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            dialog.dismiss();
            file_filter.clear();
            if (filterAdapter.getCount() > 0) {
                for (int i = 0; i < filterAdapter.getCount(); i++) {
                    if (!filterAdapter.getItem(i).isDeleted()
                            && !filterAdapter.getItem(i).getFilter().startsWith("---")) {
                        String inc = SMBSYNC_PROF_FILTER_EXCLUDE;
                        if (filterAdapter.getItem(i).getInc())
                            inc = SMBSYNC_PROF_FILTER_INCLUDE;
                        file_filter.add(inc + filterAdapter.getItem(i).getFilter());
                    }

                }
            }
            p_ntfy.notifyToListener(true, null);
        }
    });
    //      dialog.setOnKeyListener(new DialogOnKeyListener(context));
    //      dialog.setCancelable(false);
    dialog.show();

}