List of usage examples for java.util Collections binarySearch
@SuppressWarnings("unchecked") public static <T> int binarySearch(List<? extends T> list, T key, Comparator<? super T> c)
From source file:com.moesol.geoserver.sync.client.AbstractClientSynchronizer.java
/** * Delete all the features we have with this prefix * This prefix is empty on the server.//w ww.j av a 2 s. co m * * @param position */ private void deleteInPosition(Sha1SyncPositionHash position) { Sha1Value prefix = new Sha1Value(position.position()); HashAndFeatureValue find = new HashAndFeatureValue(prefix, null, null); // TODO, hmm, better search? int i = Collections.binarySearch(m_featureSha1s, find, new IdAndValueSha1Comparator(versionFeatures)); if (i < 0) { i = -i - 1; } for (; i < m_featureSha1s.size(); i++) { HashAndFeatureValue value = m_featureSha1s.get(i); if (!versionFeatures.getBucketPrefixSha1(value).isPrefixMatch(prefix.get())) { break; } FeatureId fid = value.getFeature().getIdentifier(); m_potentialDeletes.add(fid); } }
From source file:org.psikeds.resolutionengine.datalayer.knowledgebase.util.FeatureValueHelper.java
public static int find(final List<FeatureValue> sortedList, final FeatureValue fv) { if ((fv == null) || (sortedList == null) || sortedList.isEmpty()) { return -1; }/* ww w. j a v a 2 s.c o m*/ // note: binary search requires sorted list. otherwise // method will not fail, however result is undefined! return Collections.binarySearch(sortedList, fv, COMPARATOR); }
From source file:com.liferay.portal.security.permission.AdvancedPermissionChecker.java
public boolean hasOwnerPermission(long companyId, String name, String primKey, long ownerId, String actionId) { if (ownerId != getUserId()) { return false; }//from w ww .j av a2 s. c o m if (ownerId == defaultUserId) { if (actionId.equals(ActionKeys.VIEW)) { return true; } else { return false; } } try { if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6) { if (ResourceBlockLocalServiceUtil.isSupported(name)) { PermissionedModel permissionedModel = ResourceBlockLocalServiceUtil.getPermissionedModel(name, GetterUtil.getLong(primKey)); long groupId = 0; if (permissionedModel instanceof GroupedModel) { GroupedModel groupedModel = (GroupedModel) permissionedModel; groupId = groupedModel.getGroupId(); } ResourceBlockIdsBag resourceBlockIdsBag = getOwnerResourceBlockIdsBag(companyId, groupId, name); return ResourceBlockLocalServiceUtil.hasPermission(name, permissionedModel, actionId, resourceBlockIdsBag); } return ResourcePermissionLocalServiceUtil.hasResourcePermission(companyId, name, ResourceConstants.SCOPE_INDIVIDUAL, primKey, getOwnerRoleId(), actionId); } ResourceActionsUtil.checkAction(name, actionId); Resource resource = ResourceLocalServiceUtil.getResource(companyId, name, ResourceConstants.SCOPE_INDIVIDUAL, primKey); List<Permission> permissions = PermissionLocalServiceUtil.getRolePermissions(getOwnerRoleId(), resource.getResourceId()); int pos = Collections.binarySearch(permissions, actionId, new PermissionActionIdComparator()); if (pos >= 0) { return true; } } catch (Exception e) { if (_log.isDebugEnabled()) { _log.debug(e, e); } } return false; }
From source file:org.fdroid.fdroid.privileged.views.AppSecurityPermissions.java
private void addPermToList(List<MyPermissionInfo> permList, MyPermissionInfo pInfo) { if (pInfo.label == null) { pInfo.label = pInfo.loadLabel(pm); }// w ww. ja v a 2 s . com int idx = Collections.binarySearch(permList, pInfo, permComparator); if (idx < 0) { idx = -idx - 1; permList.add(idx, pInfo); } }
From source file:oscar.oscarLab.ca.all.Hl7textResultsData.java
/** *Populates ArrayList with labs attached to a consultation request *//*from ww w.j ava 2s . c o m*/ public static ArrayList<LabResultData> populateHL7ResultsData(String demographicNo, String consultationId, boolean attached) { String sql = "SELECT hl7.label,hl7.lab_no, hl7.obr_date, hl7.discipline, hl7.accessionNum, hl7.final_result_count, patientLabRouting.id " + "FROM hl7TextInfo hl7, patientLabRouting " + "WHERE patientLabRouting.lab_no = hl7.lab_no " + "AND patientLabRouting.lab_type = 'HL7' AND patientLabRouting.demographic_no=" + demographicNo + " GROUP BY hl7.lab_no"; String attachQuery = "SELECT consultdocs.document_no FROM consultdocs, patientLabRouting " + "WHERE patientLabRouting.id = consultdocs.document_no AND " + "consultdocs.requestId = " + consultationId + " AND consultdocs.doctype = 'L' AND consultdocs.deleted IS NULL ORDER BY consultdocs.document_no"; ArrayList<LabResultData> labResults = new ArrayList<LabResultData>(); ArrayList<LabResultData> attachedLabs = new ArrayList<LabResultData>(); try { ResultSet rs = DBHandler.GetSQL(attachQuery); while (rs.next()) { LabResultData lbData = new LabResultData(LabResultData.HL7TEXT); lbData.labPatientId = oscar.Misc.getString(rs, "document_no"); attachedLabs.add(lbData); } rs.close(); LabResultData lbData = new LabResultData(LabResultData.HL7TEXT); LabResultData.CompareId c = lbData.getComparatorId(); rs = DBHandler.GetSQL(sql); while (rs.next()) { lbData.segmentID = oscar.Misc.getString(rs, "lab_no"); lbData.labPatientId = oscar.Misc.getString(rs, "id"); lbData.dateTime = oscar.Misc.getString(rs, "obr_date"); lbData.discipline = oscar.Misc.getString(rs, "discipline"); lbData.accessionNumber = oscar.Misc.getString(rs, "accessionNum"); lbData.finalResultsCount = rs.getInt("final_result_count"); lbData.label = oscar.Misc.getString(rs, "label"); if (attached && Collections.binarySearch(attachedLabs, lbData, c) >= 0) labResults.add(lbData); else if (!attached && Collections.binarySearch(attachedLabs, lbData, c) < 0) labResults.add(lbData); lbData = new LabResultData(LabResultData.HL7TEXT); } rs.close(); } catch (Exception e) { logger.error("exception in HL7Populate", e); } return labResults; }
From source file:org.libreplan.business.resources.entities.Resource.java
/** * @param orderedSatisfactions/*from w w w . ja v a2 s. com*/ * @param newSatisfaction * @return the position in which if newSatisfaction is inserted would comply * with the following: * <ul> * <li>newSatisfaction startDate would be equal or posterior to all * the previous satisfactions</li> * <li>newSatisfaction startDate would be previous to all the * posterior satisfactions</li> * </ul> */ private int findPlace(List<CriterionSatisfaction> orderedSatisfactions, CriterionSatisfaction newSatisfaction) { int position = Collections.binarySearch(orderedSatisfactions, newSatisfaction, CriterionSatisfaction.BY_START_COMPARATOR); if (position >= 0) { return position + 1; } else { return Math.abs(position) - 1; } }
From source file:com.dell.asm.asmcore.asmmanager.util.deployment.ServerFilteringUtil.java
private boolean findServerNicCapabilities(FilterEnvironment filterEnvironment, SelectedServer server, List<String> vendors) { Boolean serverMatch = null;//from w w w .java 2 s . c om Boolean serverMatchWithoutOrder = null; HashMap<String, List<Map>> bioStringMappingCache = new HashMap<String, List<Map>>(); com.dell.pg.asm.server.client.device.Server serverInv = getServer(server.getRefId()); if (serverInv == null) { logger.warn("findServerNicCapabilities: Unable to find server inventory for " + server.getRefId()); return false; } List<LogicalNetworkInterface> nicsOriginal = serverInv.getNetworkInterfaceList(); if (nicsOriginal == null) { logger.warn("findServerNicCapabilities: skipped " + server.getIpAddress() + ": no nics"); return false; } List<LogicalNetworkInterface> nics = new ArrayList<>(); for (LogicalNetworkInterface nic : nicsOriginal) { try { if (!isNICEnabled(nic, serverInv.getBios(), bioStringMappingCache)) continue; } catch (IOException e) { logger.error("Check for server NIC capabilities failed for server " + serverInv.getServiceTag() + ", NIC skipped:" + nic.getFqdd(), e); continue; } nics.add(nic); } if (filterEnvironment.getPortUIMap().isEmpty()) { logger.debug("findServerNicCapabilities: skipped " + server.getIpAddress() + ", no interfaces defined in template"); return false; } List<String> filteredfqdd = new ArrayList<String>(); Set<String> serverFqdd = new HashSet<String>(); List<String> orderedInterfaces = new ArrayList<>(); List<String> fcInterfaces = new ArrayList<>(); List<SelectedNIC> selectedNICs = new ArrayList<>(); for (LogicalNetworkInterface countNic : nics) { NicFQDD nFqdd = new NicFQDD(countNic.getFqdd()); String fqddNoPartition; if (nFqdd.getPrefix().contains("FC")) { fqddNoPartition = countNic.getFqdd().trim(); if (!fcInterfaces.contains(fqddNoPartition)) fcInterfaces.add(fqddNoPartition); } else { fqddNoPartition = nFqdd.getPrefix() + "." + nFqdd.getLocator() + "." + nFqdd.getCard() + "-" + nFqdd.getPort(); String oIntf = nFqdd.getPrefix() + "." + nFqdd.getLocator() + "." + nFqdd.getCard(); // we want only one entry per interface in this list // it will define the order of cards which should match the template if (!orderedInterfaces.contains(oIntf)) orderedInterfaces.add(oIntf); } serverFqdd.add(fqddNoPartition); } Collections.sort(nics, new NicComparator()); Collections.sort(orderedInterfaces, new InterfaceComparator()); Collections.reverse(orderedInterfaces); // have to sort template interfaces by card number or else we might skip some NICs below Set<Map.Entry<String, List<String>>> templateInterfaceSet = filterEnvironment.getPortUIMap().entrySet(); List<Map.Entry<String, List<String>>> templateInterfaceList = new ArrayList<>(templateInterfaceSet); Collections.sort(templateInterfaceList, new TemplateInterfaceComparator()); if (!filterEnvironment.getFCCards().isEmpty()) { if (!checkFCCards(filterEnvironment, filteredfqdd, fcInterfaces)) { logger.warn("findServerNicCapabilities: skipped " + server.getIpAddress() + ": FC check failed"); return false; } serverMatchWithoutOrder = true; } // this is check for non-FC cards int fcPortsNeeded = filteredfqdd.size(); // adjust for ports needed by FC, we might have those fqdds selected already int totalPortsNeeded = fcPortsNeeded; // need to run this loop twice - one for exact card order match, second for match without order for (int idx = 1; idx <= 2; idx++) { totalPortsNeeded = fcPortsNeeded; int correctionNumber = 0; // adjust interface # by number of FC cards - those are out of orderedInterfaces for (Map.Entry<String, List<String>> entry : templateInterfaceList) { boolean twoByTwoInterface = filterEnvironment.getTwoByTwoInterfaces().contains(entry.getKey()); boolean iscsiInterface = filterEnvironment.getIscsiInterfaces().contains(entry.getKey()); boolean isPartitioned = filterEnvironment.getPartitionedInterfaces().contains(entry.getKey()); boolean staticOSInstallInterface = filterEnvironment.getStaticOSInstallInterfaces() .contains(entry.getKey()); int interfaceNumber = Integer.parseInt(entry.getKey().split(":")[0]); if (filterEnvironment.getFCCards().contains(entry.getKey())) { // skip the card, it is already checked earlier by checkFCCards correctionNumber++; continue; } interfaceNumber -= correctionNumber; List<String> values = entry.getValue(); List<String> portsPerSlot = new ArrayList<String>(); totalPortsNeeded += values.size(); // check if the filteredfqdd has the same port. for (String port : values) { boolean portMatchesOrdered = false; boolean portMatches = false; int numOfPorts = values.size(); for (LogicalNetworkInterface nic : nics) { // special case: skip ISCSI interfaces for Intel cards and Hardware ISCSI in template OS settings if (iscsiInterface && filterEnvironment.isHardwareISCSI() && nic.getVendorName() != null && nic.getVendorName().contains(Vendor.Intel.value())) { logger.debug("findServerNicCapabilities: " + server.getIpAddress() + ", skipped NIC: " + nic.getFqdd() + " ISCSI interfaces for Intel cards and Hardware ISCSI in template OS settings"); continue; } // special case: skip partitioned interfaces for Intel cards if (isPartitioned && nic.getVendorName() != null && nic.getVendorName().contains(Vendor.Intel.value())) { logger.debug("findServerNicCapabilities: " + server.getIpAddress() + ", skipped NIC: " + nic.getFqdd() + " partitioned interfaces for Intel cards"); continue; } // Special case: skip staticOSInstall interfaces for non-Intel cards if (staticOSInstallInterface && nic.getVendorName() != null && !nic.getVendorName().contains(Vendor.Intel.value())) { logger.debug("findServerNicCapabilities: " + server.getIpAddress() + ", skipped NIC: " + nic.getFqdd() + " staticOSInstall interfaces for non-Intel cards"); continue; } // for Brocade 57800 NICs only consider 2x10GB,2x1GB port type boolean isTwoByTwo = isTwoByTwoNic(nic, nics); if (twoByTwoInterface) { if (!isTwoByTwo) { logger.debug("findServerNicCapabilities: " + server.getIpAddress() + ", skipped NIC: " + nic.getFqdd() + " need 2x2 card for this interface: " + interfaceNumber); continue; } } else { // reverse statement is true as well if (isTwoByTwo) { logger.debug("findServerNicCapabilities: " + server.getIpAddress() + ", skipped NIC: " + nic.getFqdd() + " do NOT need 2x2 card for this interface: " + interfaceNumber); continue; } } NicFQDD nFqdd = new NicFQDD(nic.getFqdd()); if (nFqdd.getPrefix().contains("FC")) { logger.debug("findServerNicCapabilities: " + server.getIpAddress() + ", skipped NIC: " + nic.getFqdd() + " FC card"); continue; } String fqddNoPartition = nFqdd.getPrefix() + "." + nFqdd.getLocator() + "." + nFqdd.getCard() + "-" + nFqdd.getPort(); String fqddCard = nFqdd.getPrefix() + "." + nFqdd.getLocator() + "." + nFqdd.getCard(); if ((nFqdd.getPort().contentEquals(port))) { if (filteredfqdd.isEmpty() || !filteredfqdd.contains(fqddNoPartition)) { if (nFqdd.getPrefix().contains("NIC") && stringContains(nic.getVendorName(), vendors)) { boolean nicSelected = false; switch (numOfPorts) { case 1: // how is that possible??? logger.error( "Invalid filtering environment: the template has a card with a single port, interface #" + interfaceNumber); throw new LocalizedWebApplicationException( Response.Status.INTERNAL_SERVER_ERROR, AsmManagerMessages.internalError()); case 2: if (checkNicQuad(nic, nics)) { logger.debug("findServerNicCapabilities: " + server.getIpAddress() + ", skipped NIC: " + nic.getFqdd() + " Quad port card"); continue; } if (portsPerSlot.isEmpty()) { LogicalNetworkInterface searchNicFqdd = new LogicalNetworkInterface(); String m = nFqdd.getPrefix() + "." + nFqdd.getLocator() + "." + nFqdd.getCard() + "-" + 2; searchNicFqdd.setFqdd(m); int index = Collections.binarySearch(nics, searchNicFqdd, new NicComparatorWithoutPartition()); if (index >= 0) { nicSelected = true; break; } } else { nicSelected = true; break; } break; case 4: if (!checkNicQuad(nic, nics)) { logger.debug("findServerNicCapabilities: " + server.getIpAddress() + ", skipped NIC: " + nic.getFqdd() + " NOT quad port card"); continue; } if (portsPerSlot.isEmpty()) { String m = nFqdd.getPrefix() + "." + nFqdd.getLocator() + "." + nFqdd.getCard() + "-" + 4; LogicalNetworkInterface searchNicFqdd = new LogicalNetworkInterface(); searchNicFqdd.setFqdd(m); int index = Collections.binarySearch(nics, searchNicFqdd, new NicComparatorWithoutPartition()); if (index >= 0) { nicSelected = true; break; } } else { nicSelected = true; break; } break; } if (nicSelected) { portsPerSlot.add(fqddNoPartition); if (orderedInterfaces.indexOf(fqddCard) == interfaceNumber - 1) { portMatchesOrdered = true; } else { portMatches = true; } if (portMatchesOrdered || (idx == 2 && portMatches)) { filteredfqdd.add(fqddNoPartition); selectedNICs.add(new SelectedNIC(entry.getKey(), port, nic.getFqdd())); } } } } } if (portMatchesOrdered || (idx == 2 && portMatches)) break; } if (!portMatchesOrdered && !portMatches) { logger.debug("findServerNicCapabilities: skipped " + server.getIpAddress() + ": cannot find matched NIC for interface # " + interfaceNumber + ", port # " + port); logger.debug("Selected NICs: " + selectedNICs.toString()); return false; } serverMatch = (serverMatch != null) ? serverMatch && portMatchesOrdered : portMatchesOrdered; if (idx == 2) { serverMatchWithoutOrder = (serverMatchWithoutOrder != null) ? serverMatchWithoutOrder && portMatches : portMatches; } } } // only run second check if we didn't find exact match for ordered interfaces if (serverMatch != null && serverMatch && filteredfqdd.size() == totalPortsNeeded) break; } serverMatch = (serverMatch != null) && (serverMatch && filteredfqdd.size() == totalPortsNeeded); serverMatchWithoutOrder = (serverMatchWithoutOrder != null) && (serverMatchWithoutOrder && filteredfqdd.size() == totalPortsNeeded); // server has exact number of ports & partitions and also order matches server.setExactMatch(serverMatch && serverFqdd.size() == filteredfqdd.size()); server.setMatchUnordered(serverMatch || serverMatchWithoutOrder); server.setNics(selectedNICs); if (serverMatch || serverMatchWithoutOrder) return true; else { logger.debug("findServerNicCapabilities: skipped " + server.getIpAddress() + ": not enough card for required number of ports: " + totalPortsNeeded); logger.debug("Selected NICs: " + selectedNICs.toString()); return false; } }
From source file:com.nookdevs.market.NookMarket.java
private void loadApps(String url) { try {//from w ww . j a va 2s . c o m final LayoutInflater inflater = getLayoutInflater(); HttpGet request = new HttpGet(url); DefaultHttpClient httpClient = new DefaultHttpClient(); HttpResponse response = httpClient.execute(request); XmlPullParserFactory fact = XmlPullParserFactory.newInstance(); fact.setNamespaceAware(false); XmlPullParser parser = fact.newPullParser(); parser.setInput(response.getEntity().getContent(), null); int type; AppInfo app = null; String name = ""; String title = null; boolean entry = false; boolean apk = false; boolean nooklet = false; while ((type = parser.next()) != XmlPullParser.END_DOCUMENT) { if (type == XmlPullParser.START_TAG) { name = parser.getName(); if (name.equals("entry")) { entry = true; app = new AppInfo(); } else if (entry && name.equals("link")) { String val = parser.getAttributeValue(null, "type"); if (val != null && val.equals("application/vnd.android.package-archive")) { apk = true; } else if (val != null && val.equals("application/atom+xml")) { String url_new = parser.getAttributeValue(null, "href"); loadApps(url_new); entry = false; title = null; continue; } else if ("application/zip".equals(val)) { if (m_NookletInstalled) { nooklet = true; } else { entry = false; title = null; continue; } } else { entry = false; title = null; continue; } if (app.version == null) app.version = parser.getAttributeValue(null, "version"); app.url = parser.getAttributeValue(null, "href"); if (app.pkg == null) app.pkg = parser.getAttributeValue(null, "pkg"); } } else if (entry && type == XmlPullParser.TEXT) { String text = parser.getText().trim(); if (text.equals("")) continue; if (name.equals("title")) { app.title = text; } else if (name.equals("content")) { app.text = text; } else if (name.equals("version")) { app.version = text; } else if (name.equals("pkg")) { app.pkg = text; } } else if (entry && type == XmlPullParser.END_TAG && parser.getName().equals("entry")) { entry = false; final String orgPkg = app.pkg; if (apk || nooklet) { if (nooklet) { String currVersion = null; File f = new File(m_NookletFolder + "/" + app.pkg + "/" + "version.txt"); if (f.exists()) { BufferedReader fin = new BufferedReader(new FileReader(f)); currVersion = fin.readLine(); fin.close(); app.installed = true; } if (app.version != null) { if (!app.title.contains(app.version)) app.title = app.title + " " + app.version; if (currVersion != null && !app.version.trim().equals(currVersion)) { app.updateAvailable = true; app.text = "***Update Available***\n" + app.text; } } app.pkg = "Nooklet/" + app.pkg; } else { apk = false; if ("MyNook.Ru Launcher".equals(app.title) && "1.5.6".equals(app.version)) { app = null; continue; } if (installedApps.containsKey(app.pkg)) { PackageInfo info = installedApps.get(app.pkg); app.installed = true; if (app.version != null) { if (!app.title.contains(app.version)) app.title = app.title + " " + app.version; if (!app.version.trim().equals(info.versionName)) { app.updateAvailable = true; app.text = "***Update Available***\n" + app.text; } } } else if (app.version != null && !app.title.contains(app.version)) { app.title = app.title + " " + app.version; } } final int idx = -Collections.binarySearch(availableApps, app, myComp) - 1; availableApps.add(idx, app); final AppInfo app1 = app; final boolean nooklet1 = nooklet; Runnable run = new Runnable() { public void run() { RelativeLayout appdetails = (RelativeLayout) inflater.inflate(R.layout.addapp, m_Content, false); ImageButton icon = (ImageButton) appdetails.findViewById(R.id.appicon); icon.setOnClickListener(appListener); if (!app1.installed) { icon.setImageResource(R.drawable.icon); } else { icon.setOnLongClickListener(appdelListener); try { if (nooklet1) { File f = new File(m_NookletFolder + "/" + orgPkg + "/icon.png"); if (f.exists()) icon.setImageURI( Uri.parse(m_NookletFolder + "/" + orgPkg + "/icon.png")); else icon.setImageResource(R.drawable.icon); } else if (installedApps.get(app1.pkg).activities != null && installedApps.get(app1.pkg).activities[0] != null) icon.setImageDrawable(installedApps.get(app1.pkg).activities[0] .loadIcon(getPackageManager())); else icon.setImageDrawable(installedApps.get(app1.pkg).applicationInfo .loadIcon(getPackageManager())); } catch (Exception ex) { icon.setImageResource(R.drawable.icon); } } icon.setTag(app1); TextView text = (TextView) appdetails.findViewById(R.id.desc); TextView title1 = (TextView) appdetails.findViewById(R.id.title); text.setText(app1.text); title1.setText(app1.title); m_Content.addView(appdetails, idx); if (idx == 0) closeAlert(); } }; m_Handler.post(run); nooklet = false; } else { app.installed = false; app.updateAvailable = false; app.version = null; app.pkg = null; documents.add(app); } app = null; } } } catch (Exception ex) { Log.e(LOGTAG, ex.getMessage(), ex); //alert and exit. if (availableApps.size() == 0) m_Handler.post(new Runnable() { public void run() { closeAlert(); displayAlert(getString(R.string.network), getString(R.string.feed_error), 2, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }, -1); } }); } }
From source file:com.googlecode.networklog.AppFragment.java
public int getItemByAppUid(int uid) { if (groupDataBuffer == null) { return -1; }/*from ww w . j av a 2 s . c o m*/ synchronized (groupDataBuffer) { // check to see if we need to search for index // (more often than not, the last index is still the active index being requested) if (lastGetItemByAppUidIndex < 0 || groupDataBuffer.get(lastGetItemByAppUidIndex).app.uid != uid) { cachedSearchItem.app.uid = uid; lastGetItemByAppUidIndex = Collections.binarySearch(groupDataBuffer, cachedSearchItem, comparator); } // binarySearch isn't guaranteed to return the first item of items with the same uid // so find the first item while (lastGetItemByAppUidIndex > 0) { if (groupDataBuffer.get(lastGetItemByAppUidIndex - 1).app.uid == uid) { lastGetItemByAppUidIndex--; } else { break; } } } return lastGetItemByAppUidIndex; }
From source file:com.inkubator.hrm.service.impl.TempAttendanceRealizationServiceImpl.java
private Float calculateAndCheckTotalOverTime(List<ImplementationOfOverTime> listImplementationOfOverTime, WtPeriode wtPeriode, Long empDataId, String religionCode) throws Exception { Float totalOvertime = 0f;//from ww w . ja va2 s . c o m //Get List Holiday Schedule List<TempJadwalKaryawan> listJadwalLibur = tempJadwalKaryawanDao.getAllDataByEmpIdAndPeriodDateAndOffDay( empDataId, wtPeriode.getFromPeriode(), wtPeriode.getUntilPeriode()); List<Date> listDateLibur = Lambda.extract(listJadwalLibur, Lambda.on(TempJadwalKaryawan.class).getTanggalWaktuKerja()); Collections.sort(listDateLibur); //Get List Public Non Religion Holiday Schedule List<WtHoliday> listPublicNonReligionHoliday = wtHolidayDao.getListPublicNonReligionHolidayBetweenDate( wtPeriode.getFromPeriode(), wtPeriode.getUntilPeriode()); List<Date> listPublicNonReligionHolidayDate = Lambda.extract(listPublicNonReligionHoliday, Lambda.on(WtHoliday.class).getHolidayDate()); Collections.sort(listPublicNonReligionHolidayDate); //Get List Public Religion Holiday Schedule List<WtHoliday> listPublicReligionHoliday = wtHolidayDao .getListPublicReligionHolidayByReligionCodeAndBetweenDate(wtPeriode.getFromPeriode(), wtPeriode.getUntilPeriode(), religionCode); List<Date> listPublicReligionHolidayDate = Lambda.extract(listPublicReligionHoliday, Lambda.on(WtHoliday.class).getHolidayDate()); Collections.sort(listPublicReligionHolidayDate); //Looping List Overtime Implementation for (ImplementationOfOverTime otImpl : listImplementationOfOverTime) { //if overtime with null wtHitungLembur found, throw BussinessException if (ObjectUtils.equals(otImpl.getWtOverTime().getWtHitungLembur(), null)) { throw new BussinessException( "workingTime.attendance_realization_calc_error_overtime_with_null_wt_hitung_lembur_found"); } List<WtHitungLemburJam> listWtHitungLemburJam = wtHitungLemburJamDao .getListByWtHitungLemburId(otImpl.getWtOverTime().getWtHitungLembur().getId()); Boolean isImplementedOnScheduleHoliday = Collections.binarySearch(listDateLibur, otImpl.getImplementationDate(), new MyDateComparator()) >= 0; Boolean isImplementedOnPublicNonReligionHoliday = Collections.binarySearch( listPublicNonReligionHolidayDate, otImpl.getImplementationDate(), new MyDateComparator()) >= 0; Boolean isImplementedOnPublicReligionHoliday = Collections.binarySearch(listPublicReligionHolidayDate, otImpl.getImplementationDate(), new MyDateComparator()) >= 0; //get total Overtime in hours Float totalHoursOvertime = DateTimeUtil .getTotalHoursDifference(otImpl.getStartTime(), otImpl.getEndTime()).floatValue(); //Initialize real total hours overtime Float realTotalOverTime = 0f; //Check implementOn and calculate real total hours based on implementOn if (isImplementedOnScheduleHoliday || isImplementedOnPublicNonReligionHoliday) { realTotalOverTime = countRealOverTime(totalHoursOvertime, listWtHitungLemburJam, "schduleOrPublicNonReligionHoliday"); } else if (isImplementedOnPublicReligionHoliday) { realTotalOverTime = countRealOverTime(totalHoursOvertime, listWtHitungLemburJam, "publicReligionHoliday"); } else { realTotalOverTime = countRealOverTime(totalHoursOvertime, listWtHitungLemburJam, "workingDay"); } //increment totalOvertime with each realTotalOvertime record totalOvertime += realTotalOverTime; } //if totalOvertime Is Not A Number than reinitialize to 0 if (totalOvertime.isNaN()) { totalOvertime = 0f; } //return totalOvertime of employee during period active return totalOvertime; }