List of usage examples for java.util Collections binarySearch
public static <T> int binarySearch(List<? extends Comparable<? super T>> list, T key)
From source file:com.pactera.edg.am.metamanager.extractor.adapter.extract.db.impl.TeradataExtractServiceImpl.java
private void setDependenciesBetweenViewAndTable(List<HashMap<String, String>> columnRel) { for (HashMap<String, String> cols : columnRel) { // ???//from w w w . j av a2 s . c o m String srcObj = cols.get("Src_Obj").toUpperCase(); String tgtObj = cols.get("Tgt_Obj").toUpperCase(); // SRC,TGT?,? // ?:3,?schema.table.column?;??? String[] srcObjs = srcObj.split("\\."); String[] tgtObjs = tgtObj.split("\\."); // ? NamedColumnSet simTgtView = new View(); simTgtView.setName(tgtObjs[1]); List<NamedColumnSet> columnSets = cntSchema.getColumnSets(); // ??? int index = Collections.binarySearch(columnSets, simTgtView); if (index < 0) { continue; } // index // >=0,?(??,??...??!?...??....) // ?,?,??,Map,?,??? View tgtView = (View) columnSets.get(index); // List<Column> tgtViewColumns = tgtView.getColumns(); for (Column tgtViewColumn : tgtViewColumns) { if (tgtViewColumn.getName().equals(tgtObjs[2])) { // ??? NamedColumnSetType srcType = getNamedColumnSetType(srcObjs[0].concat(".").concat(srcObjs[1])); // tgtViewColumn.addReferenceSchTableColumn(srcObj, srcType); break; } } } }
From source file:org.jfree.data.xy.XYSeries.java
/** * Returns the index of the item with the specified x-value, or a * negative index if the series does not contain an item with that * x-value. Be aware that for an unsorted series, the index is * found by iterating through all items in the series. * * @param x the x-value (<code>null</code> not permitted). * * @return The index./*from w w w . j a v a 2s . c o m*/ */ public int indexOf(Number x) { if (this.autoSort) { return Collections.binarySearch(this.data, new XYDataItem(x, null)); } else { for (int i = 0; i < this.data.size(); i++) { XYDataItem item = (XYDataItem) this.data.get(i); if (item.getX().equals(x)) { return i; } } return -1; } }
From source file:com.facebook.infrastructure.io.SSTable.java
public static Range getRange(String key, IFileReader dataReader) throws IOException { List<KeyPositionInfo> indexInfo = indexMetadataMap_.get(dataReader.getFileName()); int size = (indexInfo == null) ? 0 : indexInfo.size(); long start = 0L; long end = dataReader.getEOF(); if (size > 0) { final int index = Collections.binarySearch(indexInfo, new KeyPositionInfo(key)); if (index < 0) { // key is not present at all; scan is required int insertIndex = (index + 1) * -1; start = (insertIndex == 0) ? 0 : indexInfo.get(insertIndex - 1).position; if (insertIndex < size) { end = indexInfo.get(insertIndex).position; } else { /* This is the Block Index in the file. */ end = start;/* ww w . j ava 2 s.c o m*/ } } else { /* If we are here that means the key is in the index file * and we can retrieve it w/o a scan. * TODO we would * like to have a retreive(key, fromPosition) but for now * we use scan(start, start + 1) - a hack. */ start = indexInfo.get(index).position; end = start; } } else { /* * We are here which means there are less than * 128 keys in the system and hence our only recourse * is a linear scan from start to finish. Automatically * use memory mapping since we have a huge file and very * few keys. */ end = dataReader.getEOF(); } return new Range(start, end); }
From source file:org.apache.pig.backend.hadoop.executionengine.util.MapRedUtil.java
public static List<List<InputSplit>> getCombinePigSplits(List<InputSplit> oneInputSplits, long maxCombinedSplitSize, Configuration conf) throws IOException, InterruptedException { ArrayList<Node> nodes = new ArrayList<Node>(); HashMap<String, Node> nodeMap = new HashMap<String, Node>(); List<List<InputSplit>> result = new ArrayList<List<InputSplit>>(); List<Long> resultLengths = new ArrayList<Long>(); long comparableSplitId = 0; int size = 0, nSplits = oneInputSplits.size(); InputSplit lastSplit = null;//from w ww . jav a 2 s . com int emptyCnt = 0; for (InputSplit split : oneInputSplits) { if (split.getLength() == 0) { emptyCnt++; continue; } if (split.getLength() >= maxCombinedSplitSize) { comparableSplitId++; ArrayList<InputSplit> combinedSplits = new ArrayList<InputSplit>(); combinedSplits.add(split); result.add(combinedSplits); resultLengths.add(split.getLength()); } else { String[] locations = split.getLocations(); if (locations.length == 0) { // This split is missing blocks, or the split returned bad locations. // Don't try to combine. comparableSplitId++; ArrayList<InputSplit> combinedSplits = new ArrayList<InputSplit>(); combinedSplits.add(split); result.add(combinedSplits); resultLengths.add(split.getLength()); } else { ComparableSplit csplit = new ComparableSplit(split, comparableSplitId++); // sort the locations to stabilize the number of maps: PIG-1757 Arrays.sort(locations); HashSet<String> locationSeen = new HashSet<String>(); for (String location : locations) { if (!locationSeen.contains(location)) { Node node = nodeMap.get(location); if (node == null) { node = new Node(); nodes.add(node); nodeMap.put(location, node); } node.add(csplit); csplit.add(node); locationSeen.add(location); } } lastSplit = split; size++; } } } /* verification code: debug purpose { ArrayList<ComparableSplit> leftoverSplits = new ArrayList<ComparableSplit>(); HashSet<InputSplit> seen = new HashSet<InputSplit>(); for (Node node : nodes) { if (node.getLength() > 0) { ArrayList<ComparableSplit> splits = node.getSplits(); for (ComparableSplit split : splits) { if (!seen.contains(split.getSplit())) { // remove duplicates. The set has to be on the raw input split not the // comparable input split as the latter overrides the compareTo method // so its equality semantics is changed and not we want here seen.add(split.getSplit()); leftoverSplits.add(split); } } } } int combinedSplitLen = 0; for (PigSplit split : result) combinedSplitLen += split.getNumPaths(); if (combinedSplitLen + leftoverSplits.size()!= nSplits-emptyCnt) { throw new AssertionError("number of combined splits {"+combinedSplitLen+"+"+leftoverSplits.size()+"-"+size+"} does not match the number of original splits ["+nSplits+"]."); } } */ if (nSplits > 0 && emptyCnt == nSplits) { // if all splits are empty, add a single empty split as currently an empty directory is // not properly handled somewhere ArrayList<InputSplit> combinedSplits = new ArrayList<InputSplit>(); combinedSplits.add(oneInputSplits.get(0)); result.add(combinedSplits); } else if (size == 1) { ArrayList<InputSplit> combinedSplits = new ArrayList<InputSplit>(); combinedSplits.add(lastSplit); result.add(combinedSplits); } else if (size > 1) { // combine small splits Collections.sort(nodes, nodeComparator); DummySplit dummy = new DummySplit(); // dummy is used to search for next split of suitable size to be combined ComparableSplit dummyComparableSplit = new ComparableSplit(dummy, -1); for (Node node : nodes) { // sort the splits on this node in descending order node.sort(); long totalSize = 0; ArrayList<ComparableSplit> splits = node.getSplits(); int idx; int lenSplits; ArrayList<InputSplit> combinedSplits = new ArrayList<InputSplit>(); ArrayList<ComparableSplit> combinedComparableSplits = new ArrayList<ComparableSplit>(); while (!splits.isEmpty()) { combinedSplits.add(splits.get(0).getSplit()); combinedComparableSplits.add(splits.get(0)); int startIdx = 1; lenSplits = splits.size(); totalSize += splits.get(0).getSplit().getLength(); long spaceLeft = maxCombinedSplitSize - totalSize; dummy.setLength(spaceLeft); idx = Collections.binarySearch(node.getSplits().subList(startIdx, lenSplits), dummyComparableSplit); idx = -idx - 1 + startIdx; while (idx < lenSplits) { long thisLen = splits.get(idx).getSplit().getLength(); combinedSplits.add(splits.get(idx).getSplit()); combinedComparableSplits.add(splits.get(idx)); totalSize += thisLen; spaceLeft -= thisLen; if (spaceLeft <= 0) break; // find next combinable chunk startIdx = idx + 1; if (startIdx >= lenSplits) break; dummy.setLength(spaceLeft); idx = Collections.binarySearch(node.getSplits().subList(startIdx, lenSplits), dummyComparableSplit); idx = -idx - 1 + startIdx; } if (totalSize > maxCombinedSplitSize / 2) { result.add(combinedSplits); resultLengths.add(totalSize); removeSplits(combinedComparableSplits); totalSize = 0; combinedSplits = new ArrayList<InputSplit>(); combinedComparableSplits.clear(); splits = node.getSplits(); } else { if (combinedSplits.size() != lenSplits) throw new AssertionError("Combined split logic error!"); break; } } } // handle leftovers ArrayList<ComparableSplit> leftoverSplits = new ArrayList<ComparableSplit>(); HashSet<InputSplit> seen = new HashSet<InputSplit>(); for (Node node : nodes) { for (ComparableSplit split : node.getSplits()) { if (!seen.contains(split.getSplit())) { // remove duplicates. The set has to be on the raw input split not the // comparable input split as the latter overrides the compareTo method // so its equality semantics is changed and not we want here seen.add(split.getSplit()); leftoverSplits.add(split); } } } /* verification code int combinedSplitLen = 0; for (PigSplit split : result) combinedSplitLen += split.getNumPaths(); if (combinedSplitLen + leftoverSplits.size()!= nSplits-emptyCnt) throw new AssertionError("number of combined splits ["+combinedSplitLen+"+"+leftoverSplits.size()+"] does not match the number of original splits ["+nSplits+"]."); */ if (!leftoverSplits.isEmpty()) { long totalSize = 0; ArrayList<InputSplit> combinedSplits = new ArrayList<InputSplit>(); ArrayList<ComparableSplit> combinedComparableSplits = new ArrayList<ComparableSplit>(); int splitLen = leftoverSplits.size(); for (int i = 0; i < splitLen; i++) { ComparableSplit split = leftoverSplits.get(i); long thisLen = split.getSplit().getLength(); if (totalSize + thisLen >= maxCombinedSplitSize) { removeSplits(combinedComparableSplits); result.add(combinedSplits); resultLengths.add(totalSize); combinedSplits = new ArrayList<InputSplit>(); combinedComparableSplits.clear(); totalSize = 0; } combinedSplits.add(split.getSplit()); combinedComparableSplits.add(split); totalSize += split.getSplit().getLength(); if (i == splitLen - 1) { // last piece: it could be very small, try to see it can be squeezed into any existing splits for (int j = 0; j < result.size(); j++) { if (resultLengths.get(j) + totalSize <= maxCombinedSplitSize) { List<InputSplit> isList = result.get(j); for (InputSplit csplit : combinedSplits) { isList.add(csplit); } removeSplits(combinedComparableSplits); combinedSplits.clear(); break; } } if (!combinedSplits.isEmpty()) { // last piece can not be squeezed in, create a new combined split for them. removeSplits(combinedComparableSplits); result.add(combinedSplits); } } } } } /* verification codes int combinedSplitLen = 0; for (PigSplit split : result) combinedSplitLen += split.getNumPaths(); if (combinedSplitLen != nSplits-emptyCnt) throw new AssertionError("number of combined splits ["+combinedSplitLen+"] does not match the number of original splits ["+nSplits+"]."); long totalLen = 0; for (PigSplit split : result) totalLen += split.getLength(); long origTotalLen = 0; for (InputSplit split : oneInputSplits) origTotalLen += split.getLength(); if (totalLen != origTotalLen) throw new AssertionError("The total length ["+totalLen+"] does not match the original ["+origTotalLen+"]"); */ log.info("Total input paths (combined) to process : " + result.size()); return result; }
From source file:org.jfree.data.time.TimeSeries.java
/** * Returns the index for the item (if any) that corresponds to a time * period./* w w w . j av a 2 s .com*/ * * @param period the time period (<code>null</code> not permitted). * * @return The index. */ public int getIndex(RegularTimePeriod period) { ParamChecks.nullNotPermitted(period, "period"); TimeSeriesDataItem dummy = new TimeSeriesDataItem(period, Integer.MIN_VALUE); return Collections.binarySearch(this.data, dummy); }
From source file:com.wizecommerce.hecuba.hector.HectorBasedHecubaClientManager.java
public CassandraResultSet<K, String> retrieveBySecondaryIndex(String columnName, String columnValue) { // first some fact checking, before going to Cassandra if (isSecondaryIndexByColumnNameAndValueEnabled && Collections.binarySearch(columnsToIndexOnColumnNameAndValue, columnName) >= 0) { return retrieveFromSecondaryIndex(columnName, columnValue); }//from w w w.j a va2 s.co m return null; }
From source file:edu.ku.brc.af.ui.db.DatabaseLoginPanel.java
/** * Creates the UI for the login and hooks up any listeners. * @param isDlg whether the parent is a dialog (false mean JFrame) * @param iconName the icon that will be shown in the panel * @param engageUPPrefs whether it should load and save the username password into the prefs * @param helpContext the help context to use. *///from ww w. j av a 2s .c o m protected void createUI(final boolean isDlg, final String iconName, final String helpContext) { final boolean isNotEmbedded = !DBConnection.getInstance().isEmbedded() && !UIRegistry.isMobile(); final AppPreferences localPrefs = AppPreferences.getLocalPrefs(); //Font cachedFont = UIManager.getFont("JLabel.font"); SkinItem skinItem = SkinsMgr.getSkinItem("LoginPanel"); if (skinItem != null) { skinItem.pushFG("Label.foreground"); } if (isNotEmbedded) { SpinnerModel portModel = new SpinnerNumberModel(3306, //initial value 0, //min Integer.MAX_VALUE, //max 1); //step portSpinner = new JSpinner(portModel); JSpinner.NumberEditor editor = new JSpinner.NumberEditor(portSpinner, "#"); portSpinner.setEditor(editor); portSpinner.addChangeListener(new ChangeListener() { @Override public void stateChanged(ChangeEvent e) { DatabaseDriverInfo drvInfo = dbDrivers.get(dbDriverCBX.getSelectedIndex()); if (drvInfo != null && isNotEmbedded && portSpinner != null) { drvInfo.setPort((Integer) portSpinner.getValue()); } } }); setControlSize(portSpinner); } // First create the controls and hook up listeners dbPickList = new PropertiesPickListAdapter("login.databases"); //$NON-NLS-1$ svPickList = new PropertiesPickListAdapter("login.servers"); //$NON-NLS-1$ username = createTextField(15); password = createPasswordField(15); FocusAdapter focusAdp = new FocusAdapter() { @Override public void focusGained(FocusEvent e) { super.focusGained(e); JTextField tf = (JTextField) e.getSource(); tf.selectAll(); } }; username.addFocusListener(focusAdp); password.addFocusListener(focusAdp); databases = new ValComboBox(dbPickList); if (databases.getComboBox() instanceof Java2sAutoComboBox) { ((Java2sAutoComboBox) databases.getComboBox()).setCaseSensitive(true); } servers = new ValComboBox(svPickList); dbPickList.setComboBox(databases); svPickList.setComboBox(servers); setControlSize(password); setControlSize(databases); setControlSize(servers); if (masterUsrPwdProvider != null) { editKeyInfoBtn = UIHelper.createI18NButton("CONFIG_MSTR_KEY"); editKeyInfoBtn.setIcon(IconManager.getIcon("Key", IconManager.IconSize.Std20)); editKeyInfoBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (masterUsrPwdProvider != null && databases != null) { String itemName = null; if (databases.getComboBox().getSelectedItem() instanceof String) { itemName = (String) databases.getComboBox().getSelectedItem(); } else { PickListItemIFace pli = (PickListItemIFace) databases.getComboBox().getSelectedItem(); if (pli != null && pli.getValue() != null) { itemName = pli.getValue(); } } if (itemName != null) { masterUsrPwdProvider.editMasterInfo(username.getText(), itemName, false); } } } }); } rememberUsernameCBX = createCheckBox(getResourceString("rememberuser")); //$NON-NLS-1$ rememberUsernameCBX.setEnabled(engageUPPrefs); statusBar = new JStatusBar(); statusBar.setErrorIcon(IconManager.getIcon("Error", IconManager.IconSize.Std16)); //$NON-NLS-1$ cancelBtn = createButton(getResourceString("CANCEL")); //$NON-NLS-1$ loginBtn = createButton(getResourceString("Login")); //$NON-NLS-1$ helpBtn = createButton(getResourceString("HELP")); //$NON-NLS-1$ forwardImgIcon = IconManager.getIcon("Forward"); //$NON-NLS-1$ downImgIcon = IconManager.getIcon("Down"); //$NON-NLS-1$ moreBtn = new JCheckBox(getResourceString("LOGIN_DLG_MORE"), forwardImgIcon); // XXX I18N //$NON-NLS-1$ setControlSize(moreBtn); // Extra dbDrivers = DatabaseDriverInfo.getDriversList(); dbDriverCBX = createComboBox(dbDrivers); dbDriverCBX.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { updateUIControls(); DatabaseDriverInfo drvInfo = dbDrivers.get(dbDriverCBX.getSelectedIndex()); if (drvInfo != null && isNotEmbedded && portSpinner != null) { Integer defPort = drvInfo.getPortAsInt(); int portFromPref = localPrefs.getInt(LOGIN_PORT, defPort); portSpinner.setValue(portFromPref); drvInfo.setPort(portFromPref); } } }); if (dbDrivers.size() > 0) { if (dbDrivers.size() == 1) { dbDriverCBX.setSelectedIndex(0); dbDriverCBX.setEnabled(false); } else { String selectedStr = localPrefs.get("login.dbdriver_selected", "MySQL"); //$NON-NLS-1$ //$NON-NLS-2$ int inx = Collections.binarySearch(dbDrivers, new DatabaseDriverInfo(selectedStr, null, null, false, null)); dbDriverCBX.setSelectedIndex(inx > -1 ? inx : -1); } } else { JOptionPane.showConfirmDialog(null, getResourceString("NO_DBDRIVERS"), //$NON-NLS-1$ getResourceString("NO_DBDRIVERS_TITLE"), JOptionPane.CLOSED_OPTION); //$NON-NLS-1$ System.exit(1); } addFocusListenerForTextComp(username); addFocusListenerForTextComp(password); addKeyListenerFor(username, !isDlg); addKeyListenerFor(password, !isDlg); addKeyListenerFor(databases.getTextField(), !isDlg); addKeyListenerFor(servers.getTextField(), !isDlg); if (!isDlg) { addKeyListenerFor(loginBtn, true); } rememberUsernameCBX.setSelected(engageUPPrefs ? localPrefs.getBoolean("login.rememberuser", false) : false); //$NON-NLS-1$ cancelBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (dbListener != null) { dbListener.cancelled(); } } }); loginBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { doLogin(); } }); HelpMgr.registerComponent(helpBtn, helpContext); //$NON-NLS-1$ moreBtn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (extraPanel.isVisible()) { if (dbDriverCBX.getSelectedIndex() != -1) { extraPanel.setVisible(false); moreBtn.setIcon(forwardImgIcon); } } else { extraPanel.setVisible(true); moreBtn.setIcon(downImgIcon); } if (window != null) { window.pack(); } } }); // Ask the PropertiesPickListAdapter to set the index from the prefs dbPickList.setSelectedIndex(); svPickList.setSelectedIndex(); servers.getTextField().addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { updateUIControls(); } }); databases.getTextField().addKeyListener(new KeyAdapter() { @Override public void keyReleased(KeyEvent e) { updateUIControls(); } }); databases.getTextField().addFocusListener(new FocusAdapter() { String server = null; private String getServerStr() { String serverStr = null; Object serverObj = servers.getValue(); if (serverObj != null) { serverStr = serverObj.toString(); } return serverStr; } @Override public void focusGained(FocusEvent e) { server = getServerStr(); } @Override public void focusLost(FocusEvent e) { if (server != null) { String newVal = getServerStr(); if (newVal != null && !newVal.equals(server)) { setUsrPwdControlsFromPrefs(); } } } }); setUsrPwdControlsFromPrefs(); // Layout the form PanelBuilder formBuilder = new PanelBuilder(new FormLayout("p,3dlu,p:g", "p,2dlu,p,2dlu,p,2dlu,p,2dlu,p")); //$NON-NLS-1$ //$NON-NLS-2$ CellConstraints cc = new CellConstraints(); formBuilder.addSeparator(getResourceString("LOGINLABEL"), cc.xywh(1, 1, 3, 1)); //$NON-NLS-1$ addLine("username", username, formBuilder, cc, 3); //$NON-NLS-1$ addLine("password", password, formBuilder, cc, 5); //$NON-NLS-1$ formBuilder.add(moreBtn, cc.xy(3, 7)); PanelBuilder extraPanelBlder = new PanelBuilder(new FormLayout("p,3dlu,p:g", //$NON-NLS-1$ UIHelper.createDuplicateJGoodiesDef("p", "2dlu", isNotEmbedded ? 9 : 11))); //$NON-NLS-1$ //$NON-NLS-2$ extraPanel = extraPanelBlder.getPanel(); extraPanel.setBorder(BorderFactory.createEmptyBorder(2, 2, 4, 2)); //extraPanelBlder.addSeparator("", cc.xywh(1, 1, 3, 1)); //$NON-NLS-1$ int y = 1; y = addLine(null, rememberUsernameCBX, extraPanelBlder, cc, y); y = addLine("databases", databases, extraPanelBlder, cc, y); //$NON-NLS-1$ y = addLine("servers", servers, extraPanelBlder, cc, y); //$NON-NLS-1$ y = addLine("driver", dbDriverCBX, extraPanelBlder, cc, y); //$NON-NLS-1$ if (isNotEmbedded) { y = addLine("port", portSpinner, extraPanelBlder, cc, y); //$NON-NLS-1$ } if (editKeyInfoBtn != null) { PanelBuilder pb = new PanelBuilder(new FormLayout("p,f:p:g", "p")); pb.add(editKeyInfoBtn, cc.xy(1, 1)); y = addLine(null, pb.getPanel(), extraPanelBlder, cc, y); pb.getPanel().setOpaque(false); } extraPanel.setVisible(false); formBuilder.add(extraPanelBlder.getPanel(), cc.xywh(3, 9, 1, 1)); PanelBuilder outerPanel = new PanelBuilder(new FormLayout("p,3dlu,p:g", "t:p,2dlu,p,2dlu,p"), this); //$NON-NLS-1$ //$NON-NLS-2$ JLabel icon = StringUtils.isNotEmpty(iconName) ? new JLabel(IconManager.getIcon(iconName)) : null; if (icon != null) { icon.setBorder(BorderFactory.createEmptyBorder(10, 10, 2, 2)); } formBuilder.getPanel().setBorder(BorderFactory.createEmptyBorder(10, 5, 0, 5)); if (icon != null) { outerPanel.add(icon, cc.xy(1, 1)); } JPanel btnPanel = ButtonBarFactory.buildOKCancelHelpBar(loginBtn, cancelBtn, helpBtn); outerPanel.add(formBuilder.getPanel(), cc.xy(3, 1)); outerPanel.add(btnPanel, cc.xywh(1, 3, 3, 1)); outerPanel.add(statusBar, cc.xywh(1, 5, 3, 1)); formBuilder.getPanel().setOpaque(false); outerPanel.getPanel().setOpaque(false); btnPanel.setOpaque(false); updateUIControls(); if (skinItem != null) { skinItem.popFG("Label.foreground"); } if (AppPreferences.getLocalPrefs().getBoolean(expandExtraPanelName, false)) { extraPanel.setVisible(true); moreBtn.setIcon(downImgIcon); } }
From source file:com.wizecommerce.hecuba.hector.HectorBasedHecubaClientManager.java
@Override public CassandraResultSet<K, String> retrieveBySecondaryIndex(String columnName, List<String> columnValues) { // first some fact checking, before going to Cassandra if (isSecondaryIndexByColumnNameAndValueEnabled && Collections.binarySearch(columnsToIndexOnColumnNameAndValue, columnName) >= 0) { return retrieveFromSecondaryIndex(columnName, columnValues); }//from ww w.j a v a 2s . c om return null; }
From source file:org.jaffa.soa.dataaccess.MappingFilter.java
private void calculateFilter(GraphMapping graph, String[] rules) { m_rules = rules != null && rules.length > 0 ? rules : new String[] { "*" }; List<String> filteredFields = new ArrayList<String>(); List<String> relToCheck = new LinkedList<String>(); long mem = Runtime.getRuntime().freeMemory(); if (log.isDebugEnabled()) log.debug("Getting Field list for " + graph.getDataClass() + ",Mem= " + (mem - Runtime.getRuntime().freeMemory() >> 10)); // build the rules m_filters = new Filter[m_rules.length]; for (int n = 0; n < m_rules.length; n++) { String r = m_rules[n];/*from ww w .j a va 2 s . com*/ m_filters[n] = new Filter(r); } // Get the complete field list List<String> allFields = getFieldList(graph.getDataClass()); if (log.isDebugEnabled()) log.debug("Returned Field list for " + graph.getDataClass() + " Size is " + (allFields != null ? allFields.size() : 0) + ",Mem= " + (mem - Runtime.getRuntime().freeMemory() >> 10)); // Look at all the included fields based on the rules for (Filter f : m_filters) { if (!f.isExcluded()) { if (f.isRegEx()) { Iterator<String> allIt = allFields.iterator(); while (allIt.hasNext()) { String fld = allIt.next(); boolean foreign = fld.startsWith("+"); boolean related = fld.startsWith("*"); if (foreign || related) fld = fld.substring(1); if (f.matches(fld)) { filteredFields.add(fld); if (related) relToCheck.add(fld); allIt.remove(); } } } else { int i = Collections.binarySearch(allFields, f.getRule()); if (i < 0) i = Collections.binarySearch(allFields, "+" + f.getRule()); if (i < 0) i = Collections.binarySearch(allFields, "*" + f.getRule()); if (i >= 0) filteredFields.add(f.getRule()); } } } // Remove any explicitly excluded fields for (Filter f : m_filters) { if (f.isExcluded()) { Iterator<String> itFil = filteredFields.iterator(); while (itFil.hasNext()) { String fld = itFil.next(); if (f.matches(fld)) { itFil.remove(); } } } } //if(filteredFields2.size()>0) // filteredFields = filteredFields2; Collections.sort(filteredFields); // Removed related reference if there are no related fields for (String field : relToCheck) { if (log.isDebugEnabled()) log.debug("Check related object " + field); if (!areSubFieldsIncluded(filteredFields, field)) { int i = Collections.binarySearch(filteredFields, field); if (i >= 0) { filteredFields.remove(i); if (log.isDebugEnabled()) log.debug("Removed related object " + field); } } } // Now make sure based on all the filtering, that all parent object // referenced // are in place. You can't have x.y.z without first having x.y and // therefore x for (int cursor = 0; cursor < filteredFields.size(); ++cursor) { // perform the check recursively since the addition of 'x.y.z' might // also require the insertion of 'x.y' and so on.. String field = (String) filteredFields.get(cursor); while (true) { int pos = field.lastIndexOf('.'); if (pos > 0) { field = field.substring(0, pos); int i = Collections.binarySearch(filteredFields, field); if (i < 0) { // Determine the insertion point. Note: the value of i // is (-(insertion point) - 1) i = -(i + 1); filteredFields.add(i, field); if (log.isDebugEnabled()) log.debug("Added missing parent object " + field); if (i <= cursor) ++cursor; } } else { break; } } } m_filteredFields = filteredFields; if (log.isDebugEnabled()) log.debug("Filtered field list for " + graph.getDataClass() + " Size is " + (filteredFields != null ? filteredFields.size() : 0) + ",Mem= " + (mem - Runtime.getRuntime().freeMemory() >> 10)); }
From source file:ru.moscow.tuzlukov.sergey.weatherlog.MainActivity.java
private long calculateTotalTimeLessThan(double temperatureLimit, long timeLeftLimit) { long totalTime = 0L; // calculating temperature at given left time limit: double temperatureAtLeftLimit; List<Long> timeList = new ArrayList<>(temperatureMap.keySet()); int indexLeftLimit = Collections.binarySearch(timeList, timeLeftLimit); if (indexLeftLimit < 0) { indexLeftLimit = -indexLeftLimit - 1; temperatureAtLeftLimit = temperatureByTime(timeList, indexLeftLimit, timeLeftLimit); for (int n = indexLeftLimit; n > 0; n--) timeList.remove(0);//from ww w . j a v a 2 s .c o m timeList.add(0, timeLeftLimit); } else { temperatureAtLeftLimit = temperatureMap.get(timeLeftLimit); for (int n = indexLeftLimit; n > 0; n--) timeList.remove(0); } // count total time when temperature was less than given limit, on all timeline for (int i = 1; i < timeList.size(); i++) { long t1 = timeList.get(i - 1), t2 = timeList.get(i); double y1 = i == 1 ? temperatureAtLeftLimit : temperatureMap.get(t1), y2 = temperatureMap.get(t2); if (y2 < temperatureLimit && y1 < temperatureLimit) totalTime += t2 - t1; else if (y2 > temperatureLimit && y1 < temperatureLimit) totalTime += timeByTemperature(t1, y1, t2, y2, temperatureLimit) - t1; else if (y2 < temperatureLimit && y1 > temperatureLimit) totalTime += t2 - timeByTemperature(t1, y1, t2, y2, temperatureLimit); } return totalTime; }