List of usage examples for java.util ArrayList indexOf
public int indexOf(Object o)
From source file:com.krawler.spring.hrms.rec.job.hrmsRecJobController.java
public JSONObject getJobApplicationsJson(HttpServletRequest request, HttpServletResponse response) { KwlReturnObject result = null, recruitresult = null; JSONObject jobj = new JSONObject(); JSONArray jarr = new JSONArray(); String hql = ""; int count = 0; boolean isadmin = false; HashMap<String, Object> requestParams = new HashMap<String, Object>(); int type = 0; try {// w ww . j a va 2 s . co m DateFormat df = sessionHandlerImplObj.getDateFormatter(request); String Searchjson = request.getParameter("searchJson"); List lst = null; List lst1 = null; String cmpid = sessionHandlerImplObj.getCompanyid(request); String userid = sessionHandlerImplObj.getUserid(request); requestParams.clear(); requestParams.put("userid", userid); if (hrmsCommonDAOObj.isAdmin(userid)) { isadmin = true; } ArrayList params = new ArrayList(); ArrayList filter_name = new ArrayList(); ArrayList order_by = new ArrayList(); ArrayList order_type = new ArrayList(); String ss = request.getParameter("ss"); int statusid = StringUtil.isNullOrEmpty(request.getParameter("statusid")) ? -1 : Integer.parseInt(request.getParameter("statusid")); String tempstatus = statusid == 1 ? "Pending" : (statusid == 2 ? "Shortlisted" : (statusid == 3 ? "In Process" : (statusid == 4 ? "On Hold" : ""))); if (StringUtil.isNullOrEmpty(request.getParameter("userid"))) { int emptype = Integer.parseInt(request.getParameter("employeetype")); type = emptype; int gridst = Integer.parseInt(request.getParameter("gridst")); String[] searchArray = null; String[] searchArray1 = null; if (emptype == 1) {//Internal searchArray = new String[] { "employee.firstName", "employee.lastName", "position.jobid", "position.departmentid.value" }; params.add(0); filter_name.add("employee.deleteflag"); } else if (emptype == 2) { // else added to execute only one condition emptype = 1; searchArray = new String[] { "employee.firstName", "employee.lastName", "position.jobid", "position.departmentid.value" }; searchArray1 = new String[] { "configjobapplicant.col1", "configjobapplicant.col2", "position.jobid", "position.departmentid.value" }; params.add(0); filter_name.add("employee.deleteflag"); params.add(false); filter_name.add("configjobapplicant.deleted"); } else {//External searchArray = new String[] { "configjobapplicant.col1", "configjobapplicant.col2", "position.jobid", "position.departmentid.value" }; params.add(false); filter_name.add("configjobapplicant.deleted"); } if (emptype == 0) { emptype = 4; //configjobapplicant=4 reset to 0 } if (StringUtil.isNullOrEmpty(request.getParameter("status"))) { params.add(gridst); params.add(cmpid); params.add(0); params.add(emptype); //params.add(false); filter_name.add("applicationflag"); filter_name.add("company.companyID"); filter_name.add("delflag"); filter_name.add("employeetype"); //filter_name.add("configjobapplicant.deleted"); } else { if (!tempstatus.equals("")) { params.add(gridst); params.add(cmpid); params.add(0); params.add(tempstatus); params.add(emptype); filter_name.add("applicationflag"); filter_name.add("company.companyID"); filter_name.add("delflag"); filter_name.add("status"); filter_name.add("employeetype"); } else { params.add(gridst); params.add(cmpid); params.add(0); params.add(emptype); filter_name.add("applicationflag"); filter_name.add("company.companyID"); filter_name.add("delflag"); filter_name.add("employeetype"); } } if (!isadmin) { params.add(userid); filter_name.add("position.manager.userID"); } order_by.add("position.positionid"); order_type.add("asc"); requestParams.put("filter_names", filter_name); requestParams.put("filter_values", params); ArrayList params1 = new ArrayList(params); ArrayList filter_name1 = new ArrayList(filter_name); if (filter_name1.contains("employee.deleteflag")) { params1.remove(filter_name1.indexOf("employee.deleteflag")); filter_name1.remove("employee.deleteflag"); } if (filter_name.contains("configjobapplicant.deleted") && !(emptype == 4)) { params.remove(filter_name.indexOf("configjobapplicant.deleted")); filter_name.remove("configjobapplicant.deleted"); } requestParams.put("filter_names1", filter_name1); requestParams.put("filter_values1", params1); requestParams.put("order_by", order_by); requestParams.put("order_type", order_type); requestParams.put("ss", request.getParameter("ss")); requestParams.put("searchcol", searchArray); requestParams.put("searchcol1", searchArray1); requestParams.put("allflag", true); if (!StringUtil.isNullOrEmpty(Searchjson)) { getMyAdvanceSearchparams1(Searchjson, filter_name, (type != 2 ? type : 1)); insertParamAdvanceSearchString1(params, Searchjson, type); getMyAdvanceSearchparams1(Searchjson, filter_name1, (type != 2 ? type : 0)); insertParamAdvanceSearchString1(params1, Searchjson, type); } StringUtil.checkpaging(requestParams, request); result = hrmsRecJobDAOObj.getPositionstatus(requestParams); } else { params.add(request.getParameter("userid")); params.add(cmpid); params.add(0); params.add(false); filter_name.add("configjobapplicant.id"); filter_name.add("company.companyID"); filter_name.add("delflag"); filter_name.add("configjobapplicant.deleted"); order_by.add("position.positionid"); order_type.add("asc"); requestParams.put("filter_names", filter_name); 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[] { "position.jobid", "position.position.value" }); requestParams.put("allflag", true); if (!StringUtil.isNullOrEmpty(Searchjson)) { getMyAdvanceSearchparams1(Searchjson, filter_name, type); insertParamAdvanceSearchString1(params, Searchjson, type); } StringUtil.checkpaging(requestParams, request); result = hrmsRecJobDAOObj.getPositionstatus(requestParams); } Allapplications allapps = null; count = result.getRecordTotalCount(); lst = result.getEntityList(); for (int ctr = 0; ctr < lst.size(); ctr++) { // if(isadmin){ allapps = (Allapplications) lst.get(ctr); // }else{ // Recruiter rec=(Recruiter) lst.get(ctr); // allapps = rec.getAllapplication(); // } JSONObject tmpObj = new JSONObject(); tmpObj.put("rejectedbefore", (allapps.getRejectedbefore() == 0) ? "No" : "Yes"); tmpObj.put("id", ""); tmpObj.put("posid", allapps.getPosition().getPositionid()); tmpObj.put("designationid", allapps.getPosition().getPosition().getId()); tmpObj.put("departmentid", allapps.getPosition().getDepartmentid().getId()); tmpObj.put("department", allapps.getPosition().getDepartmentid().getValue()); tmpObj.put("Department", allapps.getPosition().getDepartmentid().getValue()); tmpObj.put("designation", allapps.getPosition().getPosition().getValue()); tmpObj.put("jobpositionid", allapps.getPosition().getJobid()); tmpObj.put("jobid", allapps.getPosition().getJobid()); tmpObj.put("JobId", allapps.getPosition().getJobid()); tmpObj.put("vacancy", allapps.getPosition().getNoofpos()); tmpObj.put("filled", allapps.getPosition().getPositionsfilled()); tmpObj.put("jname", allapps.getPosition().getPosition().getValue()); tmpObj.put("applydt", df.format(allapps.getApplydate())); tmpObj.put("interviewdt", (allapps.getInterviewdate() == null ? "" : df.format(allapps.getInterviewdate()))); tmpObj.put("joiningdate", (allapps.getJoiningdate() == null ? "" : df.format(allapps.getJoiningdate()))); tmpObj.put("status", allapps.getStatus()); tmpObj.put("jobDetails", allapps.getPosition().getDetails()); if (allapps.getConfigjobapplicant() != null) { tmpObj.put("apcntid", allapps.getConfigjobapplicant().getId()); tmpObj.put("cname", allapps.getConfigjobapplicant().getCol1() + " " + allapps.getConfigjobapplicant().getCol2()); tmpObj.put("email", allapps.getConfigjobapplicant().getCol3()); tmpObj.put("fname", allapps.getConfigjobapplicant().getCol1()); tmpObj.put("lname", allapps.getConfigjobapplicant().getCol2()); tmpObj.put("contact", allapps.getConfigjobapplicant().getCol4() != null ? allapps.getConfigjobapplicant().getCol4() : ""); tmpObj.put("addr", allapps.getConfigjobapplicant().getCol6() != null ? allapps.getConfigjobapplicant().getCol6() : ""); tmpObj.put("employeetype", 0); if (!StringUtil.isNullOrEmpty(allapps.getConfigjobapplicant().getCol5())) { tmpObj.put("docid", allapps.getConfigjobapplicant().getCol5()); } // getdocsbyuser(request,allapps.getConfigjobapplicant().getId(),tmpObj); } else { tmpObj.put("apcntid", allapps.getEmployee().getUserID()); tmpObj.put("cname", allapps.getEmployee().getFirstName() + " " + allapps.getEmployee().getLastName()); tmpObj.put("email", allapps.getEmployee().getEmailID()); tmpObj.put("fname", allapps.getEmployee().getFirstName()); tmpObj.put("lname", allapps.getEmployee().getLastName() != null ? allapps.getEmployee().getLastName() : ""); tmpObj.put("contact", allapps.getEmployee().getContactNumber() != null ? allapps.getEmployee().getContactNumber() : ""); tmpObj.put("addr", allapps.getEmployee().getAddress() != null ? allapps.getEmployee().getAddress() : ""); tmpObj.put("employeetype", 1); } ArrayList recruiterparams = new ArrayList(); recruiterparams.add(allapps.getId()); ArrayList filter_names = new ArrayList(); filter_names.add("allapplication.id"); requestParams.clear(); requestParams.put("filter_names", filter_names); requestParams.put("filter_values", recruiterparams); recruitresult = hrmsRecJobDAOObj.getRecruiters(requestParams); String recruiter = ""; if (StringUtil.checkResultobjList(recruitresult)) { List recruiterlist = recruitresult.getEntityList(); for (int k = 0; k < recruiterlist.size(); k++) { Recruiter r = (Recruiter) recruiterlist.get(k); recruiter += (r.getRecruit().getFirstName() + " " + r.getRecruit().getLastName()); if (recruiterlist.size() > k + 1) recruiter += ", "; } } tmpObj.put("recruiter", recruiter); tmpObj.put("callback", (allapps.getCallback() == null ? "" : allapps.getCallback().getValue())); tmpObj.put("interviewplace", allapps.getInterviewplace()); tmpObj.put("interviewcomment", allapps.getInterviewcomment()); tmpObj.put("rank", (allapps.getRank() == null ? "" : allapps.getRank().getValue())); jarr.put(tmpObj); } jobj.put("data", jarr); jobj.put("count", count); } catch (Exception e) { e.printStackTrace(); } finally { return jobj; } }
From source file:com.krawler.spring.hrms.rec.job.hrmsRecJobController.java
public ModelAndView getJobApplications(HttpServletRequest request, HttpServletResponse response) { KwlReturnObject result = null, recruitresult = null; JSONObject jobj = new JSONObject(); JSONObject jobj1 = new JSONObject(); JSONArray jarr = new JSONArray(); String hql = ""; int count = 0; boolean isadmin = false; HashMap<String, Object> requestParams = new HashMap<String, Object>(); int type = 0; try {//from w w w . j a va 2s. c o m String Searchjson = request.getParameter("searchJson"); List lst = null; List lst1 = null; String cmpid = sessionHandlerImplObj.getCompanyid(request); String userid = sessionHandlerImplObj.getUserid(request); requestParams.clear(); requestParams.put("userid", userid); if (hrmsCommonDAOObj.isAdmin(userid)) { isadmin = true; } ArrayList params = new ArrayList(); ArrayList filter_name = new ArrayList(); ArrayList order_by = new ArrayList(); ArrayList order_type = new ArrayList(); String ss = request.getParameter("ss"); int statusid = StringUtil.isNullOrEmpty(request.getParameter("statusid")) ? -1 : Integer.parseInt(request.getParameter("statusid")); String tempstatus = statusid == 1 ? "Pending" : (statusid == 2 ? "Shortlisted" : (statusid == 3 ? "In Process" : (statusid == 4 ? "On Hold" : ""))); if (StringUtil.isNullOrEmpty(request.getParameter("userid"))) { int emptype = Integer.parseInt(request.getParameter("employeetype")); type = emptype; int gridst = Integer.parseInt(request.getParameter("gridst")); String[] searchArray = null; String[] searchArray1 = null; if (emptype == 1) {//Internal searchArray = new String[] { "employee.firstName", "employee.lastName", "position.jobid", "position.departmentid.value" }; params.add(0); filter_name.add("employee.deleteflag"); } else if (emptype == 2) { // else added to execute only one condition emptype = 1; searchArray = new String[] { "employee.firstName", "employee.lastName", "position.jobid", "position.departmentid.value" }; searchArray1 = new String[] { "configjobapplicant.col1", "configjobapplicant.col2", "position.jobid", "position.departmentid.value" }; params.add(0); filter_name.add("employee.deleteflag"); params.add(false); filter_name.add("configjobapplicant.deleted"); } else {//External searchArray = new String[] { "configjobapplicant.col1", "configjobapplicant.col2", "position.jobid", "position.departmentid.value" }; params.add(false); filter_name.add("configjobapplicant.deleted"); } if (emptype == 0) { emptype = 4; //configjobapplicant=4 reset to 0 } if (StringUtil.isNullOrEmpty(request.getParameter("status"))) { params.add(gridst); params.add(cmpid); params.add(0); params.add(emptype); //params.add(false); filter_name.add("applicationflag"); filter_name.add("company.companyID"); filter_name.add("delflag"); filter_name.add("employeetype"); //filter_name.add("configjobapplicant.deleted"); } else { if (!tempstatus.equals("")) { params.add(gridst); params.add(cmpid); params.add(0); params.add(tempstatus); params.add(emptype); filter_name.add("applicationflag"); filter_name.add("company.companyID"); filter_name.add("delflag"); filter_name.add("status"); filter_name.add("employeetype"); } else { params.add(gridst); params.add(cmpid); params.add(0); params.add(emptype); filter_name.add("applicationflag"); filter_name.add("company.companyID"); filter_name.add("delflag"); filter_name.add("employeetype"); } } if (!isadmin) { params.add(userid); filter_name.add("position.manager.userID"); } order_by.add("position.departmentid.value"); order_by.add("position.jobid"); order_type.add(""); order_type.add("asc"); requestParams.put("filter_names", filter_name); requestParams.put("filter_values", params); ArrayList params1 = new ArrayList(params); ArrayList filter_name1 = new ArrayList(filter_name); if (filter_name1.contains("employee.deleteflag")) { params1.remove(filter_name1.indexOf("employee.deleteflag")); filter_name1.remove("employee.deleteflag"); } if (filter_name.contains("configjobapplicant.deleted") && !(emptype == 4)) { params.remove(filter_name.indexOf("configjobapplicant.deleted")); filter_name.remove("configjobapplicant.deleted"); } requestParams.put("filter_names1", filter_name1); requestParams.put("filter_values1", params1); requestParams.put("order_by", order_by); requestParams.put("order_type", order_type); requestParams.put("ss", request.getParameter("ss")); requestParams.put("searchcol", searchArray); requestParams.put("searchcol1", searchArray1); requestParams.put("allflag", false); if (!StringUtil.isNullOrEmpty(Searchjson)) { getMyAdvanceSearchparams1(Searchjson, filter_name, (type != 2 ? type : 1)); insertParamAdvanceSearchString1(params, Searchjson, type); getMyAdvanceSearchparams1(Searchjson, filter_name1, (type != 2 ? type : 0)); insertParamAdvanceSearchString1(params1, Searchjson, type); } StringUtil.checkpaging(requestParams, request); result = hrmsRecJobDAOObj.getPositionstatus(requestParams); } else { params.add(request.getParameter("userid")); params.add(cmpid); params.add(0); params.add(false); filter_name.add("configjobapplicant.id"); filter_name.add("company.companyID"); filter_name.add("delflag"); filter_name.add("configjobapplicant.deleted"); order_by.add("position.departmentid.value"); order_by.add("position.jobid"); order_type.add(""); order_type.add("asc"); requestParams.put("filter_names", filter_name); 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[] { "position.jobid", "position.position.value" }); requestParams.put("allflag", false); if (!StringUtil.isNullOrEmpty(Searchjson)) { getMyAdvanceSearchparams1(Searchjson, filter_name, type); insertParamAdvanceSearchString1(params, Searchjson, type); } StringUtil.checkpaging(requestParams, request); result = hrmsRecJobDAOObj.getPositionstatus(requestParams); } Allapplications allapps = null; count = result.getRecordTotalCount(); lst = result.getEntityList(); for (int ctr = 0; ctr < lst.size(); ctr++) { // if(isadmin){ allapps = (Allapplications) lst.get(ctr); // }else{ // Recruiter rec=(Recruiter) lst.get(ctr); // allapps = rec.getAllapplication(); // } JSONObject tmpObj = new JSONObject(); tmpObj.put("id", allapps.getId()); tmpObj.put("posid", allapps.getPosition().getPositionid()); tmpObj.put("rejectedbefore", allapps.getRejectedbefore()); tmpObj.put("designationid", allapps.getPosition().getPosition().getId()); tmpObj.put("departmentid", allapps.getPosition().getDepartmentid().getId()); tmpObj.put("department", allapps.getPosition().getDepartmentid().getValue()); tmpObj.put("Department", allapps.getPosition().getDepartmentid().getValue()); tmpObj.put("designation", allapps.getPosition().getPosition().getValue()); tmpObj.put("jobpositionid", allapps.getPosition().getJobid()); tmpObj.put("jobid", allapps.getPosition().getPositionid()); tmpObj.put("JobId", allapps.getPosition().getPosition().getValue()); tmpObj.put("vacancy", allapps.getPosition().getNoofpos()); tmpObj.put("filled", allapps.getPosition().getPositionsfilled()); tmpObj.put("jname", allapps.getPosition().getPosition().getValue()); tmpObj.put("applydt", sessionHandlerImplObj.getDateFormatter(request).format(allapps.getApplydate())); tmpObj.put("interviewdt", (allapps.getInterviewdate() == null ? "" : sessionHandlerImplObj.getDateFormatter(request).format(allapps.getInterviewdate()))); tmpObj.put("joiningdate", (allapps.getJoiningdate() == null ? "" : sessionHandlerImplObj.getDateFormatter(request).format(allapps.getJoiningdate()))); tmpObj.put("status", allapps.getStatus()); tmpObj.put("jobDetails", allapps.getPosition().getDetails()); if (allapps.getConfigjobapplicant() != null) { tmpObj.put("apcntid", allapps.getConfigjobapplicant().getId()); tmpObj.put("cname", allapps.getConfigjobapplicant().getCol1() + " " + allapps.getConfigjobapplicant().getCol2()); tmpObj.put("email", allapps.getConfigjobapplicant().getCol3()); tmpObj.put("fname", allapps.getConfigjobapplicant().getCol1()); tmpObj.put("lname", allapps.getConfigjobapplicant().getCol2()); tmpObj.put("contact", allapps.getConfigjobapplicant().getCol4() != null ? allapps.getConfigjobapplicant().getCol4() : ""); tmpObj.put("addr", allapps.getConfigjobapplicant().getCol6() != null ? allapps.getConfigjobapplicant().getCol6() : ""); tmpObj.put("employeetype", 0); if (!StringUtil.isNullOrEmpty(allapps.getConfigjobapplicant().getCol5())) { tmpObj.put("docid", allapps.getConfigjobapplicant().getCol5()); } // getdocsbyuser(request,allapps.getConfigjobapplicant().getId(),tmpObj); } else { tmpObj.put("apcntid", allapps.getEmployee().getUserID()); tmpObj.put("cname", allapps.getEmployee().getFirstName() + " " + allapps.getEmployee().getLastName()); tmpObj.put("email", allapps.getEmployee().getEmailID()); tmpObj.put("fname", allapps.getEmployee().getFirstName()); tmpObj.put("lname", allapps.getEmployee().getLastName()); tmpObj.put("contact", allapps.getEmployee().getContactNumber()); tmpObj.put("addr", allapps.getEmployee().getAddress()); tmpObj.put("employeetype", 1); } ArrayList recruiterparams = new ArrayList(); recruiterparams.add(allapps.getId()); ArrayList filter_names = new ArrayList(); filter_names.add("allapplication.id"); requestParams.clear(); requestParams.put("filter_names", filter_names); requestParams.put("filter_values", recruiterparams); recruitresult = hrmsRecJobDAOObj.getRecruiters(requestParams); if (StringUtil.checkResultobjList(recruitresult)) { List recruiterlist = recruitresult.getEntityList(); for (int k = 0; k < recruiterlist.size(); k++) { Recruiter r = (Recruiter) recruiterlist.get(k); tmpObj.append("recruiter", r.getRecruit().getFirstName() + " " + r.getRecruit().getLastName()); } } tmpObj.put("callback", (allapps.getCallback() == null ? "" : allapps.getCallback().getValue())); tmpObj.put("interviewplace", allapps.getInterviewplace()); tmpObj.put("interviewcomment", allapps.getInterviewcomment()); tmpObj.put("rank", (allapps.getRank() == null ? "" : allapps.getRank().getValue())); jarr.put(tmpObj); } jobj.put("data", jarr); jobj.put("count", count); jobj1.put("valid", true); jobj1.put("data", jobj.toString()); } catch (Exception e) { e.printStackTrace(); } finally { return new ModelAndView("jsonView", "model", jobj1.toString()); } }
From source file:com.example.drugsformarinemammals.Dose_Information.java
public void show_dose(ArrayList<Dose_Data> dose, TableLayout dose_table, TableRow dose_data, String drug_name, String group_name, String animal_family, String animal_name, String animal_category, ArrayList<String> notes, ArrayList<String> references, ArrayList<Article_Reference> references_index) { String doseAmount;/*from ww w . j a va2s . co m*/ String dosePosology; String doseRoute; String doseBookReference; String doseArticleReference; for (int k = 0; k < dose.size(); k++) { if (k > 0) { dose_data = new TableRow(this); } doseAmount = dose.get(k).getAmount(); dosePosology = dose.get(k).getPosology(); doseRoute = dose.get(k).getRoute(); doseBookReference = dose.get(k).getBookReference(); doseArticleReference = dose.get(k).getArticleReference(); //Dose amount data TextView textView_animal_dose_amount = new TextView(this); textView_animal_dose_amount.setText(doseAmount); textView_animal_dose_amount.setSingleLine(false); textView_animal_dose_amount.setTextColor(Color.BLACK); textView_animal_dose_amount.setTextSize(15); textView_animal_dose_amount.setTypeface(Typeface.SANS_SERIF); TableRow.LayoutParams paramsDoseAmount = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT); paramsDoseAmount.gravity = Gravity.CENTER; dose_data.addView(textView_animal_dose_amount, paramsDoseAmount); //Dose posology data TextView textView_animal_dose_posology = new TextView(this); textView_animal_dose_posology.setText(dosePosology); textView_animal_dose_posology.setSingleLine(false); textView_animal_dose_posology.setTextColor(Color.BLACK); textView_animal_dose_posology.setTextSize(15); textView_animal_dose_posology.setTypeface(Typeface.SANS_SERIF); TableRow.LayoutParams paramsDosePosology = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT); paramsDosePosology.gravity = Gravity.CENTER; if ((screenWidth < 600 && !isCollapsed(drug_name, group_name, animal_family, "Posology")) || screenWidth >= 600) dose_data.addView(textView_animal_dose_posology, paramsDosePosology); //Dose route data TextView textView_animal_dose_route = new TextView(this); textView_animal_dose_route.setText(doseRoute); textView_animal_dose_route.setSingleLine(false); textView_animal_dose_route.setTextColor(Color.BLACK); textView_animal_dose_route.setTextSize(15); textView_animal_dose_route.setTypeface(Typeface.SANS_SERIF); if (screenWidth >= 600) { TableRow.LayoutParams paramsDoseRoute = new TableRow.LayoutParams( TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT); paramsDoseRoute.gravity = Gravity.CENTER; dose_data.addView(textView_animal_dose_route, paramsDoseRoute); } else { TableRow.LayoutParams paramsDoseRoute = new TableRow.LayoutParams(30, TableRow.LayoutParams.WRAP_CONTENT); paramsDoseRoute.gravity = Gravity.CENTER; dose_data.addView(textView_animal_dose_route, paramsDoseRoute); } //Dose reference data TextView textView_animal_dose_reference = new TextView(this); if (!doseBookReference.equals("")) textView_animal_dose_reference.setText(doseBookReference); else if (!doseArticleReference.equals("")) { if (!references.contains(doseArticleReference)) { references.add(references.size(), doseArticleReference); Article_Reference article_reference = new Article_Reference(reference_index, doseArticleReference); references_index.add(references_index.size(), article_reference); reference_index++; } int article_index = references.indexOf(doseArticleReference); textView_animal_dose_reference.setText("(" + references_index.get(article_index).getIndex() + ")"); } textView_animal_dose_reference.setSingleLine(false); textView_animal_dose_reference.setTextColor(Color.BLACK); textView_animal_dose_reference.setTextSize(15); textView_animal_dose_reference.setTypeface(Typeface.SANS_SERIF); if (screenWidth >= 600) { TableRow.LayoutParams paramsDoseReference = new TableRow.LayoutParams( TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT); paramsDoseReference.gravity = Gravity.CENTER; dose_data.addView(textView_animal_dose_reference, paramsDoseReference); } else { TableRow.LayoutParams paramsDoseReference = new TableRow.LayoutParams(150, TableRow.LayoutParams.WRAP_CONTENT); paramsDoseReference.gravity = Gravity.CENTER; dose_data.addView(textView_animal_dose_reference, paramsDoseReference); } //Specific note index ArrayList<String> specific_notes = new ArrayList<String>(); specific_notes = helper.read_specific_notes(drug_name, group_name, animal_name, animal_family, animal_category, doseAmount, dosePosology, doseRoute, doseBookReference, doseArticleReference); String index = ""; for (int m = 0; m < specific_notes.size(); m++) { String note = specific_notes.get(m); if (!notes.contains(note)) { notes.add(notes.size(), note); } index += "(" + (notes.indexOf(note) + 1) + ") "; } TextView textView_specific_note_index = new TextView(this); textView_specific_note_index.setText(index); textView_specific_note_index.setSingleLine(false); textView_specific_note_index.setTextColor(Color.BLACK); textView_specific_note_index.setTextSize(15); textView_specific_note_index.setTypeface(Typeface.SANS_SERIF); if (screenWidth >= 600 && screenWidth < 720) { TableRow.LayoutParams paramsSpecificNoteIndex = new TableRow.LayoutParams(150, TableRow.LayoutParams.WRAP_CONTENT); paramsSpecificNoteIndex.gravity = Gravity.CENTER; dose_data.addView(textView_specific_note_index, paramsSpecificNoteIndex); } else if (screenWidth >= 720) { TableRow.LayoutParams paramsSpecificNoteIndex = new TableRow.LayoutParams( TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT); paramsSpecificNoteIndex.gravity = Gravity.CENTER; dose_data.addView(textView_specific_note_index, paramsSpecificNoteIndex); } else { TableRow.LayoutParams paramsSpecificNoteIndex = new TableRow.LayoutParams(100, TableRow.LayoutParams.WRAP_CONTENT); paramsSpecificNoteIndex.gravity = Gravity.CENTER; if ((screenWidth < 600 && !isCollapsed(drug_name, group_name, animal_family, "Note")) || screenWidth >= 600) dose_data.addView(textView_specific_note_index, paramsSpecificNoteIndex); } dose_table.addView(dose_data); } }
From source file:be.ibridge.kettle.trans.TransMeta.java
/** * Gives you an ArrayList of all the steps that are at least used in one active hop. These steps will be used to * execute the transformation. The others will not be executed. */*from ww w. ja va 2s.c o m*/ * @param all Set to true if you want to get ALL the steps from the transformation. * @return A ArrayList of steps */ public ArrayList getTransHopSteps(boolean all) { ArrayList st = new ArrayList(); int idx; for (int x = 0; x < nrTransHops(); x++) { TransHopMeta hi = getTransHop(x); if (hi.isEnabled() || all) { idx = st.indexOf(hi.getFromStep()); // FROM if (idx < 0) st.add(hi.getFromStep()); idx = st.indexOf(hi.getToStep()); // TO if (idx < 0) st.add(hi.getToStep()); } } // Also, add the steps that need to be painted, but are not part of a hop for (int x = 0; x < nrSteps(); x++) { StepMeta stepMeta = getStep(x); if (stepMeta.isDrawn() && !isStepUsedInTransHops(stepMeta)) { st.add(stepMeta); } } return st; }
From source file:com.chen.mail.browse.SendersView.java
public static void handlePriority(Context context, int maxChars, String messageInfoString, ConversationInfo conversationInfo, ArrayList<SpannableString> styledSenders, ArrayList<String> displayableSenderNames, ArrayList<String> displayableSenderEmails, String account, final TextAppearanceSpan unreadStyleSpan, final CharacterStyle readStyleSpan) { boolean shouldAddPhotos = displayableSenderEmails != null; int maxPriorityToInclude = -1; // inclusive int numCharsUsed = messageInfoString.length(); // draft, number drafts, // count int numSendersUsed = 0; int numCharsToRemovePerWord = 0; int maxFoundPriority = 0; if (numCharsUsed > maxChars) { numCharsToRemovePerWord = numCharsUsed - maxChars; }//from w w w . j av a2 s . c o m final Map<Integer, Integer> priorityToLength = PRIORITY_LENGTH_MAP_CACHE.get(); try { priorityToLength.clear(); int senderLength; for (MessageInfo info : conversationInfo.messageInfos) { senderLength = !TextUtils.isEmpty(info.sender) ? info.sender.length() : 0; priorityToLength.put(info.priority, senderLength); maxFoundPriority = Math.max(maxFoundPriority, info.priority); } while (maxPriorityToInclude < maxFoundPriority) { if (priorityToLength.containsKey(maxPriorityToInclude + 1)) { int length = numCharsUsed + priorityToLength.get(maxPriorityToInclude + 1); if (numCharsUsed > 0) length += 2; // We must show at least two senders if they exist. If we don't // have space for both // then we will truncate names. if (length > maxChars && numSendersUsed >= 2) { break; } numCharsUsed = length; numSendersUsed++; } maxPriorityToInclude++; } } finally { PRIORITY_LENGTH_MAP_CACHE.release(priorityToLength); } // We want to include this entry if // 1) The onlyShowUnread flags is not set // 2) The above flag is set, and the message is unread MessageInfo currentMessage; SpannableString spannableDisplay; String nameString; CharacterStyle style; boolean appendedElided = false; Map<String, Integer> displayHash = Maps.newHashMap(); String firstDisplayableSenderEmail = null; String firstDisplayableSender = null; for (int i = 0; i < conversationInfo.messageInfos.size(); i++) { currentMessage = conversationInfo.messageInfos.get(i); nameString = !TextUtils.isEmpty(currentMessage.sender) ? currentMessage.sender : ""; if (nameString.length() == 0) { nameString = getMe(context); } if (numCharsToRemovePerWord != 0) { nameString = nameString.substring(0, Math.max(nameString.length() - numCharsToRemovePerWord, 0)); } final int priority = currentMessage.priority; style = !currentMessage.read ? getWrappedStyleSpan(unreadStyleSpan) : getWrappedStyleSpan(readStyleSpan); if (priority <= maxPriorityToInclude) { spannableDisplay = new SpannableString(sBidiFormatter.unicodeWrap(nameString)); // Don't duplicate senders; leave the first instance, unless the // current instance is also unread. int oldPos = displayHash.containsKey(currentMessage.sender) ? displayHash.get(currentMessage.sender) : DOES_NOT_EXIST; // If this sender doesn't exist OR the current message is // unread, add the sender. if (oldPos == DOES_NOT_EXIST || !currentMessage.read) { // If the sender entry already existed, and is right next to the // current sender, remove the old entry. if (oldPos != DOES_NOT_EXIST && i > 0 && oldPos == i - 1 && oldPos < styledSenders.size()) { // Remove the old one! styledSenders.set(oldPos, null); if (shouldAddPhotos && !TextUtils.isEmpty(currentMessage.senderEmail)) { displayableSenderEmails.remove(currentMessage.senderEmail); displayableSenderNames.remove(currentMessage.sender); } } displayHash.put(currentMessage.sender, i); spannableDisplay.setSpan(style, 0, spannableDisplay.length(), 0); styledSenders.add(spannableDisplay); } } else { if (!appendedElided) { spannableDisplay = new SpannableString(sElidedString); spannableDisplay.setSpan(style, 0, spannableDisplay.length(), 0); appendedElided = true; styledSenders.add(spannableDisplay); } } if (shouldAddPhotos) { String senderEmail = TextUtils.isEmpty(currentMessage.sender) ? account : TextUtils.isEmpty(currentMessage.senderEmail) ? currentMessage.sender : currentMessage.senderEmail; if (i == 0) { // Always add the first sender! firstDisplayableSenderEmail = senderEmail; firstDisplayableSender = currentMessage.sender; } else { if (!Objects.equal(firstDisplayableSenderEmail, senderEmail)) { int indexOf = displayableSenderEmails.indexOf(senderEmail); if (indexOf > -1) { displayableSenderEmails.remove(indexOf); displayableSenderNames.remove(indexOf); } displayableSenderEmails.add(senderEmail); displayableSenderNames.add(currentMessage.sender); if (displayableSenderEmails.size() > DividedImageCanvas.MAX_DIVISIONS) { displayableSenderEmails.remove(0); displayableSenderNames.remove(0); } } } } } if (shouldAddPhotos && !TextUtils.isEmpty(firstDisplayableSenderEmail)) { if (displayableSenderEmails.size() < DividedImageCanvas.MAX_DIVISIONS) { displayableSenderEmails.add(0, firstDisplayableSenderEmail); displayableSenderNames.add(0, firstDisplayableSender); } else { displayableSenderEmails.set(0, firstDisplayableSenderEmail); displayableSenderNames.set(0, firstDisplayableSender); } } }
From source file:com.tct.mail.browse.SendersView.java
private static void handlePriority(int maxChars, String messageInfoString, ConversationInfo conversationInfo, ArrayList<SpannableString> styledSenders, ArrayList<String> displayableSenderNames, ArrayList<String> displayableSenderEmails, String account, final TextAppearanceSpan unreadStyleSpan, final CharacterStyle readStyleSpan, final boolean showToHeader) { boolean shouldAddPhotos = displayableSenderEmails != null; int maxPriorityToInclude = -1; // inclusive int numCharsUsed = messageInfoString.length(); // draft, number drafts, // count int numSendersUsed = 0; int numCharsToRemovePerWord = 0; int maxFoundPriority = 0; if (numCharsUsed > maxChars) { numCharsToRemovePerWord = numCharsUsed - maxChars; }//from w w w . j a v a 2 s .c o m final Map<Integer, Integer> priorityToLength = PRIORITY_LENGTH_MAP_CACHE.get(); try { priorityToLength.clear(); int senderLength; for (ParticipantInfo info : conversationInfo.participantInfos) { final String senderName = info.name; senderLength = !TextUtils.isEmpty(senderName) ? senderName.length() : 0; priorityToLength.put(info.priority, senderLength); maxFoundPriority = Math.max(maxFoundPriority, info.priority); } while (maxPriorityToInclude < maxFoundPriority) { if (priorityToLength.containsKey(maxPriorityToInclude + 1)) { int length = numCharsUsed + priorityToLength.get(maxPriorityToInclude + 1); if (numCharsUsed > 0) length += 2; // We must show at least two senders if they exist. If we don't // have space for both // then we will truncate names. if (length > maxChars && numSendersUsed >= 2) { break; } numCharsUsed = length; numSendersUsed++; } maxPriorityToInclude++; } } finally { PRIORITY_LENGTH_MAP_CACHE.release(priorityToLength); } // We want to include this entry if // 1) The onlyShowUnread flags is not set // 2) The above flag is set, and the message is unread ParticipantInfo currentParticipant; SpannableString spannableDisplay; CharacterStyle style; boolean appendedElided = false; Map<String, Integer> displayHash = Maps.newHashMap(); String firstDisplayableSenderEmail = null; String firstDisplayableSender = null; for (int i = 0; i < conversationInfo.participantInfos.size(); i++) { currentParticipant = conversationInfo.participantInfos.get(i); final String currentEmail = currentParticipant.email; final String currentName = currentParticipant.name; String nameString = !TextUtils.isEmpty(currentName) ? currentName : ""; if (nameString.length() == 0) { // if we're showing the To: header, show the object version of me. nameString = getMe(showToHeader /* useObjectMe */); } if (numCharsToRemovePerWord != 0) { nameString = nameString.substring(0, Math.max(nameString.length() - numCharsToRemovePerWord, 0)); } final int priority = currentParticipant.priority; style = CharacterStyle.wrap(currentParticipant.readConversation ? readStyleSpan : unreadStyleSpan); if (priority <= maxPriorityToInclude) { spannableDisplay = new SpannableString(sBidiFormatter.unicodeWrap(nameString)); // Don't duplicate senders; leave the first instance, unless the // current instance is also unread. int oldPos = displayHash.containsKey(currentName) ? displayHash.get(currentName) : DOES_NOT_EXIST; // If this sender doesn't exist OR the current message is // unread, add the sender. if (oldPos == DOES_NOT_EXIST || !currentParticipant.readConversation) { // If the sender entry already existed, and is right next to the // current sender, remove the old entry. if (oldPos != DOES_NOT_EXIST && i > 0 && oldPos == i - 1 && oldPos < styledSenders.size()) { // Remove the old one! styledSenders.set(oldPos, null); if (shouldAddPhotos && !TextUtils.isEmpty(currentEmail)) { displayableSenderEmails.remove(currentEmail); displayableSenderNames.remove(currentName); } } displayHash.put(currentName, i); spannableDisplay.setSpan(style, 0, spannableDisplay.length(), 0); styledSenders.add(spannableDisplay); } } else { if (!appendedElided) { spannableDisplay = new SpannableString(sElidedString); spannableDisplay.setSpan(style, 0, spannableDisplay.length(), 0); appendedElided = true; styledSenders.add(spannableDisplay); } } if (shouldAddPhotos) { String senderEmail = TextUtils.isEmpty(currentName) ? account : TextUtils.isEmpty(currentEmail) ? currentName : currentEmail; if (i == 0) { // Always add the first sender! firstDisplayableSenderEmail = senderEmail; firstDisplayableSender = currentName; } else { if (!Objects.equal(firstDisplayableSenderEmail, senderEmail)) { int indexOf = displayableSenderEmails.indexOf(senderEmail); if (indexOf > -1) { displayableSenderEmails.remove(indexOf); displayableSenderNames.remove(indexOf); } displayableSenderEmails.add(senderEmail); displayableSenderNames.add(currentName); if (displayableSenderEmails.size() > DividedImageCanvas.MAX_DIVISIONS) { displayableSenderEmails.remove(0); displayableSenderNames.remove(0); } } } } } if (shouldAddPhotos && !TextUtils.isEmpty(firstDisplayableSenderEmail)) { if (displayableSenderEmails.size() < DividedImageCanvas.MAX_DIVISIONS) { displayableSenderEmails.add(0, firstDisplayableSenderEmail); displayableSenderNames.add(0, firstDisplayableSender); } else { displayableSenderEmails.set(0, firstDisplayableSenderEmail); displayableSenderNames.set(0, firstDisplayableSender); } } }
From source file:org.openanzo.jdbc.container.query.AnzoBGPQuery.java
/** * Get the SQL string for this query for the extra triple patterns. This joins the results from the getSQL() statement, if any, and the results from the * extra triple patterns. If there are any optional query patterns, outer joins are added to merge those results in as well. * /*w w w . j a v a 2 s . co m*/ * @return the SQL string for this query * @throws NoSolutionsException * @throws AnzoException */ public String getExtraSQL() throws NoSolutionsException, AnzoException { int namedGraphVariableTemporaryColumn = this.selectedBindables.indexOf(namedGraphVariable); // what concrete columns (w/ aliases) will go in our SELECT clause? ArrayList<String> selectedColumns = new ArrayList<String>(); // what bindables did we already select for into our temp table? ArrayList<Bindable> tempTableBindables = new ArrayList<Bindable>(this.selectedBindables); // Copy columns from the temp table to our result columns list, and stick the proper // column name for them in selectedColumns - take any columns that we don't need after // this query and skip them int c = 0; for (Bindable b : tempTableBindables) { if (isUsedOutsideOfQuery(b) || isOptionalBindable(b) || needsUnusedVariables()) { selectedColumns.add(this.temporaryTable + ".C" + c + " AS \"" + bindable2alias(b) + "\""); } else { this.selectedBindables.remove(b); } c++; } populateSelectedColumnsFromMap(selectedColumns, variableColumnsExtra, new Predicate<Bindable>() { public boolean satisfies(Bindable b) { return isUsedOutsideOfQuery(b) || needsUnusedVariables(); } }); ArrayList<String> tables = new ArrayList<String>(); if (populateSelectedColumnsWithUnit(selectedColumns)) { tables.add(SQLQueryConstants.glitterUnitTable); } String graphsTableName = null; if (extraTriples.size() > 0 && namedGraphVariable != null && !this.selectedBindables.contains(namedGraphVariable) && (isUsedOutsideOfQuery(namedGraphVariable) || isOptionalBindable(namedGraphVariable) || needsUnusedVariables())) { //Again do the check to determine if a dataset graph table is being used, or to use first triple patterns namedgraphid if (!useDefaultDataset() && (!bypassAcls() && getNamedGraphsType() == GraphSetType.LISTED)) { graphsTableName = datasetTableAlias + ".ID"; } else { TripleInstance ti = extraTriples.get(0); graphsTableName = ti.tripleTableAlias + ".NAMEDGRAPHID"; } selectedColumns.add(graphsTableName + " AS \"" + bindable2alias(namedGraphVariable) + "\""); // 4) } ////////////////////////////////////////////////////////////// // FROM clause // if (this.temporaryTable != null) tables.add(this.temporaryTable); // we need the dataset table if we didn't already select for the named graph variable in our original // query if (extraTriples.size() > 0 && !useDefaultDataset() && namedGraphVariableTemporaryColumn == -1) { //Don't add the dataset table to tables if it isn't beind used if (!bypassAcls() || getNamedGraphsType() == GraphSetType.LISTED) { tables.add(getNamedGraphsTable() + " " + datasetTableAlias); } } for (TripleInstance ti : extraTriples) tables.add(ti.getFrom()); ////////////////////////////////////////////////////////////// // WHERE clause // ArrayList<String> clauses = new ArrayList<String>(); // We need to constrain triples either by the namedgraph table or by the already bound // named graphs coming from the temporary table populateConstraintsFromTriples(clauses, extraTriples, namedGraphVariableTemporaryColumn > -1 ? this.temporaryTable + ".C" + namedGraphVariableTemporaryColumn : null); if (extraTriples.size() > 0 && namedGraphVariableTemporaryColumn == -1 && (!useDefaultDataset() && (!bypassAcls() && getNamedGraphsType() == GraphSetType.LISTED)) && namedGraphVariable != null && variableColumnsExtra.containsKey(namedGraphVariable)) variableColumnsExtra.get(namedGraphVariable).add(datasetTableAlias + ".ID"); populateConstraintsFromMap(clauses, variableColumnsExtra); populateFilterConstraintsFromMap(clauses, variableColumnsExtra); if (!populateRequiredBindings(clauses, variableColumnsExtra)) { //A required value is not in the db, so can never be true return null; } // make sure that any variabels in both the extra triples and regular triples are constrained to match for (Entry<Bindable, List<String>> e : variableColumnsExtra.entrySet()) { int col = tempTableBindables.indexOf(e.getKey()); if (col > -1) { clauses.add(this.temporaryTable + ".C" + col + "=" + e.getValue().get(0)); } } // put it all together String sql = getSQLString(selectDistinct(), selectedColumns, tables, clauses, getQueryHint(this.temporaryTable)); if (variableColumnsOptional.size() > 0) { for (int depth = 0; depth < this.optionalTriples.size(); depth++) { try { String oldSql = sql; sql = getOuterJoinSQL(sql, depth); if (sql == null) { sql = oldSql; } } catch (NoSolutionsException nse) { log.trace(LogUtils.DATASOURCE_MARKER, "No solutions found for right-hand side of OPTIONAL. Nothing to see here, move along."); } } return sql; } else { return sql; } }
From source file:org.silverpeas.core.admin.service.Admin.java
private ArrayList<String> removeTuples(ArrayList<String> al) { if (al == null) { return new ArrayList<>(); }//from ww w. j a va 2 s. c o m for (int nI = 0; nI < al.size(); nI++) { while (al.lastIndexOf(al.get(nI)) != al.indexOf(al.get(nI))) { al.remove(al.lastIndexOf(al.get(nI))); } } return al; }
From source file:fr.cirad.mgdb.exporting.markeroriented.HapMapExportHandler.java
@Override public void exportData(OutputStream outputStream, String sModule, List<SampleId> sampleIDs, ProgressIndicator progress, DBCursor markerCursor, Map<Comparable, Comparable> markerSynonyms, int nMinimumGenotypeQuality, int nMinimumReadDepth, Map<String, InputStream> readyToExportFiles) throws Exception { MongoTemplate mongoTemplate = MongoTemplateManager.get(sModule); File warningFile = File.createTempFile("export_warnings_", ""); FileWriter warningFileWriter = new FileWriter(warningFile); int markerCount = markerCursor.count(); ZipOutputStream zos = new ZipOutputStream(outputStream); if (readyToExportFiles != null) for (String readyToExportFile : readyToExportFiles.keySet()) { zos.putNextEntry(new ZipEntry(readyToExportFile)); InputStream inputStream = readyToExportFiles.get(readyToExportFile); byte[] dataBlock = new byte[1024]; int count = inputStream.read(dataBlock, 0, 1024); while (count != -1) { zos.write(dataBlock, 0, count); count = inputStream.read(dataBlock, 0, 1024); }/*from w w w . j a v a 2 s . c o m*/ } List<Individual> individuals = getIndividualsFromSamples(sModule, sampleIDs); ArrayList<String> individualList = new ArrayList<String>(); for (int i = 0; i < sampleIDs.size(); i++) { Individual individual = individuals.get(i); if (!individualList.contains(individual.getId())) { individualList.add(individual.getId()); } } String exportName = sModule + "_" + markerCount + "variants_" + individualList.size() + "individuals"; zos.putNextEntry(new ZipEntry(exportName + ".hapmap")); String header = "rs#" + "\t" + "alleles" + "\t" + "chrom" + "\t" + "pos" + "\t" + "strand" + "\t" + "assembly#" + "\t" + "center" + "\t" + "protLSID" + "\t" + "assayLSID" + "\t" + "panelLSID" + "\t" + "QCcode"; zos.write(header.getBytes()); for (int i = 0; i < individualList.size(); i++) { zos.write(("\t" + individualList.get(i)).getBytes()); } zos.write((LINE_SEPARATOR).getBytes()); int avgObjSize = (Integer) mongoTemplate .getCollection(mongoTemplate.getCollectionName(VariantRunData.class)).getStats().get("avgObjSize"); int nChunkSize = nMaxChunkSizeInMb * 1024 * 1024 / avgObjSize; short nProgress = 0, nPreviousProgress = 0; long nLoadedMarkerCount = 0; while (markerCursor == null || markerCursor.hasNext()) { int nLoadedMarkerCountInLoop = 0; Map<Comparable, String> markerChromosomalPositions = new LinkedHashMap<Comparable, String>(); boolean fStartingNewChunk = true; markerCursor.batchSize(nChunkSize); while (markerCursor.hasNext() && (fStartingNewChunk || nLoadedMarkerCountInLoop % nChunkSize != 0)) { DBObject exportVariant = markerCursor.next(); DBObject refPos = (DBObject) exportVariant.get(VariantData.FIELDNAME_REFERENCE_POSITION); markerChromosomalPositions.put((Comparable) exportVariant.get("_id"), refPos.get(ReferencePosition.FIELDNAME_SEQUENCE) + ":" + refPos.get(ReferencePosition.FIELDNAME_START_SITE)); nLoadedMarkerCountInLoop++; fStartingNewChunk = false; } List<Comparable> currentMarkers = new ArrayList<Comparable>(markerChromosomalPositions.keySet()); LinkedHashMap<VariantData, Collection<VariantRunData>> variantsAndRuns = MgdbDao.getSampleGenotypes( mongoTemplate, sampleIDs, currentMarkers, true, null /*new Sort(VariantData.FIELDNAME_REFERENCE_POSITION + "." + ChromosomalPosition.FIELDNAME_SEQUENCE).and(new Sort(VariantData.FIELDNAME_REFERENCE_POSITION + "." + ChromosomalPosition.FIELDNAME_START_SITE))*/); // query mongo db for matching genotypes for (VariantData variant : variantsAndRuns.keySet()) // read data and write results into temporary files (one per sample) { Comparable variantId = variant.getId(); if (markerSynonyms != null) { Comparable syn = markerSynonyms.get(variantId); if (syn != null) variantId = syn; } boolean fIsSNP = variant.getType().equals(Type.SNP.toString()); byte[] missingGenotype = ("\t" + "NN").getBytes(); String[] chromAndPos = markerChromosomalPositions.get(variant.getId()).split(":"); zos.write(((variantId == null ? variant.getId() : variantId) + "\t" + StringUtils.join(variant.getKnownAlleleList(), "/") + "\t" + chromAndPos[0] + "\t" + Long.parseLong(chromAndPos[1]) + "\t" + "+").getBytes()); for (int j = 0; j < 6; j++) zos.write(("\t" + "NA").getBytes()); Map<String, Integer> gqValueForSampleId = new LinkedHashMap<String, Integer>(); Map<String, Integer> dpValueForSampleId = new LinkedHashMap<String, Integer>(); Map<String, List<String>> individualGenotypes = new LinkedHashMap<String, List<String>>(); Collection<VariantRunData> runs = variantsAndRuns.get(variant); if (runs != null) for (VariantRunData run : runs) for (Integer sampleIndex : run.getSampleGenotypes().keySet()) { SampleGenotype sampleGenotype = run.getSampleGenotypes().get(sampleIndex); String gtCode = run.getSampleGenotypes().get(sampleIndex).getCode(); String individualId = individuals .get(sampleIDs.indexOf(new SampleId(run.getId().getProjectId(), sampleIndex))) .getId(); List<String> storedIndividualGenotypes = individualGenotypes.get(individualId); if (storedIndividualGenotypes == null) { storedIndividualGenotypes = new ArrayList<String>(); individualGenotypes.put(individualId, storedIndividualGenotypes); } storedIndividualGenotypes.add(gtCode); gqValueForSampleId.put(individualId, (Integer) sampleGenotype.getAdditionalInfo().get(VariantData.GT_FIELD_GQ)); dpValueForSampleId.put(individualId, (Integer) sampleGenotype.getAdditionalInfo().get(VariantData.GT_FIELD_DP)); } int writtenGenotypeCount = 0; for (String individualId : individualList /* we use this list because it has the proper ordering */) { int individualIndex = individualList.indexOf(individualId); while (writtenGenotypeCount < individualIndex - 1) { zos.write(missingGenotype); writtenGenotypeCount++; } List<String> genotypes = individualGenotypes.get(individualId); HashMap<Object, Integer> genotypeCounts = new HashMap<Object, Integer>(); // will help us to keep track of missing genotypes int highestGenotypeCount = 0; String mostFrequentGenotype = null; if (genotypes != null) for (String genotype : genotypes) { if (genotype.length() == 0) continue; /* skip missing genotypes */ Integer gqValue = gqValueForSampleId.get(individualId); if (gqValue != null && gqValue < nMinimumGenotypeQuality) continue; /* skip this sample because its GQ is under the threshold */ Integer dpValue = dpValueForSampleId.get(individualId); if (dpValue != null && dpValue < nMinimumReadDepth) continue; /* skip this sample because its DP is under the threshold */ int gtCount = 1 + MgdbDao.getCountForKey(genotypeCounts, genotype); if (gtCount > highestGenotypeCount) { highestGenotypeCount = gtCount; mostFrequentGenotype = genotype; } genotypeCounts.put(genotype, gtCount); } byte[] exportedGT = mostFrequentGenotype == null ? missingGenotype : ("\t" + StringUtils.join(variant.getAllelesFromGenotypeCode(mostFrequentGenotype), fIsSNP ? "" : "/")).getBytes(); zos.write(exportedGT); writtenGenotypeCount++; if (genotypeCounts.size() > 1) warningFileWriter.write("- Dissimilar genotypes found for variant " + (variantId == null ? variant.getId() : variantId) + ", individual " + individualId + ". Exporting most frequent: " + new String(exportedGT) + "\n"); } while (writtenGenotypeCount < individualList.size()) { zos.write(missingGenotype); writtenGenotypeCount++; } zos.write((LINE_SEPARATOR).getBytes()); } if (progress.hasAborted()) return; nLoadedMarkerCount += nLoadedMarkerCountInLoop; nProgress = (short) (nLoadedMarkerCount * 100 / markerCount); if (nProgress > nPreviousProgress) { // if (nProgress%5 == 0) // LOG.info("========================= exportData: " + nProgress + "% =========================" + (System.currentTimeMillis() - before)/1000 + "s"); progress.setCurrentStepProgress(nProgress); nPreviousProgress = nProgress; } } warningFileWriter.close(); if (warningFile.length() > 0) { zos.putNextEntry(new ZipEntry(exportName + "-REMARKS.txt")); int nWarningCount = 0; BufferedReader in = new BufferedReader(new FileReader(warningFile)); String sLine; while ((sLine = in.readLine()) != null) { zos.write((sLine + "\n").getBytes()); in.readLine(); nWarningCount++; } LOG.info("Number of Warnings for export (" + exportName + "): " + nWarningCount); in.close(); } warningFile.delete(); zos.close(); progress.setCurrentStepProgress((short) 100); }
From source file:cloudproject.test.GetContainerInfo.java
/** * Parse information from a file, and also optionally print information about what * formats, containers and codecs fit into that file. * //from w w w. ja va2 s . c o m * @param arg The file to open, or null if we just want generic options. * @throws IOException if file cannot be opened. * @throws InterruptedException if process is interrupted while querying. */ private static void getInfo(String filename) throws InterruptedException, IOException { // In Humble, all objects have special contructors named 'make'. // A Demuxer opens up media containers, parses and de-multiplexes the streams // of media data without those containers. final Demuxer demuxer = Demuxer.make(); // We open the demuxer by pointing it at a URL. demuxer.open(filename, null, false, true, null, null); // Once we've opened a demuxer, Humble can make a guess about the // DemuxerFormat. Humble supports over 100+ media container formats. final DemuxerFormat format = demuxer.getFormat(); System.out.printf("URL: '%s' (%s: %s)\n", demuxer.getURL(), format.getLongName(), format.getName()); // Many programs that make containers, such as iMovie or Adobe Elements, will // insert meta-data about the container. Here we extract that meta data and print it. KeyValueBag metadata = demuxer.getMetaData(); System.out.println("MetaData:"); for (String key : metadata.getKeys()) System.out.printf(" %s: %s\n", key, metadata.getValue(key)); System.out.println("\n"); // There are a few other key pieces of information that are interesting for // most containers; The duration, the starting time, and the estimated bit-rate. // This code extracts all three. final String formattedDuration = formatTimeStamp(demuxer.getDuration()); System.out.printf("Duration: %s, start: %f, bitrate: %d kb/s\n", formattedDuration, demuxer.getStartTime() == Global.NO_PTS ? 0 : demuxer.getStartTime() / 1000000.0, demuxer.getBitRate() / 1000); System.out.println("\n"); String output = "/Users/lxb200709/Documents/TransCloud/videosource/elephants dream_00_cv.WebM"; // we're forcing this to be HTTP Live Streaming for this demo. final Muxer muxer = Muxer.make(output, null, "mp4"); //final MuxerFormat format_muxer = MuxerFormat.guessFormat("mp4", null, null); /** * Create bit stream filters if we are asked to. */ final BitStreamFilter vf = BitStreamFilter.make("dump_extra"); final BitStreamFilter af = BitStreamFilter.make("aac_adtstoasc"); // Finally, a container consists of several different independent streams of // data called Streams. In Humble there are two objects that represent streams: // DemuxerStream (when you are reading) and MuxerStreams (when you are writing). // First find the number of streams in this container. int ns = demuxer.getNumStreams(); final Decoder[] decoders = new Decoder[ns]; MediaPicture picture = null; MediaAudio samples = null; // Now, let's iterate through each of them. for (int i = 0; i < ns; i++) { DemuxerStream stream = demuxer.getStream(i); metadata = stream.getMetaData(); // Language is usually embedded as metadata in a stream. final String language = metadata.getValue("language"); // We will only be able to make a decoder for streams we can actually // decode, so the caller should check for null. decoders[i] = stream.getDecoder(); System.out.printf(" Stream #0.%1$d (%2$s): %3$s\n", i, language, decoders[i] != null ? decoders[i].toString() : "unknown coder"); System.out.println(" Metadata:"); for (String key : metadata.getKeys()) System.out.printf(" %s: %s\n", key, metadata.getValue(key)); if (decoders[i].getCodecType() == Type.MEDIA_VIDEO) { System.out.printf(" frame rate: %s\n", stream.getFrameRate()); System.out.printf(" frame number: %s\n", stream.getNumFrames()); System.out.printf(" stream tb: %s\n", stream.getTimeBase()); //Open the video decoder decoders[i].open(null, null); } if (decoders[i].getCodecType() == Type.MEDIA_AUDIO) { decoders[i].open(null, null); } System.out.println("\n"); muxer.addNewStream(decoders[i]); } muxer.open(null, null); final MediaPacket packet = MediaPacket.make(); ArrayList<MediaPicture> keyFrameList = new ArrayList<MediaPicture>(); ArrayList<MediaPicture> keyFrameListInOnePacket = new ArrayList<MediaPicture>(); ArrayList<String> frameList = new ArrayList<String>(); ArrayList<Long> gopDuration = new ArrayList<Long>(); long gopSize = 0; long previousKeyFramePosition = 0; long currentKeyFramePosition = 0; long gopPts = 0; long previousKeyFramePts = 0; long currentKeyFramePts = 0; long gopDts = 0; long previousKeyFrameDts = 0; long currentKeyFrameDts = 0; long gopPosition = 0; int packetCount = 0; while (demuxer.read(packet) >= 0) { /** * Now we have a packet, but we can only write packets that had decoders we knew what to do with. */ final Decoder d = decoders[packet.getStreamIndex()]; if (d != null && d.getCodecType() == Type.MEDIA_VIDEO) { packetCount++; System.out.println("\npacket number: " + packetCount); System.out.println("packet position: " + packet.getPosition()); System.out.println("packet duration: " + packet.getDuration()); System.out.println("packet size: " + packet.getSize()); System.out.println("packet dts: " + packet.getDts()); System.out.println("packet pts: " + packet.getPts()); System.out.println("this is a video packet"); picture = MediaPicture.make(d.getWidth(), d.getHeight(), d.getPixelFormat()); picture.setTimeBase(demuxer.getStream(packet.getStreamIndex()).getFrameRate()); int offset = 0; int bytesDecoded = 0; while (offset < packet.getSize()) { bytesDecoded += d.decode(picture, packet, offset); if (bytesDecoded < 0) throw new RuntimeException("got error decoding video"); offset += bytesDecoded; if (bytesDecoded >= 0) { if (picture.isComplete()) { if (picture.getType() == MediaPicture.Type.PICTURE_TYPE_I) { //Once a new GOP, create a new packet final MediaPacket packetGOP = MediaPacket.make(); keyFrameList.add(picture); keyFrameListInOnePacket.add(picture); System.out.println("A I frame is created"); frameList.add("I"); //Calculate GOP size I, the previous GOP size will current I frame position //minus previous I frame position. currentKeyFramePosition = packet.getPosition(); gopSize = currentKeyFramePosition - previousKeyFramePosition; gopPosition = previousKeyFramePosition; previousKeyFramePosition = currentKeyFramePosition; //Calculate GOP pts (deadline). It should the first frame in this GOP's pts, most time //is key frame. gopPts = previousKeyFramePts; currentKeyFramePts = packet.getPts(); previousKeyFramePts = currentKeyFramePts; gopDts = previousKeyFrameDts; currentKeyFrameDts = packet.getDts(); previousKeyFrameDts = currentKeyFrameDts; /*packetGOP.setKeyPacket(true); packetGOP.setTimeBase(packet.getTimeBase()); packetGOP.setDuration(gopDuration.size()); packetGOP.setPts(gopPts); packetGOP.setDts(gopDts); packetGOP.setPosition(gopPosition); // packetGOP.setComplete(true); gopDuration.clear(); if (vf != null && d.getCodecType() == Type.MEDIA_VIDEO) vf.filter(packetGOP, null); else if (af != null && d.getCodecType() == Type.MEDIA_AUDIO) af.filter(packetGOP, null); System.out.println("*******Writing packetGOP to muxer container*****");*/ muxer.write(packet, true); } if (picture.getType() == MediaPicture.Type.PICTURE_TYPE_P) { System.out.println("A P frame is created"); frameList.add("P"); } if (picture.getType() == MediaPicture.Type.PICTURE_TYPE_B) { System.out.println("A B frame is created"); frameList.add("B"); } } } } } /* if(d.getCodecType() == Type.MEDIA_AUDIO) { System.out.println("this is a audio packet"); samples = MediaAudio.make( d.getFrameSize(), d.getSampleRate(), d.getChannels(), d.getChannelLayout(), d.getSampleFormat()); int offset = 0; int bytesRead = 0; do { bytesRead += d.decodeAudio(samples, packet, offset); if (samples.isComplete()) { } offset += bytesRead; } while (offset < packet.getSize()); }*/ if (packet.isComplete() && d != null && d.getCodecType() == Type.MEDIA_VIDEO) { if (packet.isKeyPacket()) { System.out.println("This is a keypacket"); } //Calculate the total GOP duration gopDuration.add(packet.getDuration()); // System.out.printf("****Find %d I frames in this packet****", keyFrameListInOnePacket.size()); //System.out.println("\n"); for (MediaPicture pic : keyFrameListInOnePacket) { System.out.println( "\nI frame #" + keyFrameListInOnePacket.indexOf(pic) + " pts: " + pic.getPts()); } keyFrameListInOnePacket.clear(); System.out.println("\n"); // System.out.println(frameList); // System.out.println("\n"); } } for (int i = 0; i < ns; i++) { do { decoders[i].decode(picture, null, 0); if (picture.isComplete()) { } } while (picture.isComplete()); } // It is good practice to close demuxers when you're done to free // up file handles. Humble will EVENTUALLY detect if nothing else // references this demuxer and close it then, but get in the habit // of cleaning up after yourself, and your future girlfriend/boyfriend // will appreciate it. muxer.close(); demuxer.close(); }