code
stringlengths
130
281k
code_dependency
stringlengths
182
306k
public class class_name { static String stripLeadingSlash(String path) { if (path.endsWith("/")) { return path.substring(0, path.length() - 1); } else { return path; } } }
public class class_name { static String stripLeadingSlash(String path) { if (path.endsWith("/")) { return path.substring(0, path.length() - 1); // depends on control dependency: [if], data = [none] } else { return path; // depends on control dependency: [if], data = [none] } } }
public class class_name { @Override public boolean check(WyilFile wf) { for (Decl decl : wf.getModule().getUnits()) { checkDeclaration(decl); } return status; } }
public class class_name { @Override public boolean check(WyilFile wf) { for (Decl decl : wf.getModule().getUnits()) { checkDeclaration(decl); // depends on control dependency: [for], data = [decl] } return status; } }
public class class_name { public static String getFileExtension(String _fileName) { if (_fileName == null) { return null; } int lastDot = _fileName.lastIndexOf('.'); if (lastDot == -1) { return ""; } return _fileName.substring(lastDot + 1); } }
public class class_name { public static String getFileExtension(String _fileName) { if (_fileName == null) { return null; // depends on control dependency: [if], data = [none] } int lastDot = _fileName.lastIndexOf('.'); if (lastDot == -1) { return ""; // depends on control dependency: [if], data = [none] } return _fileName.substring(lastDot + 1); } }
public class class_name { public static URLConnection prepareForAuthentication( final URLConnection connection ) { NullArgumentException.validateNotNull( connection, "url connection cannot be null" ); if( connection.getURL().getUserInfo() != null ) { // Need to decode username/password because it may contain encoded characters (http://www.w3schools.com/tags/ref_urlencode.asp) // A common encoding is to provide a username as an email address like user%40domain.org String decodedUserInfo = decode( connection.getURL().getUserInfo() ); String base64Encoded = Base64Encoder.encode( decodedUserInfo ); // sun bug 6459815: Long passwords cause Basic Auth to fail with a java.net.Authenticator base64Encoded = base64Encoded.replaceAll( "\n", "" ); connection.setRequestProperty( "Authorization", "Basic " + base64Encoded ); } return connection; } }
public class class_name { public static URLConnection prepareForAuthentication( final URLConnection connection ) { NullArgumentException.validateNotNull( connection, "url connection cannot be null" ); if( connection.getURL().getUserInfo() != null ) { // Need to decode username/password because it may contain encoded characters (http://www.w3schools.com/tags/ref_urlencode.asp) // A common encoding is to provide a username as an email address like user%40domain.org String decodedUserInfo = decode( connection.getURL().getUserInfo() ); String base64Encoded = Base64Encoder.encode( decodedUserInfo ); // sun bug 6459815: Long passwords cause Basic Auth to fail with a java.net.Authenticator base64Encoded = base64Encoded.replaceAll( "\n", "" ); // depends on control dependency: [if], data = [none] connection.setRequestProperty( "Authorization", "Basic " + base64Encoded ); // depends on control dependency: [if], data = [none] } return connection; } }
public class class_name { private static Map<String, String> getIntrospectedProperties(String clz, URLClassLoader cl, PrintStream error) { Map<String, String> result = null; try { Class<?> c = Class.forName(clz, true, cl); result = new TreeMap<String, String>(); Method[] methods = c.getMethods(); for (Method m : methods) { if (m.getName().startsWith("set") && m.getParameterTypes().length == 1 && isValidType(m.getParameterTypes()[0])) { String name = m.getName().substring(3); if (name.length() == 1) { name = name.toLowerCase(Locale.US); } else { name = name.substring(0, 1).toLowerCase(Locale.US) + name.substring(1); } String type = m.getParameterTypes()[0].getName(); result.put(name, type); } } } catch (Throwable t) { // Nothing we can do t.printStackTrace(error); } return result; } }
public class class_name { private static Map<String, String> getIntrospectedProperties(String clz, URLClassLoader cl, PrintStream error) { Map<String, String> result = null; try { Class<?> c = Class.forName(clz, true, cl); result = new TreeMap<String, String>(); Method[] methods = c.getMethods(); for (Method m : methods) { if (m.getName().startsWith("set") && m.getParameterTypes().length == 1 && isValidType(m.getParameterTypes()[0])) { String name = m.getName().substring(3); if (name.length() == 1) { name = name.toLowerCase(Locale.US); // depends on control dependency: [if], data = [none] } else { name = name.substring(0, 1).toLowerCase(Locale.US) + name.substring(1); // depends on control dependency: [if], data = [1)] } String type = m.getParameterTypes()[0].getName(); result.put(name, type); // depends on control dependency: [if], data = [none] } } } catch (Throwable t) { // Nothing we can do t.printStackTrace(error); } // depends on control dependency: [catch], data = [none] return result; } }
public class class_name { @Override public int compareTo(final RegistrationItem o) { int priorityDiff = 0; if (priority() != null) { if (o.priority() != null) { priorityDiff = priority().level(weight()) - o.priority().level(o.weight()); } else { priorityDiff = 1; } } else { if (o.priority() != null) { priorityDiff = -1; } } return priorityDiff == 0 ? this.implClass().getName().compareTo(o.implClass().getName()) : priorityDiff; } }
public class class_name { @Override public int compareTo(final RegistrationItem o) { int priorityDiff = 0; if (priority() != null) { if (o.priority() != null) { priorityDiff = priority().level(weight()) - o.priority().level(o.weight()); // depends on control dependency: [if], data = [none] } else { priorityDiff = 1; // depends on control dependency: [if], data = [none] } } else { if (o.priority() != null) { priorityDiff = -1; // depends on control dependency: [if], data = [none] } } return priorityDiff == 0 ? this.implClass().getName().compareTo(o.implClass().getName()) : priorityDiff; } }
public class class_name { public static BufferedImage disparity(ImageGray disparity, BufferedImage dst, int minDisparity, int maxDisparity, int invalidColor) { if( dst == null ) dst = new BufferedImage(disparity.getWidth(),disparity.getHeight(),BufferedImage.TYPE_INT_RGB); if (disparity.getDataType().isInteger()) { return disparity((GrayI) disparity, dst, minDisparity, maxDisparity, invalidColor); } else if (disparity instanceof GrayF32) { return disparity((GrayF32) disparity, dst, minDisparity, maxDisparity, invalidColor); } else { throw new RuntimeException("Add support"); } } }
public class class_name { public static BufferedImage disparity(ImageGray disparity, BufferedImage dst, int minDisparity, int maxDisparity, int invalidColor) { if( dst == null ) dst = new BufferedImage(disparity.getWidth(),disparity.getHeight(),BufferedImage.TYPE_INT_RGB); if (disparity.getDataType().isInteger()) { return disparity((GrayI) disparity, dst, minDisparity, maxDisparity, invalidColor); // depends on control dependency: [if], data = [none] } else if (disparity instanceof GrayF32) { return disparity((GrayF32) disparity, dst, minDisparity, maxDisparity, invalidColor); // depends on control dependency: [if], data = [none] } else { throw new RuntimeException("Add support"); } } }
public class class_name { public static Iterator getChildrenByTagName(Element element, String tagName) { if (element == null) return null; // getElementsByTagName gives the corresponding elements in the whole // descendance. We want only children NodeList children = element.getChildNodes(); ArrayList goodChildren = new ArrayList(); for (int i=0; i<children.getLength(); i++) { Node currentChild = children.item(i); if (currentChild.getNodeType() == Node.ELEMENT_NODE && ((Element)currentChild).getTagName().equals(tagName)) { goodChildren.add(currentChild); } } return goodChildren.iterator(); } }
public class class_name { public static Iterator getChildrenByTagName(Element element, String tagName) { if (element == null) return null; // getElementsByTagName gives the corresponding elements in the whole // descendance. We want only children NodeList children = element.getChildNodes(); ArrayList goodChildren = new ArrayList(); for (int i=0; i<children.getLength(); i++) { Node currentChild = children.item(i); if (currentChild.getNodeType() == Node.ELEMENT_NODE && ((Element)currentChild).getTagName().equals(tagName)) { goodChildren.add(currentChild); // depends on control dependency: [if], data = [none] } } return goodChildren.iterator(); } }
public class class_name { public static MigratePartitionLeaderInfo getMigratePartitionLeaderInfo(ZooKeeper zk) { try { byte[] data = zk.getData(migrate_partition_leader_info, null, null); if (data != null) { MigratePartitionLeaderInfo info = new MigratePartitionLeaderInfo(data); return info; } } catch (KeeperException | InterruptedException | JSONException e) { } return null; } }
public class class_name { public static MigratePartitionLeaderInfo getMigratePartitionLeaderInfo(ZooKeeper zk) { try { byte[] data = zk.getData(migrate_partition_leader_info, null, null); if (data != null) { MigratePartitionLeaderInfo info = new MigratePartitionLeaderInfo(data); return info; // depends on control dependency: [if], data = [none] } } catch (KeeperException | InterruptedException | JSONException e) { } // depends on control dependency: [catch], data = [none] return null; } }
public class class_name { @Override public FeatureDao getFeatureDao(GeometryColumns geometryColumns) { if (geometryColumns == null) { throw new GeoPackageException("Non null " + GeometryColumns.class.getSimpleName() + " is required to create " + FeatureDao.class.getSimpleName()); } // Read the existing table and create the dao FeatureTableReader tableReader = new FeatureTableReader(geometryColumns); final FeatureTable featureTable = tableReader.readTable(new FeatureWrapperConnection(database)); featureTable.setContents(geometryColumns.getContents()); FeatureConnection userDb = new FeatureConnection(database); FeatureDao dao = new FeatureDao(getName(), database, userDb, geometryColumns, featureTable); // Register the table name (with and without quotes) to wrap cursors with the feature cursor registerCursorWrapper(geometryColumns.getTableName(), new GeoPackageCursorWrapper() { @Override public Cursor wrapCursor(Cursor cursor) { return new FeatureCursor(featureTable, cursor); } }); // If the GeoPackage is writable and the feature table has a RTree Index // extension, drop the RTree triggers. User defined functions are currently not supported. if (writable) { RTreeIndexExtension rtree = new RTreeIndexExtension(this); rtree.dropTriggers(featureTable); } return dao; } }
public class class_name { @Override public FeatureDao getFeatureDao(GeometryColumns geometryColumns) { if (geometryColumns == null) { throw new GeoPackageException("Non null " + GeometryColumns.class.getSimpleName() + " is required to create " + FeatureDao.class.getSimpleName()); } // Read the existing table and create the dao FeatureTableReader tableReader = new FeatureTableReader(geometryColumns); final FeatureTable featureTable = tableReader.readTable(new FeatureWrapperConnection(database)); featureTable.setContents(geometryColumns.getContents()); FeatureConnection userDb = new FeatureConnection(database); FeatureDao dao = new FeatureDao(getName(), database, userDb, geometryColumns, featureTable); // Register the table name (with and without quotes) to wrap cursors with the feature cursor registerCursorWrapper(geometryColumns.getTableName(), new GeoPackageCursorWrapper() { @Override public Cursor wrapCursor(Cursor cursor) { return new FeatureCursor(featureTable, cursor); } }); // If the GeoPackage is writable and the feature table has a RTree Index // extension, drop the RTree triggers. User defined functions are currently not supported. if (writable) { RTreeIndexExtension rtree = new RTreeIndexExtension(this); rtree.dropTriggers(featureTable); // depends on control dependency: [if], data = [none] } return dao; } }
public class class_name { public static Logger getLogger(Class<?> clazz) { Logger logger = getLogger(clazz.getName()); if (DETECT_LOGGER_NAME_MISMATCH) { Class<?> autoComputedCallingClass = Util.getCallingClass(); if (autoComputedCallingClass != null && nonMatchingClasses(clazz, autoComputedCallingClass)) { Util.report(String.format("Detected logger name mismatch. Given name: \"%s\"; computed name: \"%s\".", logger.getName(), autoComputedCallingClass.getName())); Util.report("See " + LOGGER_NAME_MISMATCH_URL + " for an explanation"); } } return logger; } }
public class class_name { public static Logger getLogger(Class<?> clazz) { Logger logger = getLogger(clazz.getName()); if (DETECT_LOGGER_NAME_MISMATCH) { Class<?> autoComputedCallingClass = Util.getCallingClass(); if (autoComputedCallingClass != null && nonMatchingClasses(clazz, autoComputedCallingClass)) { Util.report(String.format("Detected logger name mismatch. Given name: \"%s\"; computed name: \"%s\".", logger.getName(), autoComputedCallingClass.getName())); // depends on control dependency: [if], data = [none] Util.report("See " + LOGGER_NAME_MISMATCH_URL + " for an explanation"); // depends on control dependency: [if], data = [none] } } return logger; } }
public class class_name { public static int sum( InterleavedS32 img ) { if( BoofConcurrency.USE_CONCURRENT ) { return ImplImageStatistics_MT.sum(img); } else { return ImplImageStatistics.sum(img); } } }
public class class_name { public static int sum( InterleavedS32 img ) { if( BoofConcurrency.USE_CONCURRENT ) { return ImplImageStatistics_MT.sum(img); // depends on control dependency: [if], data = [none] } else { return ImplImageStatistics.sum(img); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void displaySuggestions(boolean display) { // If nothing to change, return early if (display == isDisplayingSuggestions() || mMentionsEditText == null) { return; } // Change view depending on whether suggestions are being shown or not if (display) { disableSpellingSuggestions(true); mTextCounterView.setVisibility(View.GONE); mSuggestionsList.setVisibility(View.VISIBLE); mPrevEditTextParams = mMentionsEditText.getLayoutParams(); mPrevEditTextBottomPadding = mMentionsEditText.getPaddingBottom(); mMentionsEditText.setPadding(mMentionsEditText.getPaddingLeft(), mMentionsEditText.getPaddingTop(), mMentionsEditText.getPaddingRight(), mMentionsEditText.getPaddingTop()); int height = mMentionsEditText.getPaddingTop() + mMentionsEditText.getLineHeight() + mMentionsEditText.getPaddingBottom(); mMentionsEditText.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, height)); mMentionsEditText.setVerticalScrollBarEnabled(false); int cursorLine = getCurrentCursorLine(); Layout layout = mMentionsEditText.getLayout(); if (layout != null) { int lineTop = layout.getLineTop(cursorLine); mMentionsEditText.scrollTo(0, lineTop); } // Notify action listener that list was shown if (mActionListener != null) { mActionListener.onSuggestionsDisplayed(); } } else { disableSpellingSuggestions(false); mTextCounterView.setVisibility(View.VISIBLE); mSuggestionsList.setVisibility(View.GONE); mMentionsEditText.setPadding(mMentionsEditText.getPaddingLeft(), mMentionsEditText.getPaddingTop(), mMentionsEditText.getPaddingRight(), mPrevEditTextBottomPadding); if (mPrevEditTextParams == null) { mPrevEditTextParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); } mMentionsEditText.setLayoutParams(mPrevEditTextParams); mMentionsEditText.setVerticalScrollBarEnabled(true); // Notify action listener that list was hidden if (mActionListener != null) { mActionListener.onSuggestionsHidden(); } } requestLayout(); invalidate(); } }
public class class_name { public void displaySuggestions(boolean display) { // If nothing to change, return early if (display == isDisplayingSuggestions() || mMentionsEditText == null) { return; // depends on control dependency: [if], data = [none] } // Change view depending on whether suggestions are being shown or not if (display) { disableSpellingSuggestions(true); // depends on control dependency: [if], data = [none] mTextCounterView.setVisibility(View.GONE); // depends on control dependency: [if], data = [none] mSuggestionsList.setVisibility(View.VISIBLE); // depends on control dependency: [if], data = [none] mPrevEditTextParams = mMentionsEditText.getLayoutParams(); // depends on control dependency: [if], data = [none] mPrevEditTextBottomPadding = mMentionsEditText.getPaddingBottom(); // depends on control dependency: [if], data = [none] mMentionsEditText.setPadding(mMentionsEditText.getPaddingLeft(), mMentionsEditText.getPaddingTop(), mMentionsEditText.getPaddingRight(), mMentionsEditText.getPaddingTop()); // depends on control dependency: [if], data = [none] int height = mMentionsEditText.getPaddingTop() + mMentionsEditText.getLineHeight() + mMentionsEditText.getPaddingBottom(); mMentionsEditText.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, height)); // depends on control dependency: [if], data = [none] mMentionsEditText.setVerticalScrollBarEnabled(false); // depends on control dependency: [if], data = [none] int cursorLine = getCurrentCursorLine(); Layout layout = mMentionsEditText.getLayout(); if (layout != null) { int lineTop = layout.getLineTop(cursorLine); mMentionsEditText.scrollTo(0, lineTop); // depends on control dependency: [if], data = [none] } // Notify action listener that list was shown if (mActionListener != null) { mActionListener.onSuggestionsDisplayed(); // depends on control dependency: [if], data = [none] } } else { disableSpellingSuggestions(false); // depends on control dependency: [if], data = [none] mTextCounterView.setVisibility(View.VISIBLE); // depends on control dependency: [if], data = [none] mSuggestionsList.setVisibility(View.GONE); // depends on control dependency: [if], data = [none] mMentionsEditText.setPadding(mMentionsEditText.getPaddingLeft(), mMentionsEditText.getPaddingTop(), mMentionsEditText.getPaddingRight(), mPrevEditTextBottomPadding); // depends on control dependency: [if], data = [none] if (mPrevEditTextParams == null) { mPrevEditTextParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); // depends on control dependency: [if], data = [none] } mMentionsEditText.setLayoutParams(mPrevEditTextParams); // depends on control dependency: [if], data = [none] mMentionsEditText.setVerticalScrollBarEnabled(true); // depends on control dependency: [if], data = [none] // Notify action listener that list was hidden if (mActionListener != null) { mActionListener.onSuggestionsHidden(); // depends on control dependency: [if], data = [none] } } requestLayout(); invalidate(); } }
public class class_name { private StyleFilter findStyleFilter(Object feature, List<StyleFilter> styles) { for (StyleFilter styleFilter : styles) { if (styleFilter.getFilter().evaluate(feature)) { return styleFilter; } } return new StyleFilterImpl(); } }
public class class_name { private StyleFilter findStyleFilter(Object feature, List<StyleFilter> styles) { for (StyleFilter styleFilter : styles) { if (styleFilter.getFilter().evaluate(feature)) { return styleFilter; // depends on control dependency: [if], data = [none] } } return new StyleFilterImpl(); } }
public class class_name { @Override public int getIconHeight(SynthContext context) { if (context == null) { return height; } JComponent c = context.getComponent(); if (c instanceof JToolBar) { JToolBar toolbar = (JToolBar) c; if (toolbar.getOrientation() == JToolBar.HORIZONTAL) { // we only do the -1 hack for UIResource borders, assuming // that the border is probably going to be our border if (toolbar.getBorder() instanceof UIResource) { return c.getHeight() - 1; } else { return c.getHeight(); } } else { return scale(context, width); } } else { return scale(context, height); } } }
public class class_name { @Override public int getIconHeight(SynthContext context) { if (context == null) { return height; // depends on control dependency: [if], data = [none] } JComponent c = context.getComponent(); if (c instanceof JToolBar) { JToolBar toolbar = (JToolBar) c; if (toolbar.getOrientation() == JToolBar.HORIZONTAL) { // we only do the -1 hack for UIResource borders, assuming // that the border is probably going to be our border if (toolbar.getBorder() instanceof UIResource) { return c.getHeight() - 1; // depends on control dependency: [if], data = [none] } else { return c.getHeight(); // depends on control dependency: [if], data = [none] } } else { return scale(context, width); // depends on control dependency: [if], data = [none] } } else { return scale(context, height); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void register(String local, String alias) { Map<String, String> map = local.contains("*") || local.contains("?") ? wildcardMap : aliasMap; if (alias == null) { map.remove(local); return; } String oldAlias = map.get(local); if (oldAlias != null) { if (oldAlias.equals(alias)) { return; } if (log.isInfoEnabled()) { log.info(StrUtil.formatMessage("Replaced %s alias for '%s': old value ='%s', new value ='%s'.", getName(), local, oldAlias, alias)); } } map.put(local, alias); } }
public class class_name { public void register(String local, String alias) { Map<String, String> map = local.contains("*") || local.contains("?") ? wildcardMap : aliasMap; if (alias == null) { map.remove(local); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } String oldAlias = map.get(local); if (oldAlias != null) { if (oldAlias.equals(alias)) { return; // depends on control dependency: [if], data = [none] } if (log.isInfoEnabled()) { log.info(StrUtil.formatMessage("Replaced %s alias for '%s': old value ='%s', new value ='%s'.", getName(), local, oldAlias, alias)); // depends on control dependency: [if], data = [none] } } map.put(local, alias); } }
public class class_name { public void updateDistanceMatrix() { // Reset the distance Matrix variable distanceMatrix = new ArrayList<Matrix>(); for (int s = 0; s < size(); s++) { Atom[] ca = atomArrays.get(s); Matrix distMat = AlignUtils.getDistanceMatrix(ca, ca); distanceMatrix.add(distMat); } } }
public class class_name { public void updateDistanceMatrix() { // Reset the distance Matrix variable distanceMatrix = new ArrayList<Matrix>(); for (int s = 0; s < size(); s++) { Atom[] ca = atomArrays.get(s); Matrix distMat = AlignUtils.getDistanceMatrix(ca, ca); distanceMatrix.add(distMat); // depends on control dependency: [for], data = [none] } } }
public class class_name { public static <T> Iterator<T> allSolutions(SearchMethod<T> method) { //return new Filterator<SearchNode<O, T>, T>(allSolutionNodes(method), new ExtractSearchNode<O, T>()); // Take a final reference to the search method to use from within the inner class. final SearchMethod<T> search = method; return new SequenceIterator<T>() { /** * Generates the next element in the search. * * @return The next solution from the search if one is available, or <tt>null</tt> if the search is * complete. */ public T nextInSequence() { try { return search.search(); } catch (SearchNotExhaustiveException e) { // SearchNotExhaustiveException means that the search has completed within its designed parameters // without exhausting the search space. Consequently there are no more solutions to find, // the exception can be ignored and the sequence correctly terminated. e = null; return null; } } }; } }
public class class_name { public static <T> Iterator<T> allSolutions(SearchMethod<T> method) { //return new Filterator<SearchNode<O, T>, T>(allSolutionNodes(method), new ExtractSearchNode<O, T>()); // Take a final reference to the search method to use from within the inner class. final SearchMethod<T> search = method; return new SequenceIterator<T>() { /** * Generates the next element in the search. * * @return The next solution from the search if one is available, or <tt>null</tt> if the search is * complete. */ public T nextInSequence() { try { return search.search(); // depends on control dependency: [try], data = [none] } catch (SearchNotExhaustiveException e) { // SearchNotExhaustiveException means that the search has completed within its designed parameters // without exhausting the search space. Consequently there are no more solutions to find, // the exception can be ignored and the sequence correctly terminated. e = null; return null; } // depends on control dependency: [catch], data = [none] } }; } }
public class class_name { private static int writeUncompressedLength(byte[] compressed, int compressedOffset, int uncompressedLength) { int highBitMask = 0x80; if (uncompressedLength < (1 << 7) && uncompressedLength >= 0) { compressed[compressedOffset++] = (byte) (uncompressedLength); } else if (uncompressedLength < (1 << 14) && uncompressedLength > 0) { compressed[compressedOffset++] = (byte) (uncompressedLength | highBitMask); compressed[compressedOffset++] = (byte) (uncompressedLength >>> 7); } else if (uncompressedLength < (1 << 21) && uncompressedLength > 0) { compressed[compressedOffset++] = (byte) (uncompressedLength | highBitMask); compressed[compressedOffset++] = (byte) ((uncompressedLength >>> 7) | highBitMask); compressed[compressedOffset++] = (byte) (uncompressedLength >>> 14); } else if (uncompressedLength < (1 << 28) && uncompressedLength > 0) { compressed[compressedOffset++] = (byte) (uncompressedLength | highBitMask); compressed[compressedOffset++] = (byte) ((uncompressedLength >>> 7) | highBitMask); compressed[compressedOffset++] = (byte) ((uncompressedLength >>> 14) | highBitMask); compressed[compressedOffset++] = (byte) (uncompressedLength >>> 21); } else { compressed[compressedOffset++] = (byte) (uncompressedLength | highBitMask); compressed[compressedOffset++] = (byte) ((uncompressedLength >>> 7) | highBitMask); compressed[compressedOffset++] = (byte) ((uncompressedLength >>> 14) | highBitMask); compressed[compressedOffset++] = (byte) ((uncompressedLength >>> 21) | highBitMask); compressed[compressedOffset++] = (byte) (uncompressedLength >>> 28); } return compressedOffset; } }
public class class_name { private static int writeUncompressedLength(byte[] compressed, int compressedOffset, int uncompressedLength) { int highBitMask = 0x80; if (uncompressedLength < (1 << 7) && uncompressedLength >= 0) { compressed[compressedOffset++] = (byte) (uncompressedLength); // depends on control dependency: [if], data = [none] } else if (uncompressedLength < (1 << 14) && uncompressedLength > 0) { compressed[compressedOffset++] = (byte) (uncompressedLength | highBitMask); // depends on control dependency: [if], data = [none] compressed[compressedOffset++] = (byte) (uncompressedLength >>> 7); // depends on control dependency: [if], data = [none] } else if (uncompressedLength < (1 << 21) && uncompressedLength > 0) { compressed[compressedOffset++] = (byte) (uncompressedLength | highBitMask); // depends on control dependency: [if], data = [none] compressed[compressedOffset++] = (byte) ((uncompressedLength >>> 7) | highBitMask); // depends on control dependency: [if], data = [none] compressed[compressedOffset++] = (byte) (uncompressedLength >>> 14); // depends on control dependency: [if], data = [none] } else if (uncompressedLength < (1 << 28) && uncompressedLength > 0) { compressed[compressedOffset++] = (byte) (uncompressedLength | highBitMask); // depends on control dependency: [if], data = [none] compressed[compressedOffset++] = (byte) ((uncompressedLength >>> 7) | highBitMask); // depends on control dependency: [if], data = [none] compressed[compressedOffset++] = (byte) ((uncompressedLength >>> 14) | highBitMask); // depends on control dependency: [if], data = [none] compressed[compressedOffset++] = (byte) (uncompressedLength >>> 21); // depends on control dependency: [if], data = [none] } else { compressed[compressedOffset++] = (byte) (uncompressedLength | highBitMask); // depends on control dependency: [if], data = [none] compressed[compressedOffset++] = (byte) ((uncompressedLength >>> 7) | highBitMask); // depends on control dependency: [if], data = [none] compressed[compressedOffset++] = (byte) ((uncompressedLength >>> 14) | highBitMask); // depends on control dependency: [if], data = [none] compressed[compressedOffset++] = (byte) ((uncompressedLength >>> 21) | highBitMask); // depends on control dependency: [if], data = [none] compressed[compressedOffset++] = (byte) (uncompressedLength >>> 28); // depends on control dependency: [if], data = [none] } return compressedOffset; } }
public class class_name { public static <V> double getCohenD(final Map<V, Double> baselineMetricPerDimension, final Map<V, Double> testMetricPerDimension, final boolean doLeastSquares) { SummaryStatistics statsBaseline = new SummaryStatistics(); for (double d : baselineMetricPerDimension.values()) { statsBaseline.addValue(d); } SummaryStatistics statsTest = new SummaryStatistics(); for (double d : testMetricPerDimension.values()) { statsTest.addValue(d); } if (doLeastSquares) { return getCohenDLeastSquares( (int) statsBaseline.getN(), statsBaseline.getMean(), statsBaseline.getStandardDeviation(), (int) statsTest.getN(), statsTest.getMean(), statsTest.getStandardDeviation()); } return getCohenD( (int) statsBaseline.getN(), statsBaseline.getMean(), statsBaseline.getStandardDeviation(), (int) statsTest.getN(), statsTest.getMean(), statsTest.getStandardDeviation()); } }
public class class_name { public static <V> double getCohenD(final Map<V, Double> baselineMetricPerDimension, final Map<V, Double> testMetricPerDimension, final boolean doLeastSquares) { SummaryStatistics statsBaseline = new SummaryStatistics(); for (double d : baselineMetricPerDimension.values()) { statsBaseline.addValue(d); // depends on control dependency: [for], data = [d] } SummaryStatistics statsTest = new SummaryStatistics(); for (double d : testMetricPerDimension.values()) { statsTest.addValue(d); // depends on control dependency: [for], data = [d] } if (doLeastSquares) { return getCohenDLeastSquares( (int) statsBaseline.getN(), statsBaseline.getMean(), statsBaseline.getStandardDeviation(), (int) statsTest.getN(), statsTest.getMean(), statsTest.getStandardDeviation()); // depends on control dependency: [if], data = [none] } return getCohenD( (int) statsBaseline.getN(), statsBaseline.getMean(), statsBaseline.getStandardDeviation(), (int) statsTest.getN(), statsTest.getMean(), statsTest.getStandardDeviation()); } }
public class class_name { void unregisterKvState(KeyGroupRange keyGroupRange) { if (keyGroupRange.getStartKeyGroup() < 0 || keyGroupRange.getEndKeyGroup() >= numKeyGroups) { throw new IndexOutOfBoundsException("Key group index"); } for (int kgIdx = keyGroupRange.getStartKeyGroup(); kgIdx <= keyGroupRange.getEndKeyGroup(); ++kgIdx) { if (kvStateIds[kgIdx] == null || kvStateAddresses[kgIdx] == null) { throw new IllegalArgumentException("Not registered. Probably registration/unregistration race."); } numRegisteredKeyGroups--; kvStateIds[kgIdx] = null; kvStateAddresses[kgIdx] = null; } } }
public class class_name { void unregisterKvState(KeyGroupRange keyGroupRange) { if (keyGroupRange.getStartKeyGroup() < 0 || keyGroupRange.getEndKeyGroup() >= numKeyGroups) { throw new IndexOutOfBoundsException("Key group index"); } for (int kgIdx = keyGroupRange.getStartKeyGroup(); kgIdx <= keyGroupRange.getEndKeyGroup(); ++kgIdx) { if (kvStateIds[kgIdx] == null || kvStateAddresses[kgIdx] == null) { throw new IllegalArgumentException("Not registered. Probably registration/unregistration race."); } numRegisteredKeyGroups--; // depends on control dependency: [for], data = [none] kvStateIds[kgIdx] = null; // depends on control dependency: [for], data = [kgIdx] kvStateAddresses[kgIdx] = null; // depends on control dependency: [for], data = [kgIdx] } } }
public class class_name { @Override public void serializePrimitive(IntSumRecord rec, String fieldName, Object value) { /// only interested in int values. if(value instanceof Integer) { rec.addValue(((Integer) value).intValue()); } } }
public class class_name { @Override public void serializePrimitive(IntSumRecord rec, String fieldName, Object value) { /// only interested in int values. if(value instanceof Integer) { rec.addValue(((Integer) value).intValue()); // depends on control dependency: [if], data = [none] } } }
public class class_name { protected void slowScan() { synchronized (slowScanLock) { if (haveSlowResults) { return; } if (slowScanning) { while (slowScanning) { try { slowScanLock.wait(); } catch (InterruptedException e) { // Empty } } return; } slowScanning = true; } try { synchronized (this) { // set in/excludes to reasonable defaults if needed: boolean nullIncludes = (includes == null); includes = nullIncludes ? new String[] {"**"} : includes; boolean nullExcludes = (excludes == null); excludes = nullExcludes ? new String[0] : excludes; String[] excl = new String[dirsExcluded.size()]; dirsExcluded.copyInto(excl); String[] notIncl = new String[dirsNotIncluded.size()]; dirsNotIncluded.copyInto(notIncl); processSlowScan(excl); processSlowScan(notIncl); clearCaches(); includes = nullIncludes ? null : includes; excludes = nullExcludes ? null : excludes; } } finally { synchronized (slowScanLock) { haveSlowResults = true; slowScanning = false; slowScanLock.notifyAll(); } } } }
public class class_name { protected void slowScan() { synchronized (slowScanLock) { if (haveSlowResults) { return; // depends on control dependency: [if], data = [none] } if (slowScanning) { while (slowScanning) { try { slowScanLock.wait(); // depends on control dependency: [try], data = [none] } catch (InterruptedException e) { // Empty } // depends on control dependency: [catch], data = [none] } return; // depends on control dependency: [if], data = [none] } slowScanning = true; } try { synchronized (this) { // depends on control dependency: [try], data = [none] // set in/excludes to reasonable defaults if needed: boolean nullIncludes = (includes == null); includes = nullIncludes ? new String[] {"**"} : includes; boolean nullExcludes = (excludes == null); excludes = nullExcludes ? new String[0] : excludes; String[] excl = new String[dirsExcluded.size()]; dirsExcluded.copyInto(excl); String[] notIncl = new String[dirsNotIncluded.size()]; dirsNotIncluded.copyInto(notIncl); processSlowScan(excl); processSlowScan(notIncl); clearCaches(); includes = nullIncludes ? null : includes; excludes = nullExcludes ? null : excludes; } } finally { synchronized (slowScanLock) { haveSlowResults = true; slowScanning = false; slowScanLock.notifyAll(); } } } }
public class class_name { public static EUI64 fromString(String name) { long bits = 0; char sep = 0; for (int n = 0;; ++n) { if (n == name.length()) { if (n == 23) { return new EUI64(bits); } else { break; } } char c = name.charAt(n); if (n == 2) { if (c != ':' && c != '-') { break; } sep = c; } else if ((n - 2) % 3 == 0) { if (c != sep) { break; } } else if (c >= '0' && c <= '9') { bits = (bits << 4) | (c - '0'); } else if (c >= 'a' && c <= 'f') { bits = (bits << 4) | (10 + c - 'a'); } else if (c >= 'A' && c <= 'F') { bits = (bits << 4) | (10 + c - 'A'); } else { break; } } throw new IllegalArgumentException("Invalid EUI-64 string: " + name); } }
public class class_name { public static EUI64 fromString(String name) { long bits = 0; char sep = 0; for (int n = 0;; ++n) { if (n == name.length()) { if (n == 23) { return new EUI64(bits); // depends on control dependency: [if], data = [none] } else { break; } } char c = name.charAt(n); if (n == 2) { if (c != ':' && c != '-') { break; } sep = c; // depends on control dependency: [if], data = [none] } else if ((n - 2) % 3 == 0) { if (c != sep) { break; } } else if (c >= '0' && c <= '9') { bits = (bits << 4) | (c - '0'); // depends on control dependency: [if], data = [(c] } else if (c >= 'a' && c <= 'f') { bits = (bits << 4) | (10 + c - 'a'); // depends on control dependency: [if], data = [none] } else if (c >= 'A' && c <= 'F') { bits = (bits << 4) | (10 + c - 'A'); // depends on control dependency: [if], data = [none] } else { break; } } throw new IllegalArgumentException("Invalid EUI-64 string: " + name); } }
public class class_name { public void push(AbstractDrawer drawer, AjaxRequestTarget target, String cssClass) { ListItem item = new ListItem("next", drawer, this, cssClass); drawers.push(item); if (first == null) { first = item; addOrReplace(first); } else { ListItem iter = first; while (iter.next != null) { iter = iter.next; } iter.add(item); } if (target!=null) { target.add(item); target.appendJavaScript("$('#"+item.item.getMarkupId()+"').modaldrawer('show');"); if (item.previous!=null) { target.appendJavaScript("$('#"+item.previous.item.getMarkupId()+"').removeClass('shown-modal');"); target.appendJavaScript("$('#"+item.previous.item.getMarkupId()+"').addClass('hidden-modal');"); } } drawer.setManager(this); } }
public class class_name { public void push(AbstractDrawer drawer, AjaxRequestTarget target, String cssClass) { ListItem item = new ListItem("next", drawer, this, cssClass); drawers.push(item); if (first == null) { first = item; // depends on control dependency: [if], data = [none] addOrReplace(first); // depends on control dependency: [if], data = [(first] } else { ListItem iter = first; while (iter.next != null) { iter = iter.next; // depends on control dependency: [while], data = [none] } iter.add(item); // depends on control dependency: [if], data = [none] } if (target!=null) { target.add(item); // depends on control dependency: [if], data = [none] target.appendJavaScript("$('#"+item.item.getMarkupId()+"').modaldrawer('show');"); // depends on control dependency: [if], data = [none] if (item.previous!=null) { target.appendJavaScript("$('#"+item.previous.item.getMarkupId()+"').removeClass('shown-modal');"); // depends on control dependency: [if], data = [none] target.appendJavaScript("$('#"+item.previous.item.getMarkupId()+"').addClass('hidden-modal');"); // depends on control dependency: [if], data = [none] } } drawer.setManager(this); } }
public class class_name { public boolean checkPermission(Principal user, int operation) { if (tc.isEntryEnabled()) SibTr.entry(tc, "checkPermission", new Object[]{user, new Integer(operation)}); boolean allowed = false; if(operation == 1) // a publish operation { // check whether permission has been granted to special group Everyone. // We can do this before we check whether the user is authenticated if(accumGroupAllowedToPublish.size() > 0 && accumGroupAllowedToPublish.contains(everyone)) { allowed = true; } // Now check whether the user is authenticated, ie we have a username else if (user.getName() != null && user.getName().length() > 0) { // User is authenticated // Check user list next if(accumUsersAllowedToPublish.size() > 0 && accumUsersAllowedToPublish.contains(user)) { allowed = true; } else // Now check the groups { if(accumGroupAllowedToPublish.size() > 0) { // user hasn't been granted access directly, check the groups // check for AllAuthenticated first if (accumGroupAllowedToPublish.contains(allAuthenticated)) { allowed = true; } else { Iterator itr = accumGroupAllowedToPublish.iterator(); while (itr.hasNext()) { Group group = (Group)itr.next(); if(group.isMember(user)) { allowed = true; break; } } // eof while } } } } } else // a subscribe operation { // check whether permission has been granted to special group Everyone. // We can do this before we check whether the user is authenticated if(accumGroupAllowedToSubscribe.size() > 0 && accumGroupAllowedToSubscribe.contains(everyone)) { allowed = true; } // Now check whether the user is authenticated, ie we have a username else if (user.getName() != null && user.getName().length() > 0) { // User is authenticated // Check user list next if(accumUsersAllowedToSubscribe.size() > 0 && accumUsersAllowedToSubscribe.contains(user)) { allowed = true; } else // Now check the groups { if(accumGroupAllowedToSubscribe.size() > 0) { // user hasn't been granted access directly, check the groups // check for AllAuthenticated first if (accumGroupAllowedToSubscribe.contains(allAuthenticated)) { allowed = true; } else { Iterator itr = accumGroupAllowedToSubscribe.iterator(); while (itr.hasNext()) { Group group = (Group)itr.next(); if(group.isMember(user)) { allowed = true; break; } } } } } } } if (tc.isEntryEnabled()) SibTr.exit(tc, "checkPermission", new Boolean(allowed)); return allowed; } }
public class class_name { public boolean checkPermission(Principal user, int operation) { if (tc.isEntryEnabled()) SibTr.entry(tc, "checkPermission", new Object[]{user, new Integer(operation)}); boolean allowed = false; if(operation == 1) // a publish operation { // check whether permission has been granted to special group Everyone. // We can do this before we check whether the user is authenticated if(accumGroupAllowedToPublish.size() > 0 && accumGroupAllowedToPublish.contains(everyone)) { allowed = true; // depends on control dependency: [if], data = [none] } // Now check whether the user is authenticated, ie we have a username else if (user.getName() != null && user.getName().length() > 0) { // User is authenticated // Check user list next if(accumUsersAllowedToPublish.size() > 0 && accumUsersAllowedToPublish.contains(user)) { allowed = true; // depends on control dependency: [if], data = [none] } else // Now check the groups { if(accumGroupAllowedToPublish.size() > 0) { // user hasn't been granted access directly, check the groups // check for AllAuthenticated first if (accumGroupAllowedToPublish.contains(allAuthenticated)) { allowed = true; // depends on control dependency: [if], data = [none] } else { Iterator itr = accumGroupAllowedToPublish.iterator(); while (itr.hasNext()) { Group group = (Group)itr.next(); if(group.isMember(user)) { allowed = true; // depends on control dependency: [if], data = [none] break; } } // eof while } } } } } else // a subscribe operation { // check whether permission has been granted to special group Everyone. // We can do this before we check whether the user is authenticated if(accumGroupAllowedToSubscribe.size() > 0 && accumGroupAllowedToSubscribe.contains(everyone)) { allowed = true; // depends on control dependency: [if], data = [none] } // Now check whether the user is authenticated, ie we have a username else if (user.getName() != null && user.getName().length() > 0) { // User is authenticated // Check user list next if(accumUsersAllowedToSubscribe.size() > 0 && accumUsersAllowedToSubscribe.contains(user)) { allowed = true; // depends on control dependency: [if], data = [none] } else // Now check the groups { if(accumGroupAllowedToSubscribe.size() > 0) { // user hasn't been granted access directly, check the groups // check for AllAuthenticated first if (accumGroupAllowedToSubscribe.contains(allAuthenticated)) { allowed = true; // depends on control dependency: [if], data = [none] } else { Iterator itr = accumGroupAllowedToSubscribe.iterator(); while (itr.hasNext()) { Group group = (Group)itr.next(); if(group.isMember(user)) { allowed = true; // depends on control dependency: [if], data = [none] break; } } } } } } } if (tc.isEntryEnabled()) SibTr.exit(tc, "checkPermission", new Boolean(allowed)); return allowed; } }
public class class_name { public int[] set(ReadablePartial partial, int fieldIndex, int[] values, int newValue) { FieldUtils.verifyValueBounds(this, newValue, getMinimumValue(partial, values), getMaximumValue(partial, values)); values[fieldIndex] = newValue; // may need to adjust smaller fields for (int i = fieldIndex + 1; i < partial.size(); i++) { DateTimeField field = partial.getField(i); if (values[i] > field.getMaximumValue(partial, values)) { values[i] = field.getMaximumValue(partial, values); } if (values[i] < field.getMinimumValue(partial, values)) { values[i] = field.getMinimumValue(partial, values); } } return values; } }
public class class_name { public int[] set(ReadablePartial partial, int fieldIndex, int[] values, int newValue) { FieldUtils.verifyValueBounds(this, newValue, getMinimumValue(partial, values), getMaximumValue(partial, values)); values[fieldIndex] = newValue; // may need to adjust smaller fields for (int i = fieldIndex + 1; i < partial.size(); i++) { DateTimeField field = partial.getField(i); if (values[i] > field.getMaximumValue(partial, values)) { values[i] = field.getMaximumValue(partial, values); // depends on control dependency: [if], data = [none] } if (values[i] < field.getMinimumValue(partial, values)) { values[i] = field.getMinimumValue(partial, values); // depends on control dependency: [if], data = [none] } } return values; } }
public class class_name { private int fillLine(int maxLen) throws IOException { _mark=_pos; if (_pos>=_avail) fill(); if (_pos>=_avail) return -1; byte b; boolean cr=_lastCr; boolean lf=false; _lastCr=false; int len=0; LineLoop: while (_pos<=_avail) { // if we have gone past the end of the buffer while (_pos==_avail) { // If EOF or no more space in the buffer, // return a line. if (_eof || (_mark==0 && _contents==_buf.length)) { _lastCr=!_eof && _buf[_avail-1]==CR; cr=true; lf=true; break LineLoop; } // If we have a CR and no more characters are available if (cr && in.available()==0 && !_seenCrLf) { _lastCr=true; cr=true; lf=true; break LineLoop; } else { // Else just wait for more... _pos=_mark; fill(); _pos=len; cr=false; } } // Get the byte b=_buf[_pos++]; switch(b) { case LF: if (cr) _seenCrLf=true; lf=true; break LineLoop; case CR: if (cr) { // Double CR if (_pos>1) { _pos--; break LineLoop; } } cr=true; break; default: if(cr) { if (_pos==1) cr=false; else { _pos--; break LineLoop; } } len++; if (len==maxLen) { // look for EOL if (_mark!=0 && _pos+2>=_avail && _avail<_buf.length) fill(); if (_pos<_avail && _buf[_pos]==CR) { cr=true; _pos++; } if (_pos<_avail && _buf[_pos]==LF) { lf=true; _pos++; } if (!cr && !lf) { // fake EOL lf=true; cr=true; } break LineLoop; } break; } } if (!cr && !lf && len==0) len=-1; return len; } }
public class class_name { private int fillLine(int maxLen) throws IOException { _mark=_pos; if (_pos>=_avail) fill(); if (_pos>=_avail) return -1; byte b; boolean cr=_lastCr; boolean lf=false; _lastCr=false; int len=0; LineLoop: while (_pos<=_avail) { // if we have gone past the end of the buffer while (_pos==_avail) { // If EOF or no more space in the buffer, // return a line. if (_eof || (_mark==0 && _contents==_buf.length)) { _lastCr=!_eof && _buf[_avail-1]==CR; // depends on control dependency: [if], data = [none] cr=true; // depends on control dependency: [if], data = [none] lf=true; // depends on control dependency: [if], data = [none] break LineLoop; } // If we have a CR and no more characters are available if (cr && in.available()==0 && !_seenCrLf) { _lastCr=true; // depends on control dependency: [if], data = [none] cr=true; // depends on control dependency: [if], data = [none] lf=true; // depends on control dependency: [if], data = [none] break LineLoop; } else { // Else just wait for more... _pos=_mark; // depends on control dependency: [if], data = [none] fill(); // depends on control dependency: [if], data = [none] _pos=len; // depends on control dependency: [if], data = [none] cr=false; // depends on control dependency: [if], data = [none] } } // Get the byte b=_buf[_pos++]; switch(b) { case LF: if (cr) _seenCrLf=true; lf=true; break LineLoop; case CR: if (cr) { // Double CR if (_pos>1) { _pos--; // depends on control dependency: [if], data = [none] break LineLoop; } } cr=true; break; default: if(cr) { if (_pos==1) cr=false; else { _pos--; // depends on control dependency: [if], data = [none] break LineLoop; } } len++; if (len==maxLen) { // look for EOL if (_mark!=0 && _pos+2>=_avail && _avail<_buf.length) fill(); if (_pos<_avail && _buf[_pos]==CR) { cr=true; // depends on control dependency: [if], data = [none] _pos++; // depends on control dependency: [if], data = [none] } if (_pos<_avail && _buf[_pos]==LF) { lf=true; // depends on control dependency: [if], data = [none] _pos++; // depends on control dependency: [if], data = [none] } if (!cr && !lf) { // fake EOL lf=true; // depends on control dependency: [if], data = [none] cr=true; // depends on control dependency: [if], data = [none] } break LineLoop; } break; } } if (!cr && !lf && len==0) len=-1; return len; } }
public class class_name { public Collection<String> getDeadNodes() { List<String> activeHosts = new ArrayList<String>(); synchronized(taskTrackers) { for (TaskTracker tt : taskTrackers.values()) { activeHosts.add(tt.getStatus().getHost()); } } // dead hosts are the difference between active and known hosts // We don't consider a blacklisted host to be dead. Set<String> knownHosts = new HashSet<String>(hostsReader.getHosts()); knownHosts.removeAll(activeHosts); // Also remove the excluded nodes as getHosts() returns them as well knownHosts.removeAll(hostsReader.getExcludedHosts()); Set<String> deadHosts = knownHosts; return deadHosts; } }
public class class_name { public Collection<String> getDeadNodes() { List<String> activeHosts = new ArrayList<String>(); synchronized(taskTrackers) { for (TaskTracker tt : taskTrackers.values()) { activeHosts.add(tt.getStatus().getHost()); // depends on control dependency: [for], data = [tt] } } // dead hosts are the difference between active and known hosts // We don't consider a blacklisted host to be dead. Set<String> knownHosts = new HashSet<String>(hostsReader.getHosts()); knownHosts.removeAll(activeHosts); // Also remove the excluded nodes as getHosts() returns them as well knownHosts.removeAll(hostsReader.getExcludedHosts()); Set<String> deadHosts = knownHosts; return deadHosts; } }
public class class_name { public final void setCustomer(final DebtorCreditor pCustomer) { this.customer = pCustomer; if (this.itsId == null) { this.itsId = new CustomerGoodsSeenId(); } this.itsId.setCustomer(this.customer); } }
public class class_name { public final void setCustomer(final DebtorCreditor pCustomer) { this.customer = pCustomer; if (this.itsId == null) { this.itsId = new CustomerGoodsSeenId(); // depends on control dependency: [if], data = [none] } this.itsId.setCustomer(this.customer); } }
public class class_name { @Override public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { if (src == null) { return JsonNull.INSTANCE; } else { return new JsonPrimitive(apiClient.formatDatetime(src)); } } }
public class class_name { @Override public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { if (src == null) { return JsonNull.INSTANCE; // depends on control dependency: [if], data = [none] } else { return new JsonPrimitive(apiClient.formatDatetime(src)); // depends on control dependency: [if], data = [(src] } } }
public class class_name { public Type resolveType(Type type) { checkNotNull(type); if (type instanceof TypeVariable) { return typeTable.resolve((TypeVariable<?>) type); } else if (type instanceof ParameterizedType) { return resolveParameterizedType((ParameterizedType) type); } else if (type instanceof GenericArrayType) { return resolveGenericArrayType((GenericArrayType) type); } else if (type instanceof WildcardType) { return resolveWildcardType((WildcardType) type); } else { // if Class<?>, no resolution needed, we are done. return type; } } }
public class class_name { public Type resolveType(Type type) { checkNotNull(type); if (type instanceof TypeVariable) { return typeTable.resolve((TypeVariable<?>) type); // depends on control dependency: [if], data = [none] } else if (type instanceof ParameterizedType) { return resolveParameterizedType((ParameterizedType) type); // depends on control dependency: [if], data = [none] } else if (type instanceof GenericArrayType) { return resolveGenericArrayType((GenericArrayType) type); // depends on control dependency: [if], data = [none] } else if (type instanceof WildcardType) { return resolveWildcardType((WildcardType) type); // depends on control dependency: [if], data = [none] } else { // if Class<?>, no resolution needed, we are done. return type; // depends on control dependency: [if], data = [none] } } }
public class class_name { private String findLabelFor(Entity pe) { // Use gene symbol of PE for (Xref xref : pe.getXref()) { String sym = extractGeneSymbol(xref); if (sym != null) return sym; } // Use gene symbol of ER EntityReference er = null; if (pe instanceof SimplePhysicalEntity) { er = ((SimplePhysicalEntity) pe).getEntityReference(); } if (er != null) { for (Xref xref : er.getXref()) { String sym = extractGeneSymbol(xref); if (sym != null) return sym; } } // Use display name of entity String name = pe.getDisplayName(); if (name == null || name.trim().isEmpty()) { if (er != null) { name = er.getDisplayName(); } if (name == null || name.trim().isEmpty()) { name = pe.getStandardName(); if (name == null || name.trim().isEmpty()) { if (er != null) { name = er.getStandardName(); } if (name == null || name.trim().isEmpty()) { if (!pe.getName().isEmpty()) { // Use first name of entity name = pe.getName().iterator().next(); } else if (er != null && !er.getName().isEmpty()) { // Use first name of reference name = er.getName().iterator().next(); } } } } } // Search for the shortest name of chemicals if (pe instanceof SmallMolecule) { String shortName = getShortestName((SmallMolecule) pe); if (shortName != null) { if (name == null || (shortName.length() < name.length() && !shortName.isEmpty())) { name = shortName; } } } if (name == null || name.trim().isEmpty()) { // Don't leave it without a name name = "noname"; } return name; } }
public class class_name { private String findLabelFor(Entity pe) { // Use gene symbol of PE for (Xref xref : pe.getXref()) { String sym = extractGeneSymbol(xref); if (sym != null) return sym; } // Use gene symbol of ER EntityReference er = null; if (pe instanceof SimplePhysicalEntity) { er = ((SimplePhysicalEntity) pe).getEntityReference(); // depends on control dependency: [if], data = [none] } if (er != null) { for (Xref xref : er.getXref()) { String sym = extractGeneSymbol(xref); if (sym != null) return sym; } } // Use display name of entity String name = pe.getDisplayName(); if (name == null || name.trim().isEmpty()) { if (er != null) { name = er.getDisplayName(); // depends on control dependency: [if], data = [none] } if (name == null || name.trim().isEmpty()) { name = pe.getStandardName(); // depends on control dependency: [if], data = [none] if (name == null || name.trim().isEmpty()) { if (er != null) { name = er.getStandardName(); // depends on control dependency: [if], data = [none] } if (name == null || name.trim().isEmpty()) { if (!pe.getName().isEmpty()) { // Use first name of entity name = pe.getName().iterator().next(); // depends on control dependency: [if], data = [none] } else if (er != null && !er.getName().isEmpty()) { // Use first name of reference name = er.getName().iterator().next(); // depends on control dependency: [if], data = [none] } } } } } // Search for the shortest name of chemicals if (pe instanceof SmallMolecule) { String shortName = getShortestName((SmallMolecule) pe); if (shortName != null) { if (name == null || (shortName.length() < name.length() && !shortName.isEmpty())) { name = shortName; // depends on control dependency: [if], data = [none] } } } if (name == null || name.trim().isEmpty()) { // Don't leave it without a name name = "noname"; // depends on control dependency: [if], data = [none] } return name; } }
public class class_name { public Cursor rawQuery(String sql, String[] makeArgListQueryString) throws SQLException { Log.v("SQLiteDatabase rawQuery: " + Thread.currentThread().getId() + " \"" + Thread.currentThread().getName() + "\" " + sql); long timeNow = System.currentTimeMillis(); long delta = 0; do { try { Cursor cursor = sqliteDatabase.rawQuery(sql, makeArgListQueryString); Log.v("SQLiteDatabase rawQuery OK: " + Thread.currentThread().getId() + " \"" + Thread.currentThread().getName() + "\" " + sql); return cursor; } catch (SQLiteException e) { if ( isLockedException(e) ) { delta = System.currentTimeMillis() - timeNow; } else { throw SQLDroidConnection.chainException(e); } } } while (delta < timeout); throw new SQLException ("Timeout Expired"); } }
public class class_name { public Cursor rawQuery(String sql, String[] makeArgListQueryString) throws SQLException { Log.v("SQLiteDatabase rawQuery: " + Thread.currentThread().getId() + " \"" + Thread.currentThread().getName() + "\" " + sql); long timeNow = System.currentTimeMillis(); long delta = 0; do { try { Cursor cursor = sqliteDatabase.rawQuery(sql, makeArgListQueryString); Log.v("SQLiteDatabase rawQuery OK: " + Thread.currentThread().getId() + " \"" + Thread.currentThread().getName() + "\" " + sql); // depends on control dependency: [try], data = [none] return cursor; // depends on control dependency: [try], data = [none] } catch (SQLiteException e) { if ( isLockedException(e) ) { delta = System.currentTimeMillis() - timeNow; // depends on control dependency: [if], data = [none] } else { throw SQLDroidConnection.chainException(e); } } // depends on control dependency: [catch], data = [none] } while (delta < timeout); throw new SQLException ("Timeout Expired"); } }
public class class_name { public void generateRandom( int nbPoints, float minX, float maxX, float minY, float maxY ) { xs = new ArrayList<Float>(); ys = new ArrayList<Float>(); for( int i = 0; i < nbPoints; i++ ) { float r = (float) Math.random(); r = (float) (((int) (r * 100)) / 100.0); xs.add( minX + (i * (maxX - minX) / (nbPoints - 1)) ); ys.add( minY + r * (maxY - minY) ); } } }
public class class_name { public void generateRandom( int nbPoints, float minX, float maxX, float minY, float maxY ) { xs = new ArrayList<Float>(); ys = new ArrayList<Float>(); for( int i = 0; i < nbPoints; i++ ) { float r = (float) Math.random(); r = (float) (((int) (r * 100)) / 100.0); // depends on control dependency: [for], data = [none] xs.add( minX + (i * (maxX - minX) / (nbPoints - 1)) ); // depends on control dependency: [for], data = [i] ys.add( minY + r * (maxY - minY) ); // depends on control dependency: [for], data = [none] } } }
public class class_name { private void buildDecoding(Mode mode, CodeAssembler a, StorableProperty<S>[] properties, Direction[] directions, LocalVariable instanceVar, Class<?> adapterInstanceClass, boolean useWriteMethods, int generation, Label altGenerationHandler, LocalVariable encodedVar) throws SupportException { if (a == null) { throw new IllegalArgumentException(); } if (encodedVar == null || encodedVar.getType() != TypeDesc.forClass(byte[].class)) { throw new IllegalArgumentException(); } // Decoding order is: // // 1. Prefix // 2. Generation prefix // 3. Property states (if Mode.SERIAL) // 4. Properties // 5. Suffix final int prefix; switch (mode) { default: prefix = 0; break; case KEY: prefix = mKeyPrefixPadding; break; case DATA: prefix = mDataPrefixPadding; break; } decodeGeneration(a, encodedVar, prefix, generation, altGenerationHandler); final int generationPrefix; if (generation < 0) { generationPrefix = 0; } else if (generation < 128) { generationPrefix = 1; } else { generationPrefix = 4; } final int suffix; switch (mode) { default: suffix = 0; break; case KEY: suffix = mKeySuffixPadding; break; case DATA: suffix = mDataSuffixPadding; extraDataDecoding(a, encodedVar, prefix + generationPrefix, suffix); break; } final TypeDesc byteArrayType = TypeDesc.forClass(byte[].class); StorablePropertyInfo[] infos = checkSupport(properties); if (properties.length == 1) { StorableProperty<S> property = properties[0]; StorablePropertyInfo info = infos[0]; if (mode != Mode.SERIAL && info.getStorageType().toClass() == byte[].class) { // Since there is only one property, and it is just a byte // array, it doesn't have any fancy encoding. // Push to stack in preparation for storing a property. pushDecodingInstanceVar(a, 0, instanceVar); a.loadLocal(encodedVar); boolean descending = mode == Mode.KEY && directions != null && directions[0] == Direction.DESCENDING; TypeDesc[] params; if (prefix > 0 || generationPrefix > 0 || suffix > 0) { a.loadConstant(prefix + generationPrefix); a.loadConstant(suffix); params = new TypeDesc[] {byteArrayType, TypeDesc.INT, TypeDesc.INT}; } else { params = new TypeDesc[] {byteArrayType}; } if (property.isNullable()) { if (descending) { a.invokeStatic(KeyDecoder.class.getName(), "decodeSingleNullableDesc", byteArrayType, params); } else { a.invokeStatic(DataDecoder.class.getName(), "decodeSingleNullable", byteArrayType, params); } } else if (descending) { a.invokeStatic(KeyDecoder.class.getName(), "decodeSingleDesc", byteArrayType, params); } else if (prefix > 0 || generationPrefix > 0 || suffix > 0) { a.invokeStatic(DataDecoder.class.getName(), "decodeSingle", byteArrayType, params); } else { // Always clone the byte array as some implementations // reuse the byte array (e.g. iterating using a cursor). a.invokeVirtual(TypeDesc.OBJECT, "clone", TypeDesc.OBJECT, null); a.checkCast(byteArrayType); } storePropertyValue(a, info, useWriteMethods, instanceVar, adapterInstanceClass); return; } } // Now decode properties from the byte array. int constantOffset = prefix + generationPrefix; LocalVariable offsetVar = null; // References to local variables which will hold references. LocalVariable[] stringRefRef = new LocalVariable[1]; LocalVariable[] byteArrayRefRef = new LocalVariable[1]; LocalVariable[] bigIntegerRefRef = new LocalVariable[1]; LocalVariable[] bigDecimalRefRef = new LocalVariable[1]; LocalVariable[] valueRefRef = new LocalVariable[1]; // Used by SERIAL mode. List<LocalVariable> stateVars = null; if (mode == Mode.SERIAL) { stateVars = decodePropertyStates(a, encodedVar, constantOffset, properties); constantOffset += (properties.length + 3) / 4; // Some properties are skipped at runtime, so offset variable is required. offsetVar = a.createLocalVariable(null, TypeDesc.INT); a.loadConstant(constantOffset); a.storeLocal(offsetVar); // References need to be initialized early because some properties // are skipped at runtime. for (int i=0; i<properties.length; i++) { TypeDesc storageType = infos[i].getStorageType(); if (storageType == TypeDesc.STRING) { if (stringRefRef[0] == null) { TypeDesc refType = TypeDesc.forClass(String[].class); stringRefRef[0] = a.createLocalVariable(null, refType); a.loadConstant(1); a.newObject(refType); a.storeLocal(stringRefRef[0]); } } else if (storageType.toClass() == byte[].class) { if (byteArrayRefRef[0] == null) { TypeDesc refType = TypeDesc.forClass(byte[][].class); byteArrayRefRef[0] = a.createLocalVariable(null, refType); a.loadConstant(1); a.newObject(refType); a.storeLocal(byteArrayRefRef[0]); } } else if (storageType.toClass() == BigInteger.class) { if (bigIntegerRefRef[0] == null) { TypeDesc refType = TypeDesc.forClass(BigInteger[].class); bigIntegerRefRef[0] = a.createLocalVariable(null, refType); a.loadConstant(1); a.newObject(refType); a.storeLocal(bigIntegerRefRef[0]); } } else if (storageType.toClass() == BigDecimal.class) { if (bigDecimalRefRef[0] == null) { TypeDesc refType = TypeDesc.forClass(BigDecimal[].class); bigDecimalRefRef[0] = a.createLocalVariable(null, refType); a.loadConstant(1); a.newObject(refType); a.storeLocal(bigDecimalRefRef[0]); } } } } for (int i=0; i<properties.length; i++) { StorableProperty<S> property = properties[i]; StorablePropertyInfo info = infos[i]; Label storePropertyLocation = a.createLabel(); Label nextPropertyLocation = a.createLabel(); // Push to stack in preparation for storing a property. pushDecodingInstanceVar(a, i, instanceVar); if (mode == Mode.SERIAL) { // Load property if initialized, else reset it. a.loadLocal(stateVars.get(property.getNumber() >> 4)); a.loadConstant(PROPERTY_STATE_MASK << ((property.getNumber() & 0xf) * 2)); a.math(Opcode.IAND); Label isInitialized = a.createLabel(); a.ifZeroComparisonBranch(isInitialized, "!="); // Reset property value to zero, false, or null. loadBlankValue(a, TypeDesc.forClass(property.getType())); if (info.getToStorageAdapter() != null) { // Bypass adapter. a.storeField(info.getPropertyName(), info.getPropertyType()); a.branch(nextPropertyLocation); } else { a.branch(storePropertyLocation); } isInitialized.setLocation(); } TypeDesc storageType = info.getStorageType(); if (info.isLob()) { // Need RawSupport instance for getting Lob from locator. pushRawSupport(a, instanceVar); // Also need to pass this stuff along when getting Lob. a.loadThis(); a.loadConstant(info.getPropertyName()); // Locator is encoded as a long. storageType = TypeDesc.LONG; } a.loadLocal(encodedVar); if (offsetVar == null) { a.loadConstant(constantOffset); } else { a.loadLocal(offsetVar); } boolean descending = mode == Mode.KEY && directions != null && directions[i] == Direction.DESCENDING; int amt = decodeProperty(a, info, storageType, mode, descending, // TODO: do something better for passing these refs stringRefRef, byteArrayRefRef, bigIntegerRefRef, bigDecimalRefRef, valueRefRef); if (info.isLob()) { getLobFromLocator(a, info); } if (amt != 0) { if (i + 1 < properties.length) { // Only adjust offset if there are more properties. if (amt > 0) { if (offsetVar == null) { constantOffset += amt; } else { a.loadConstant(amt); a.loadLocal(offsetVar); a.math(Opcode.IADD); a.storeLocal(offsetVar); } } else { // Offset adjust is one if returned object is null. a.dup(); Label notNull = a.createLabel(); a.ifNullBranch(notNull, false); a.loadConstant(1 + (offsetVar == null ? constantOffset : 0)); Label cont = a.createLabel(); a.branch(cont); notNull.setLocation(); a.loadConstant(~amt + (offsetVar == null ? constantOffset : 0)); cont.setLocation(); if (offsetVar == null) { offsetVar = a.createLocalVariable(null, TypeDesc.INT); } else { a.loadLocal(offsetVar); a.math(Opcode.IADD); } a.storeLocal(offsetVar); } } } else { if (i + 1 >= properties.length) { // Don't need to keep track of offset anymore. a.pop(); } else { // Only adjust offset if there are more properties. if (offsetVar == null) { if (constantOffset > 0) { a.loadConstant(constantOffset); a.math(Opcode.IADD); } offsetVar = a.createLocalVariable(null, TypeDesc.INT); } else { a.loadLocal(offsetVar); a.math(Opcode.IADD); } a.storeLocal(offsetVar); } // Get the value out of the ref array so that it can be stored. a.loadLocal(valueRefRef[0]); a.loadConstant(0); a.loadFromArray(valueRefRef[0].getType()); } storePropertyLocation.setLocation(); storePropertyValue(a, info, useWriteMethods, instanceVar, adapterInstanceClass); nextPropertyLocation.setLocation(); } if (stateVars != null) { for (int i=0; i<stateVars.size(); i++) { LocalVariable stateVar = stateVars.get(i); if (stateVar != null) { a.loadThis(); a.loadLocal(stateVar); a.storeField(PROPERTY_STATE_FIELD_NAME + i, TypeDesc.INT); } } } } }
public class class_name { private void buildDecoding(Mode mode, CodeAssembler a, StorableProperty<S>[] properties, Direction[] directions, LocalVariable instanceVar, Class<?> adapterInstanceClass, boolean useWriteMethods, int generation, Label altGenerationHandler, LocalVariable encodedVar) throws SupportException { if (a == null) { throw new IllegalArgumentException(); } if (encodedVar == null || encodedVar.getType() != TypeDesc.forClass(byte[].class)) { throw new IllegalArgumentException(); } // Decoding order is: // // 1. Prefix // 2. Generation prefix // 3. Property states (if Mode.SERIAL) // 4. Properties // 5. Suffix final int prefix; switch (mode) { default: prefix = 0; break; case KEY: prefix = mKeyPrefixPadding; break; case DATA: prefix = mDataPrefixPadding; break; } decodeGeneration(a, encodedVar, prefix, generation, altGenerationHandler); final int generationPrefix; if (generation < 0) { generationPrefix = 0; } else if (generation < 128) { generationPrefix = 1; } else { generationPrefix = 4; } final int suffix; switch (mode) { default: suffix = 0; break; case KEY: suffix = mKeySuffixPadding; break; case DATA: suffix = mDataSuffixPadding; extraDataDecoding(a, encodedVar, prefix + generationPrefix, suffix); break; } final TypeDesc byteArrayType = TypeDesc.forClass(byte[].class); StorablePropertyInfo[] infos = checkSupport(properties); if (properties.length == 1) { StorableProperty<S> property = properties[0]; StorablePropertyInfo info = infos[0]; if (mode != Mode.SERIAL && info.getStorageType().toClass() == byte[].class) { // Since there is only one property, and it is just a byte // array, it doesn't have any fancy encoding. // Push to stack in preparation for storing a property. pushDecodingInstanceVar(a, 0, instanceVar); a.loadLocal(encodedVar); boolean descending = mode == Mode.KEY && directions != null && directions[0] == Direction.DESCENDING; TypeDesc[] params; if (prefix > 0 || generationPrefix > 0 || suffix > 0) { a.loadConstant(prefix + generationPrefix); // depends on control dependency: [if], data = [(prefix] a.loadConstant(suffix); // depends on control dependency: [if], data = [none] params = new TypeDesc[] {byteArrayType, TypeDesc.INT, TypeDesc.INT}; // depends on control dependency: [if], data = [none] } else { params = new TypeDesc[] {byteArrayType}; // depends on control dependency: [if], data = [none] } if (property.isNullable()) { if (descending) { a.invokeStatic(KeyDecoder.class.getName(), "decodeSingleNullableDesc", byteArrayType, params); // depends on control dependency: [if], data = [none] } else { a.invokeStatic(DataDecoder.class.getName(), "decodeSingleNullable", byteArrayType, params); // depends on control dependency: [if], data = [none] } } else if (descending) { a.invokeStatic(KeyDecoder.class.getName(), "decodeSingleDesc", byteArrayType, params); // depends on control dependency: [if], data = [none] } else if (prefix > 0 || generationPrefix > 0 || suffix > 0) { a.invokeStatic(DataDecoder.class.getName(), "decodeSingle", byteArrayType, params); // depends on control dependency: [if], data = [none] } else { // Always clone the byte array as some implementations // reuse the byte array (e.g. iterating using a cursor). a.invokeVirtual(TypeDesc.OBJECT, "clone", TypeDesc.OBJECT, null); // depends on control dependency: [if], data = [none] a.checkCast(byteArrayType); // depends on control dependency: [if], data = [none] } storePropertyValue(a, info, useWriteMethods, instanceVar, adapterInstanceClass); return; } } // Now decode properties from the byte array. int constantOffset = prefix + generationPrefix; LocalVariable offsetVar = null; // References to local variables which will hold references. LocalVariable[] stringRefRef = new LocalVariable[1]; LocalVariable[] byteArrayRefRef = new LocalVariable[1]; LocalVariable[] bigIntegerRefRef = new LocalVariable[1]; LocalVariable[] bigDecimalRefRef = new LocalVariable[1]; LocalVariable[] valueRefRef = new LocalVariable[1]; // Used by SERIAL mode. List<LocalVariable> stateVars = null; if (mode == Mode.SERIAL) { stateVars = decodePropertyStates(a, encodedVar, constantOffset, properties); constantOffset += (properties.length + 3) / 4; // Some properties are skipped at runtime, so offset variable is required. offsetVar = a.createLocalVariable(null, TypeDesc.INT); a.loadConstant(constantOffset); a.storeLocal(offsetVar); // References need to be initialized early because some properties // are skipped at runtime. for (int i=0; i<properties.length; i++) { TypeDesc storageType = infos[i].getStorageType(); if (storageType == TypeDesc.STRING) { if (stringRefRef[0] == null) { TypeDesc refType = TypeDesc.forClass(String[].class); stringRefRef[0] = a.createLocalVariable(null, refType); a.loadConstant(1); a.newObject(refType); a.storeLocal(stringRefRef[0]); } } else if (storageType.toClass() == byte[].class) { if (byteArrayRefRef[0] == null) { TypeDesc refType = TypeDesc.forClass(byte[][].class); byteArrayRefRef[0] = a.createLocalVariable(null, refType); a.loadConstant(1); a.newObject(refType); a.storeLocal(byteArrayRefRef[0]); } } else if (storageType.toClass() == BigInteger.class) { if (bigIntegerRefRef[0] == null) { TypeDesc refType = TypeDesc.forClass(BigInteger[].class); bigIntegerRefRef[0] = a.createLocalVariable(null, refType); a.loadConstant(1); a.newObject(refType); a.storeLocal(bigIntegerRefRef[0]); } } else if (storageType.toClass() == BigDecimal.class) { if (bigDecimalRefRef[0] == null) { TypeDesc refType = TypeDesc.forClass(BigDecimal[].class); bigDecimalRefRef[0] = a.createLocalVariable(null, refType); a.loadConstant(1); a.newObject(refType); a.storeLocal(bigDecimalRefRef[0]); } } } } for (int i=0; i<properties.length; i++) { StorableProperty<S> property = properties[i]; StorablePropertyInfo info = infos[i]; Label storePropertyLocation = a.createLabel(); Label nextPropertyLocation = a.createLabel(); // Push to stack in preparation for storing a property. pushDecodingInstanceVar(a, i, instanceVar); if (mode == Mode.SERIAL) { // Load property if initialized, else reset it. a.loadLocal(stateVars.get(property.getNumber() >> 4)); a.loadConstant(PROPERTY_STATE_MASK << ((property.getNumber() & 0xf) * 2)); a.math(Opcode.IAND); Label isInitialized = a.createLabel(); a.ifZeroComparisonBranch(isInitialized, "!="); // Reset property value to zero, false, or null. loadBlankValue(a, TypeDesc.forClass(property.getType())); if (info.getToStorageAdapter() != null) { // Bypass adapter. a.storeField(info.getPropertyName(), info.getPropertyType()); a.branch(nextPropertyLocation); } else { a.branch(storePropertyLocation); } isInitialized.setLocation(); } TypeDesc storageType = info.getStorageType(); if (info.isLob()) { // Need RawSupport instance for getting Lob from locator. pushRawSupport(a, instanceVar); // Also need to pass this stuff along when getting Lob. a.loadThis(); a.loadConstant(info.getPropertyName()); // Locator is encoded as a long. storageType = TypeDesc.LONG; } a.loadLocal(encodedVar); if (offsetVar == null) { a.loadConstant(constantOffset); } else { a.loadLocal(offsetVar); } boolean descending = mode == Mode.KEY && directions != null && directions[i] == Direction.DESCENDING; int amt = decodeProperty(a, info, storageType, mode, descending, // TODO: do something better for passing these refs stringRefRef, byteArrayRefRef, bigIntegerRefRef, bigDecimalRefRef, valueRefRef); if (info.isLob()) { getLobFromLocator(a, info); } if (amt != 0) { if (i + 1 < properties.length) { // Only adjust offset if there are more properties. if (amt > 0) { if (offsetVar == null) { constantOffset += amt; } else { a.loadConstant(amt); a.loadLocal(offsetVar); a.math(Opcode.IADD); a.storeLocal(offsetVar); } } else { // Offset adjust is one if returned object is null. a.dup(); Label notNull = a.createLabel(); a.ifNullBranch(notNull, false); a.loadConstant(1 + (offsetVar == null ? constantOffset : 0)); Label cont = a.createLabel(); a.branch(cont); notNull.setLocation(); a.loadConstant(~amt + (offsetVar == null ? constantOffset : 0)); cont.setLocation(); if (offsetVar == null) { offsetVar = a.createLocalVariable(null, TypeDesc.INT); } else { a.loadLocal(offsetVar); a.math(Opcode.IADD); } a.storeLocal(offsetVar); } } } else { if (i + 1 >= properties.length) { // Don't need to keep track of offset anymore. a.pop(); } else { // Only adjust offset if there are more properties. if (offsetVar == null) { if (constantOffset > 0) { a.loadConstant(constantOffset); a.math(Opcode.IADD); } offsetVar = a.createLocalVariable(null, TypeDesc.INT); } else { a.loadLocal(offsetVar); a.math(Opcode.IADD); } a.storeLocal(offsetVar); } // Get the value out of the ref array so that it can be stored. a.loadLocal(valueRefRef[0]); a.loadConstant(0); a.loadFromArray(valueRefRef[0].getType()); } storePropertyLocation.setLocation(); storePropertyValue(a, info, useWriteMethods, instanceVar, adapterInstanceClass); nextPropertyLocation.setLocation(); } if (stateVars != null) { for (int i=0; i<stateVars.size(); i++) { LocalVariable stateVar = stateVars.get(i); if (stateVar != null) { a.loadThis(); a.loadLocal(stateVar); a.storeField(PROPERTY_STATE_FIELD_NAME + i, TypeDesc.INT); } } } } }
public class class_name { public void onDoubleClick(DoubleClickEvent event) { tempLength = 0; mapWidget.unregisterWorldPaintable(distanceLine); mapWidget.unregisterWorldPaintable(lineSegment); distanceLine.setGeometry(null); lineSegment.setGeometry(null); if (panel != null) { panel.destroy(); } dispatchState(State.STOP); } }
public class class_name { public void onDoubleClick(DoubleClickEvent event) { tempLength = 0; mapWidget.unregisterWorldPaintable(distanceLine); mapWidget.unregisterWorldPaintable(lineSegment); distanceLine.setGeometry(null); lineSegment.setGeometry(null); if (panel != null) { panel.destroy(); // depends on control dependency: [if], data = [none] } dispatchState(State.STOP); } }
public class class_name { public static boolean isMessageContentToBeLogged(final Message message, final boolean logMessageContent, boolean logMessageContentOverride) { /* * If controlling of logging behavior is not allowed externally * then log according to global property value */ if (!logMessageContentOverride) { return logMessageContent; } Object logMessageContentExtObj = message.getContextualProperty(EXTERNAL_PROPERTY_NAME); if (null == logMessageContentExtObj) { return logMessageContent; } else if (logMessageContentExtObj instanceof Boolean) { return ((Boolean) logMessageContentExtObj).booleanValue(); } else if (logMessageContentExtObj instanceof String) { String logMessageContentExtVal = (String) logMessageContentExtObj; if (logMessageContentExtVal.equalsIgnoreCase("true")) { return true; } else if (logMessageContentExtVal.equalsIgnoreCase("false")) { return false; } else { return logMessageContent; } } else { return logMessageContent; } } }
public class class_name { public static boolean isMessageContentToBeLogged(final Message message, final boolean logMessageContent, boolean logMessageContentOverride) { /* * If controlling of logging behavior is not allowed externally * then log according to global property value */ if (!logMessageContentOverride) { return logMessageContent; // depends on control dependency: [if], data = [none] } Object logMessageContentExtObj = message.getContextualProperty(EXTERNAL_PROPERTY_NAME); if (null == logMessageContentExtObj) { return logMessageContent; // depends on control dependency: [if], data = [none] } else if (logMessageContentExtObj instanceof Boolean) { return ((Boolean) logMessageContentExtObj).booleanValue(); // depends on control dependency: [if], data = [none] } else if (logMessageContentExtObj instanceof String) { String logMessageContentExtVal = (String) logMessageContentExtObj; if (logMessageContentExtVal.equalsIgnoreCase("true")) { return true; // depends on control dependency: [if], data = [none] } else if (logMessageContentExtVal.equalsIgnoreCase("false")) { return false; // depends on control dependency: [if], data = [none] } else { return logMessageContent; // depends on control dependency: [if], data = [none] } } else { return logMessageContent; // depends on control dependency: [if], data = [none] } } }
public class class_name { public static int decompressBBitSlots(int[] outDecompSlots, int[] inCompBlock, int blockSize, int bits) { int compressedBitSize = 0; int offset = HEADER_SIZE; for (int i = 0; i < blockSize; i++) { outDecompSlots[i] = readBits(inCompBlock, offset, bits); offset += bits; } compressedBitSize = bits * blockSize; return compressedBitSize; } }
public class class_name { public static int decompressBBitSlots(int[] outDecompSlots, int[] inCompBlock, int blockSize, int bits) { int compressedBitSize = 0; int offset = HEADER_SIZE; for (int i = 0; i < blockSize; i++) { outDecompSlots[i] = readBits(inCompBlock, offset, bits); // depends on control dependency: [for], data = [i] offset += bits; // depends on control dependency: [for], data = [none] } compressedBitSize = bits * blockSize; return compressedBitSize; } }
public class class_name { @Override public EClass getIfcReference() { if (ifcReferenceEClass == null) { ifcReferenceEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers() .get(507); } return ifcReferenceEClass; } }
public class class_name { @Override public EClass getIfcReference() { if (ifcReferenceEClass == null) { ifcReferenceEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers() .get(507); // depends on control dependency: [if], data = [none] } return ifcReferenceEClass; } }
public class class_name { public WordInfo getNextN(String[] data, int index, int N) { StringBuilder sb = new StringBuilder(); int i = index; while(sb.length()<N&&i<data.length){ sb.append(data[i]); i++; } if(sb.length()<=N) return new WordInfo(sb.toString(),i-index); else return new WordInfo(sb.substring(0,N),i-index); } }
public class class_name { public WordInfo getNextN(String[] data, int index, int N) { StringBuilder sb = new StringBuilder(); int i = index; while(sb.length()<N&&i<data.length){ sb.append(data[i]); // depends on control dependency: [while], data = [none] i++; // depends on control dependency: [while], data = [none] } if(sb.length()<=N) return new WordInfo(sb.toString(),i-index); else return new WordInfo(sb.substring(0,N),i-index); } }
public class class_name { synchronized PollObj get_polled_obj_by_type_name(final int obj_type, final String obj_name) throws DevFailed { // Get vector and search for type and name. final Vector po_list = get_poll_obj_list(); for (int i = 0; i < po_list.size(); i++) { final PollObj polled_obj = (PollObj) po_list.elementAt(i); if (polled_obj.get_type_i() == obj_type) { if (polled_obj.get_name_i().equals(obj_name)) { return polled_obj; } } } // If not found throws exception Except.throw_exception("API_PollObjNotFound", obj_name + " not found in list of polled object", "DeviceImpl.get_polled_obj_by_type_name"); return null; } }
public class class_name { synchronized PollObj get_polled_obj_by_type_name(final int obj_type, final String obj_name) throws DevFailed { // Get vector and search for type and name. final Vector po_list = get_poll_obj_list(); for (int i = 0; i < po_list.size(); i++) { final PollObj polled_obj = (PollObj) po_list.elementAt(i); if (polled_obj.get_type_i() == obj_type) { if (polled_obj.get_name_i().equals(obj_name)) { return polled_obj; // depends on control dependency: [if], data = [none] } } } // If not found throws exception Except.throw_exception("API_PollObjNotFound", obj_name + " not found in list of polled object", "DeviceImpl.get_polled_obj_by_type_name"); return null; } }
public class class_name { @SuppressWarnings("unchecked") public Future<Boolean> shutdown(long quietPeriod, long timeout, TimeUnit timeUnit) { logger.debug("Initiate shutdown ({}, {}, {})", quietPeriod, timeout, timeUnit); shutdownCalled = true; DefaultPromise<Boolean> overall = new DefaultPromise<Boolean>(GlobalEventExecutor.INSTANCE); DefaultPromise<Boolean> lastRelease = new DefaultPromise<Boolean>(GlobalEventExecutor.INSTANCE); Futures.PromiseAggregator<Boolean, Promise<Boolean>> aggregator = new Futures.PromiseAggregator<Boolean, Promise<Boolean>>( overall); aggregator.expectMore(1); if (!sharedEventLoopGroupProvider) { aggregator.expectMore(1); } if (!sharedEventExecutor) { aggregator.expectMore(1); } aggregator.arm(); if (metricEventPublisher != null) { metricEventPublisher.shutdown(); } if (!sharedTimer) { timer.stop(); } if (!sharedEventLoopGroupProvider) { Future<Boolean> shutdown = eventLoopGroupProvider.shutdown(quietPeriod, timeout, timeUnit); if (shutdown instanceof Promise) { aggregator.add((Promise<Boolean>) shutdown); } else { aggregator.add(toBooleanPromise(shutdown)); } } if (!sharedEventExecutor) { Future<?> shutdown = eventExecutorGroup.shutdownGracefully(quietPeriod, timeout, timeUnit); aggregator.add(toBooleanPromise(shutdown)); } if (!sharedCommandLatencyCollector) { commandLatencyCollector.shutdown(); } aggregator.add(lastRelease); lastRelease.setSuccess(null); return toBooleanPromise(overall); } }
public class class_name { @SuppressWarnings("unchecked") public Future<Boolean> shutdown(long quietPeriod, long timeout, TimeUnit timeUnit) { logger.debug("Initiate shutdown ({}, {}, {})", quietPeriod, timeout, timeUnit); shutdownCalled = true; DefaultPromise<Boolean> overall = new DefaultPromise<Boolean>(GlobalEventExecutor.INSTANCE); DefaultPromise<Boolean> lastRelease = new DefaultPromise<Boolean>(GlobalEventExecutor.INSTANCE); Futures.PromiseAggregator<Boolean, Promise<Boolean>> aggregator = new Futures.PromiseAggregator<Boolean, Promise<Boolean>>( overall); aggregator.expectMore(1); if (!sharedEventLoopGroupProvider) { aggregator.expectMore(1); // depends on control dependency: [if], data = [none] } if (!sharedEventExecutor) { aggregator.expectMore(1); // depends on control dependency: [if], data = [none] } aggregator.arm(); if (metricEventPublisher != null) { metricEventPublisher.shutdown(); // depends on control dependency: [if], data = [none] } if (!sharedTimer) { timer.stop(); // depends on control dependency: [if], data = [none] } if (!sharedEventLoopGroupProvider) { Future<Boolean> shutdown = eventLoopGroupProvider.shutdown(quietPeriod, timeout, timeUnit); if (shutdown instanceof Promise) { aggregator.add((Promise<Boolean>) shutdown); // depends on control dependency: [if], data = [none] } else { aggregator.add(toBooleanPromise(shutdown)); // depends on control dependency: [if], data = [none] } } if (!sharedEventExecutor) { Future<?> shutdown = eventExecutorGroup.shutdownGracefully(quietPeriod, timeout, timeUnit); aggregator.add(toBooleanPromise(shutdown)); // depends on control dependency: [if], data = [none] } if (!sharedCommandLatencyCollector) { commandLatencyCollector.shutdown(); // depends on control dependency: [if], data = [none] } aggregator.add(lastRelease); lastRelease.setSuccess(null); return toBooleanPromise(overall); } }
public class class_name { public void startSendingEvents () { if (this.getOutputStream() == null) throw new IllegalStateException("Try sending events from EntrancePI while outputStream is not set."); while (!this.getProcessor().isFinished()) { if (!this.injectNextEvent()) { try { waitForNewEvents(); } catch (Exception e) { e.printStackTrace(); break; } } } } }
public class class_name { public void startSendingEvents () { if (this.getOutputStream() == null) throw new IllegalStateException("Try sending events from EntrancePI while outputStream is not set."); while (!this.getProcessor().isFinished()) { if (!this.injectNextEvent()) { try { waitForNewEvents(); // depends on control dependency: [try], data = [none] } catch (Exception e) { e.printStackTrace(); break; } // depends on control dependency: [catch], data = [none] } } } }
public class class_name { static public int intToBytes(int i, byte[] buffer, int index) { int length = buffer.length - index; if (length > 4) length = 4; for (int j = 0; j < length; j++) { buffer[index + length - j - 1] = (byte) (i >> (j * 8)); } return length; } }
public class class_name { static public int intToBytes(int i, byte[] buffer, int index) { int length = buffer.length - index; if (length > 4) length = 4; for (int j = 0; j < length; j++) { buffer[index + length - j - 1] = (byte) (i >> (j * 8)); // depends on control dependency: [for], data = [j] } return length; } }
public class class_name { private Logger getLogger() { if ( logger != null ) { return logger; } logger = LoggerFactory.getLogger( ResourceReaderImpl.class ); return logger; } }
public class class_name { private Logger getLogger() { if ( logger != null ) { return logger; // depends on control dependency: [if], data = [none] } logger = LoggerFactory.getLogger( ResourceReaderImpl.class ); return logger; } }
public class class_name { public CharSequence matchOnLength(final Supplier<CharSequence> one, final Supplier<CharSequence> many) { final int arrayLength = arrayLength(); if (arrayLength == 1) { return one.get(); } else if (arrayLength > 1) { return many.get(); } return ""; } }
public class class_name { public CharSequence matchOnLength(final Supplier<CharSequence> one, final Supplier<CharSequence> many) { final int arrayLength = arrayLength(); if (arrayLength == 1) { return one.get(); // depends on control dependency: [if], data = [none] } else if (arrayLength > 1) { return many.get(); // depends on control dependency: [if], data = [none] } return ""; } }
public class class_name { public static String getExtension(String filename) { if (filename == null) { return null; } int index = indexOfExtension(filename); if (index == -1) { return StringUtils.EMPTY; } else { return filename.substring(index + 1); } } }
public class class_name { public static String getExtension(String filename) { if (filename == null) { return null; // depends on control dependency: [if], data = [none] } int index = indexOfExtension(filename); if (index == -1) { return StringUtils.EMPTY; // depends on control dependency: [if], data = [none] } else { return filename.substring(index + 1); // depends on control dependency: [if], data = [(index] } } }
public class class_name { public final void addAll (final SettingsMap textKeys) { for (Map.Entry<OperationalTextKey , String> e : textKeys.entrySet()) { add(e.getKey(), e.getValue()); } isDirty = true; } }
public class class_name { public final void addAll (final SettingsMap textKeys) { for (Map.Entry<OperationalTextKey , String> e : textKeys.entrySet()) { add(e.getKey(), e.getValue()); // depends on control dependency: [for], data = [e] } isDirty = true; } }
public class class_name { public int compare (IntWritable i, IntWritable j) { // indicate we're making progress but do a batch update if (progressCalls < progressUpdateFrequency) { progressCalls++; } else { progressCalls = 0; reporter.progress(); } return comparator.compare(keyValBuffer.getData(), startOffsets[i.get()], keyLengths[i.get()], keyValBuffer.getData(), startOffsets[j.get()], keyLengths[j.get()]); } }
public class class_name { public int compare (IntWritable i, IntWritable j) { // indicate we're making progress but do a batch update if (progressCalls < progressUpdateFrequency) { progressCalls++; // depends on control dependency: [if], data = [none] } else { progressCalls = 0; // depends on control dependency: [if], data = [none] reporter.progress(); // depends on control dependency: [if], data = [none] } return comparator.compare(keyValBuffer.getData(), startOffsets[i.get()], keyLengths[i.get()], keyValBuffer.getData(), startOffsets[j.get()], keyLengths[j.get()]); } }
public class class_name { private List<Double> getAngles() { int n = subunits.getSubunitCount(); // for spherical symmetric cases, n cannot be higher than 60 if (n % 60 == 0 && isSpherical()) { n = 60; } List<Integer> folds = subunits.getFolds(); List<Double> angles = new ArrayList<Double>(folds.size()-1); // note this loop starts at 1, we do ignore 1-fold symmetry, which is the first entry for (int fold: folds) { if (fold > 0 && fold <= n) { angles.add(2* Math.PI/fold); } } return angles; } }
public class class_name { private List<Double> getAngles() { int n = subunits.getSubunitCount(); // for spherical symmetric cases, n cannot be higher than 60 if (n % 60 == 0 && isSpherical()) { n = 60; // depends on control dependency: [if], data = [none] } List<Integer> folds = subunits.getFolds(); List<Double> angles = new ArrayList<Double>(folds.size()-1); // note this loop starts at 1, we do ignore 1-fold symmetry, which is the first entry for (int fold: folds) { if (fold > 0 && fold <= n) { angles.add(2* Math.PI/fold); // depends on control dependency: [if], data = [none] } } return angles; } }
public class class_name { protected void reset() { this.ndx = 0; this.textLen = 0; this.path = new Path(); this.notFirstObject = false; if (useAltPaths) { path.altPath = new Path(); } if (classMetadataName != null) { mapToBean = createMapToBean(classMetadataName); } } }
public class class_name { protected void reset() { this.ndx = 0; this.textLen = 0; this.path = new Path(); this.notFirstObject = false; if (useAltPaths) { path.altPath = new Path(); // depends on control dependency: [if], data = [none] } if (classMetadataName != null) { mapToBean = createMapToBean(classMetadataName); // depends on control dependency: [if], data = [(classMetadataName] } } }
public class class_name { boolean canInsert(Table table, boolean[] columnCheckList) { if (isFull || isFullInsert) { return true; } return containsAllColumns(insertColumnSet, table, columnCheckList); } }
public class class_name { boolean canInsert(Table table, boolean[] columnCheckList) { if (isFull || isFullInsert) { return true; // depends on control dependency: [if], data = [none] } return containsAllColumns(insertColumnSet, table, columnCheckList); } }
public class class_name { public static CharacterDescriptor getRandomDescriptor ( ComponentRepository crepo, String gender, String[] COMP_CLASSES, ColorPository cpos, String[] COLOR_CLASSES) { // get all available classes ArrayList<ComponentClass> classes = Lists.newArrayList(); for (String element : COMP_CLASSES) { String cname = gender + "/" + element; ComponentClass cclass = crepo.getComponentClass(cname); // make sure the component class exists if (cclass == null) { log.warning("Missing definition for component class", "class", cname); continue; } // make sure there are some components in this class Iterator<Integer> iter = crepo.enumerateComponentIds(cclass); if (!iter.hasNext()) { log.info("Skipping class for which we have no components", "class", cclass); continue; } classes.add(cclass); } // select the components int[] components = new int[classes.size()]; Colorization[][] zations = new Colorization[components.length][]; for (int ii = 0; ii < components.length; ii++) { ComponentClass cclass = classes.get(ii); // get the components available for this class ArrayList<Integer> choices = Lists.newArrayList(); Iterators.addAll(choices, crepo.enumerateComponentIds(cclass)); // each of our components has up to four colorizations: two "global" skin colorizations // and potentially a primary and secondary clothing colorization; in a real system one // would probably keep a separate database of which character component required which // colorizations, but here we just assume everything could have any of the four // colorizations; it *usually* doesn't hose an image if you apply a recoloring that it // does not support, but it can match stray colors unnecessarily zations[ii] = new Colorization[COLOR_CLASSES.length]; for (int zz = 0; zz < COLOR_CLASSES.length; zz++) { zations[ii][zz] = cpos.getRandomStartingColor(COLOR_CLASSES[zz]).getColorization(); } // choose a random component if (choices.size() > 0) { int idx = RandomUtil.getInt(choices.size()); components[ii] = choices.get(idx).intValue(); } else { log.info("Have no components in class", "class", cclass); } } return new CharacterDescriptor(components, zations); } }
public class class_name { public static CharacterDescriptor getRandomDescriptor ( ComponentRepository crepo, String gender, String[] COMP_CLASSES, ColorPository cpos, String[] COLOR_CLASSES) { // get all available classes ArrayList<ComponentClass> classes = Lists.newArrayList(); for (String element : COMP_CLASSES) { String cname = gender + "/" + element; ComponentClass cclass = crepo.getComponentClass(cname); // make sure the component class exists if (cclass == null) { log.warning("Missing definition for component class", "class", cname); // depends on control dependency: [if], data = [none] continue; } // make sure there are some components in this class Iterator<Integer> iter = crepo.enumerateComponentIds(cclass); if (!iter.hasNext()) { log.info("Skipping class for which we have no components", "class", cclass); // depends on control dependency: [if], data = [none] continue; } classes.add(cclass); // depends on control dependency: [for], data = [none] } // select the components int[] components = new int[classes.size()]; Colorization[][] zations = new Colorization[components.length][]; for (int ii = 0; ii < components.length; ii++) { ComponentClass cclass = classes.get(ii); // get the components available for this class ArrayList<Integer> choices = Lists.newArrayList(); Iterators.addAll(choices, crepo.enumerateComponentIds(cclass)); // depends on control dependency: [for], data = [none] // each of our components has up to four colorizations: two "global" skin colorizations // and potentially a primary and secondary clothing colorization; in a real system one // would probably keep a separate database of which character component required which // colorizations, but here we just assume everything could have any of the four // colorizations; it *usually* doesn't hose an image if you apply a recoloring that it // does not support, but it can match stray colors unnecessarily zations[ii] = new Colorization[COLOR_CLASSES.length]; // depends on control dependency: [for], data = [ii] for (int zz = 0; zz < COLOR_CLASSES.length; zz++) { zations[ii][zz] = cpos.getRandomStartingColor(COLOR_CLASSES[zz]).getColorization(); // depends on control dependency: [for], data = [zz] } // choose a random component if (choices.size() > 0) { int idx = RandomUtil.getInt(choices.size()); components[ii] = choices.get(idx).intValue(); // depends on control dependency: [if], data = [none] } else { log.info("Have no components in class", "class", cclass); // depends on control dependency: [if], data = [none] } } return new CharacterDescriptor(components, zations); } }
public class class_name { private void startSpider() { spider = new Spider(id, extension, spiderParams, extension.getModel().getOptionsParam() .getConnectionParam(), extension.getModel(), this.scanContext); // Register this thread as a Spider Listener, so it gets notified of events and is able // to manipulate the UI accordingly spider.addSpiderListener(this); // Add the pending listeners for (SpiderListener l : pendingSpiderListeners) { spider.addSpiderListener(l); } // Add the list of (regex) URIs that should be excluded List<String> excludeList = new ArrayList<>(); excludeList.addAll(extension.getExcludeList()); excludeList.addAll(extension.getModel().getSession().getExcludeFromSpiderRegexs()); excludeList.addAll(extension.getModel().getSession().getGlobalExcludeURLRegexs()); spider.setExcludeList(excludeList); // Add seeds accordingly addSeeds(); spider.setScanAsUser(scanUser); // Add any custom parsers and filters specified if (this.customSpiderParsers != null) { for (SpiderParser sp : this.customSpiderParsers) { spider.addCustomParser(sp); } } if (this.customFetchFilters != null) { for (FetchFilter ff : this.customFetchFilters) { spider.addFetchFilter(ff); } } if (this.customParseFilters != null) { for (ParseFilter pf : this.customParseFilters) { spider.addParseFilter(pf); } } // Start the spider spider.start(); } }
public class class_name { private void startSpider() { spider = new Spider(id, extension, spiderParams, extension.getModel().getOptionsParam() .getConnectionParam(), extension.getModel(), this.scanContext); // Register this thread as a Spider Listener, so it gets notified of events and is able // to manipulate the UI accordingly spider.addSpiderListener(this); // Add the pending listeners for (SpiderListener l : pendingSpiderListeners) { spider.addSpiderListener(l); // depends on control dependency: [for], data = [l] } // Add the list of (regex) URIs that should be excluded List<String> excludeList = new ArrayList<>(); excludeList.addAll(extension.getExcludeList()); excludeList.addAll(extension.getModel().getSession().getExcludeFromSpiderRegexs()); excludeList.addAll(extension.getModel().getSession().getGlobalExcludeURLRegexs()); spider.setExcludeList(excludeList); // Add seeds accordingly addSeeds(); spider.setScanAsUser(scanUser); // Add any custom parsers and filters specified if (this.customSpiderParsers != null) { for (SpiderParser sp : this.customSpiderParsers) { spider.addCustomParser(sp); // depends on control dependency: [for], data = [sp] } } if (this.customFetchFilters != null) { for (FetchFilter ff : this.customFetchFilters) { spider.addFetchFilter(ff); // depends on control dependency: [for], data = [ff] } } if (this.customParseFilters != null) { for (ParseFilter pf : this.customParseFilters) { spider.addParseFilter(pf); // depends on control dependency: [for], data = [pf] } } // Start the spider spider.start(); } }
public class class_name { public static void bindProperties(Binder binder, Properties properties) { binder = binder.skipSources(Names.class); // use enumeration to include the default properties for (Enumeration<?> e = properties.propertyNames(); e.hasMoreElements(); ) { String propertyName = (String) e.nextElement(); String value = properties.getProperty(propertyName); binder.bind(Key.get(String.class, new NamedImpl(propertyName))).toInstance(value); } } }
public class class_name { public static void bindProperties(Binder binder, Properties properties) { binder = binder.skipSources(Names.class); // use enumeration to include the default properties for (Enumeration<?> e = properties.propertyNames(); e.hasMoreElements(); ) { String propertyName = (String) e.nextElement(); String value = properties.getProperty(propertyName); binder.bind(Key.get(String.class, new NamedImpl(propertyName))).toInstance(value); // depends on control dependency: [for], data = [none] } } }
public class class_name { public int getPathId(String pathName, int profileId) { PreparedStatement queryStatement = null; ResultSet results = null; // first get the pathId for the pathName/profileId int pathId = -1; try (Connection sqlConnection = sqlService.getConnection()) { queryStatement = sqlConnection.prepareStatement( "SELECT " + Constants.GENERIC_ID + " FROM " + Constants.DB_TABLE_PATH + " WHERE " + Constants.PATH_PROFILE_PATHNAME + "= ? " + " AND " + Constants.GENERIC_PROFILE_ID + "= ?" ); queryStatement.setString(1, pathName); queryStatement.setInt(2, profileId); results = queryStatement.executeQuery(); if (results.next()) { pathId = results.getInt(Constants.GENERIC_ID); } } catch (Exception e) { e.printStackTrace(); } finally { try { if (results != null) { results.close(); } } catch (Exception e) { } try { if (queryStatement != null) { queryStatement.close(); } } catch (Exception e) { } } return pathId; } }
public class class_name { public int getPathId(String pathName, int profileId) { PreparedStatement queryStatement = null; ResultSet results = null; // first get the pathId for the pathName/profileId int pathId = -1; try (Connection sqlConnection = sqlService.getConnection()) { queryStatement = sqlConnection.prepareStatement( "SELECT " + Constants.GENERIC_ID + " FROM " + Constants.DB_TABLE_PATH + " WHERE " + Constants.PATH_PROFILE_PATHNAME + "= ? " + " AND " + Constants.GENERIC_PROFILE_ID + "= ?" ); queryStatement.setString(1, pathName); queryStatement.setInt(2, profileId); results = queryStatement.executeQuery(); if (results.next()) { pathId = results.getInt(Constants.GENERIC_ID); // depends on control dependency: [if], data = [none] } } catch (Exception e) { e.printStackTrace(); } finally { try { if (results != null) { results.close(); // depends on control dependency: [if], data = [none] } } catch (Exception e) { } // depends on control dependency: [catch], data = [none] try { if (queryStatement != null) { queryStatement.close(); // depends on control dependency: [if], data = [none] } } catch (Exception e) { } // depends on control dependency: [catch], data = [none] } return pathId; } }
public class class_name { public void setStartDate(String startDate) { if (StringUtils.isNotBlank(startDate)) { this.startDate = Instant.parse(startDate); } } }
public class class_name { public void setStartDate(String startDate) { if (StringUtils.isNotBlank(startDate)) { this.startDate = Instant.parse(startDate); // depends on control dependency: [if], data = [none] } } }
public class class_name { public Iterator<Operator<Term>> traverse(Functor functor, boolean reverse) { /*log.fine("Traversing functor " + functor.toString());*/ Queue<Operator<Term>> queue = (!reverse) ? new StackQueue<Operator<Term>>() : new LinkedList<Operator<Term>>(); Term[] arguments = functor.getArguments(); // For a top-level functor clear top-level flag, so that child functors are not taken as top-level. if (arguments != null) { for (int i = leftToRightFunctorArgs ? 0 : (arguments.length - 1); leftToRightFunctorArgs ? (i < arguments.length) : (i >= 0); i = i + (leftToRightFunctorArgs ? 1 : -1)) { Term argument = arguments[i]; argument.setReversable(createTermOperator(argument, i, functor)); argument.setTermTraverser(this); queue.offer(argument); } } return queue.iterator(); } }
public class class_name { public Iterator<Operator<Term>> traverse(Functor functor, boolean reverse) { /*log.fine("Traversing functor " + functor.toString());*/ Queue<Operator<Term>> queue = (!reverse) ? new StackQueue<Operator<Term>>() : new LinkedList<Operator<Term>>(); Term[] arguments = functor.getArguments(); // For a top-level functor clear top-level flag, so that child functors are not taken as top-level. if (arguments != null) { for (int i = leftToRightFunctorArgs ? 0 : (arguments.length - 1); leftToRightFunctorArgs ? (i < arguments.length) : (i >= 0); i = i + (leftToRightFunctorArgs ? 1 : -1)) { Term argument = arguments[i]; argument.setReversable(createTermOperator(argument, i, functor)); // depends on control dependency: [for], data = [i] argument.setTermTraverser(this); // depends on control dependency: [for], data = [none] queue.offer(argument); // depends on control dependency: [for], data = [none] } } return queue.iterator(); } }
public class class_name { @Override public T resolve(String name, MediaType mediaType) { if (this.cache != null) { if (!this.cache.containsKey(name)) { T t = this.resolve(name); if (t != null) this.cache.putIfAbsent(name, t); } return this.cache.get(name); } else { return this.resolve(name); } } }
public class class_name { @Override public T resolve(String name, MediaType mediaType) { if (this.cache != null) { if (!this.cache.containsKey(name)) { T t = this.resolve(name); if (t != null) this.cache.putIfAbsent(name, t); } return this.cache.get(name); // depends on control dependency: [if], data = [none] } else { return this.resolve(name); // depends on control dependency: [if], data = [none] } } }
public class class_name { private void setCorsResponseHeaders(ServiceRequestContext ctx, HttpRequest req, HttpHeaders headers) { final CorsPolicy policy = setCorsOrigin(ctx, req, headers); if (policy != null) { policy.setCorsAllowCredentials(headers); policy.setCorsAllowHeaders(headers); policy.setCorsExposeHeaders(headers); } } }
public class class_name { private void setCorsResponseHeaders(ServiceRequestContext ctx, HttpRequest req, HttpHeaders headers) { final CorsPolicy policy = setCorsOrigin(ctx, req, headers); if (policy != null) { policy.setCorsAllowCredentials(headers); // depends on control dependency: [if], data = [none] policy.setCorsAllowHeaders(headers); // depends on control dependency: [if], data = [none] policy.setCorsExposeHeaders(headers); // depends on control dependency: [if], data = [none] } } }
public class class_name { private boolean isNotPrompt(String action, String expected, String perform) { // wait for element to be present if (!is.promptPresent()) { waitFor.promptPresent(); } if (!is.promptPresent()) { reporter.fail(action, expected, "Unable to " + perform + " prompt as it is not present"); return true; // indicates element not present } return false; } }
public class class_name { private boolean isNotPrompt(String action, String expected, String perform) { // wait for element to be present if (!is.promptPresent()) { waitFor.promptPresent(); // depends on control dependency: [if], data = [none] } if (!is.promptPresent()) { reporter.fail(action, expected, "Unable to " + perform + " prompt as it is not present"); // depends on control dependency: [if], data = [none] return true; // indicates element not present // depends on control dependency: [if], data = [none] } return false; } }
public class class_name { public void sort() { if (IndexTerm.getTermLocale() == null || IndexTerm.getTermLocale().getLanguage().trim().length() == 0) { IndexTerm.setTermLocale(new Locale(LANGUAGE_EN, COUNTRY_US)); } /* * Sort all the terms recursively */ for (final IndexTerm term : termList) { term.sortSubTerms(); } Collections.sort(termList); } }
public class class_name { public void sort() { if (IndexTerm.getTermLocale() == null || IndexTerm.getTermLocale().getLanguage().trim().length() == 0) { IndexTerm.setTermLocale(new Locale(LANGUAGE_EN, COUNTRY_US)); // depends on control dependency: [if], data = [none] } /* * Sort all the terms recursively */ for (final IndexTerm term : termList) { term.sortSubTerms(); // depends on control dependency: [for], data = [term] } Collections.sort(termList); } }
public class class_name { public Docket genericModelSubstitutes(Class... genericClasses) { for (Class clz : genericClasses) { this.ruleBuilders.add(newGenericSubstitutionFunction(clz)); } return this; } }
public class class_name { public Docket genericModelSubstitutes(Class... genericClasses) { for (Class clz : genericClasses) { this.ruleBuilders.add(newGenericSubstitutionFunction(clz)); // depends on control dependency: [for], data = [clz] } return this; } }
public class class_name { public List<JAXBElement<? extends AbstractPositionalAccuracyType>> get_PositionalAccuracy() { if (_PositionalAccuracy == null) { _PositionalAccuracy = new ArrayList<JAXBElement<? extends AbstractPositionalAccuracyType>>(); } return this._PositionalAccuracy; } }
public class class_name { public List<JAXBElement<? extends AbstractPositionalAccuracyType>> get_PositionalAccuracy() { if (_PositionalAccuracy == null) { _PositionalAccuracy = new ArrayList<JAXBElement<? extends AbstractPositionalAccuracyType>>(); // depends on control dependency: [if], data = [none] } return this._PositionalAccuracy; } }
public class class_name { protected boolean sample() { if (curr.increment() >= freq) { curr.set(0); target.set(rand.nextInt(freq)); } return curr.get() == target.get(); } }
public class class_name { protected boolean sample() { if (curr.increment() >= freq) { curr.set(0); // depends on control dependency: [if], data = [none] target.set(rand.nextInt(freq)); // depends on control dependency: [if], data = [none] } return curr.get() == target.get(); } }
public class class_name { private synchronized void changeState(PrimitiveState state) { if (this.state != state) { this.state = state; stateChangeListeners.forEach(l -> threadContext.execute(() -> l.accept(state))); } } }
public class class_name { private synchronized void changeState(PrimitiveState state) { if (this.state != state) { this.state = state; // depends on control dependency: [if], data = [none] stateChangeListeners.forEach(l -> threadContext.execute(() -> l.accept(state))); // depends on control dependency: [if], data = [state)] } } }
public class class_name { public String renderQualifiedName(String qualifiedName) { Assert.notNull(qualifiedName, "No qualified name specified"); StringBuffer sb = new StringBuffer(qualifiedName.length() + 5); char[] chars = qualifiedName.toCharArray(); sb.append(Character.toUpperCase(chars[0])); boolean foundDot = false; for (int i = 1; i < chars.length; i++) { char c = chars[i]; if (Character.isLetter(c)) { if (Character.isLowerCase(c)) { if (foundDot) { sb.append(Character.toUpperCase(c)); foundDot = false; } else { sb.append(c); } } else { sb.append(c); } } else if (c == '.') { sb.append(c); foundDot = true; } } return sb.toString(); } }
public class class_name { public String renderQualifiedName(String qualifiedName) { Assert.notNull(qualifiedName, "No qualified name specified"); StringBuffer sb = new StringBuffer(qualifiedName.length() + 5); char[] chars = qualifiedName.toCharArray(); sb.append(Character.toUpperCase(chars[0])); boolean foundDot = false; for (int i = 1; i < chars.length; i++) { char c = chars[i]; if (Character.isLetter(c)) { if (Character.isLowerCase(c)) { if (foundDot) { sb.append(Character.toUpperCase(c)); // depends on control dependency: [if], data = [none] foundDot = false; // depends on control dependency: [if], data = [none] } else { sb.append(c); // depends on control dependency: [if], data = [none] } } else { sb.append(c); // depends on control dependency: [if], data = [none] } } else if (c == '.') { sb.append(c); // depends on control dependency: [if], data = [(c] foundDot = true; // depends on control dependency: [if], data = [none] } } return sb.toString(); } }
public class class_name { public int getFirstChild(int nodeHandle) { // ###shs worry about tracing/debug later nodeHandle &= NODEHANDLE_MASK; // Read node into variable nodes.readSlot(nodeHandle, gotslot); // type is the last half of first slot short type = (short) (gotslot[0] & 0xFFFF); // Check to see if Element or Document node if ((type == ELEMENT_NODE) || (type == DOCUMENT_NODE) || (type == ENTITY_REFERENCE_NODE)) { // In case when Document root is given // if (nodeHandle == 0) nodeHandle = 1; // %TBD% Probably was a mistake. // If someone explicitly asks for first child // of Document, I would expect them to want // that and only that. int kid = nodeHandle + 1; nodes.readSlot(kid, gotslot); while (ATTRIBUTE_NODE == (gotslot[0] & 0xFFFF)) { // points to next sibling kid = gotslot[2]; // Return NULL if node has only attributes if (kid == NULL) return NULL; nodes.readSlot(kid, gotslot); } // If parent slot matches given parent, return kid if (gotslot[1] == nodeHandle) { int firstChild = kid | m_docHandle; return firstChild; } } // No child found return NULL; } }
public class class_name { public int getFirstChild(int nodeHandle) { // ###shs worry about tracing/debug later nodeHandle &= NODEHANDLE_MASK; // Read node into variable nodes.readSlot(nodeHandle, gotslot); // type is the last half of first slot short type = (short) (gotslot[0] & 0xFFFF); // Check to see if Element or Document node if ((type == ELEMENT_NODE) || (type == DOCUMENT_NODE) || (type == ENTITY_REFERENCE_NODE)) { // In case when Document root is given // if (nodeHandle == 0) nodeHandle = 1; // %TBD% Probably was a mistake. // If someone explicitly asks for first child // of Document, I would expect them to want // that and only that. int kid = nodeHandle + 1; nodes.readSlot(kid, gotslot); // depends on control dependency: [if], data = [none] while (ATTRIBUTE_NODE == (gotslot[0] & 0xFFFF)) { // points to next sibling kid = gotslot[2]; // depends on control dependency: [while], data = [none] // Return NULL if node has only attributes if (kid == NULL) return NULL; nodes.readSlot(kid, gotslot); // depends on control dependency: [while], data = [none] } // If parent slot matches given parent, return kid if (gotslot[1] == nodeHandle) { int firstChild = kid | m_docHandle; return firstChild; // depends on control dependency: [if], data = [none] } } // No child found return NULL; } }
public class class_name { public List<T> keySetSorted() { List<T> result = new ArrayList<>(); PriorityQueue<Pair<T, Double>> pq = asPriorityQueue(); while (!pq.isEmpty()) { result.add(pq.poll().getFirst()); } return result; } }
public class class_name { public List<T> keySetSorted() { List<T> result = new ArrayList<>(); PriorityQueue<Pair<T, Double>> pq = asPriorityQueue(); while (!pq.isEmpty()) { result.add(pq.poll().getFirst()); // depends on control dependency: [while], data = [none] } return result; } }
public class class_name { private boolean isVoidVariable(WAMInstruction instruction) { SymbolKey symbolKey = instruction.getSymbolKeyReg1(); if (symbolKey != null) { Integer count = (Integer) symbolTable.get(symbolKey, SymbolTableKeys.SYMKEY_VAR_OCCURRENCE_COUNT); Boolean nonArgPositionOnly = (Boolean) symbolTable.get(symbolKey, SymbolTableKeys.SYMKEY_VAR_NON_ARG); Integer allocation = (Integer) symbolTable.get(symbolKey, SymbolTableKeys.SYMKEY_ALLOCATION); boolean singleton = (count != null) && count.equals(1); boolean nonArgPosition = (nonArgPositionOnly != null) && TRUE.equals(nonArgPositionOnly); boolean permanent = (allocation != null) && ((byte) ((allocation & 0xff00) >> 8) == WAMInstruction.STACK_ADDR); if (singleton && nonArgPosition && !permanent) { return true; } } return false; } }
public class class_name { private boolean isVoidVariable(WAMInstruction instruction) { SymbolKey symbolKey = instruction.getSymbolKeyReg1(); if (symbolKey != null) { Integer count = (Integer) symbolTable.get(symbolKey, SymbolTableKeys.SYMKEY_VAR_OCCURRENCE_COUNT); Boolean nonArgPositionOnly = (Boolean) symbolTable.get(symbolKey, SymbolTableKeys.SYMKEY_VAR_NON_ARG); Integer allocation = (Integer) symbolTable.get(symbolKey, SymbolTableKeys.SYMKEY_ALLOCATION); boolean singleton = (count != null) && count.equals(1); boolean nonArgPosition = (nonArgPositionOnly != null) && TRUE.equals(nonArgPositionOnly); boolean permanent = (allocation != null) && ((byte) ((allocation & 0xff00) >> 8) == WAMInstruction.STACK_ADDR); if (singleton && nonArgPosition && !permanent) { return true; // depends on control dependency: [if], data = [none] } } return false; } }
public class class_name { private void setSessionContext(Object targetObject, TargetMetaRequest targetMetaRequest) { if (isSessionContextAcceptables.contains(targetMetaRequest.getTargetMetaDef().getName())) { SessionContextAcceptable myResult = (SessionContextAcceptable) targetObject; SessionContext sessionContext = targetMetaRequest.getSessionContext(); myResult.setSessionContext(sessionContext); } else if (isSessionContextAcceptablesAnnotations.containsKey(targetMetaRequest.getTargetMetaDef().getName())) { Method method = isSessionContextAcceptablesAnnotations.get(targetMetaRequest.getTargetMetaDef().getName()); try { Object[] sessionContexts = new SessionContext[1]; sessionContexts[0] = targetMetaRequest.getSessionContext(); method.invoke(targetObject, sessionContexts); } catch (Exception e) { Debug.logError("[JdonFramework]the target must has method setSessionContext(SessionContext sessionContext) : " + e, module); } } } }
public class class_name { private void setSessionContext(Object targetObject, TargetMetaRequest targetMetaRequest) { if (isSessionContextAcceptables.contains(targetMetaRequest.getTargetMetaDef().getName())) { SessionContextAcceptable myResult = (SessionContextAcceptable) targetObject; SessionContext sessionContext = targetMetaRequest.getSessionContext(); myResult.setSessionContext(sessionContext); // depends on control dependency: [if], data = [none] } else if (isSessionContextAcceptablesAnnotations.containsKey(targetMetaRequest.getTargetMetaDef().getName())) { Method method = isSessionContextAcceptablesAnnotations.get(targetMetaRequest.getTargetMetaDef().getName()); try { Object[] sessionContexts = new SessionContext[1]; sessionContexts[0] = targetMetaRequest.getSessionContext(); // depends on control dependency: [try], data = [none] method.invoke(targetObject, sessionContexts); // depends on control dependency: [try], data = [none] } catch (Exception e) { Debug.logError("[JdonFramework]the target must has method setSessionContext(SessionContext sessionContext) : " + e, module); } // depends on control dependency: [catch], data = [none] } } }
public class class_name { private boolean findAttribute(JsonParser parser, JsonPathCursor pathCursor) throws IOException { JsonToken token = parser.getCurrentToken(); if (token != JsonToken.START_OBJECT) { return false; } while (true) { token = parser.nextToken(); if (token == JsonToken.END_OBJECT) { return false; } if (pathCursor.getCurrent().equals(parser.getCurrentName())) { parser.nextToken(); return true; } else { parser.nextToken(); parser.skipChildren(); } } } }
public class class_name { private boolean findAttribute(JsonParser parser, JsonPathCursor pathCursor) throws IOException { JsonToken token = parser.getCurrentToken(); if (token != JsonToken.START_OBJECT) { return false; } while (true) { token = parser.nextToken(); if (token == JsonToken.END_OBJECT) { return false; // depends on control dependency: [if], data = [none] } if (pathCursor.getCurrent().equals(parser.getCurrentName())) { parser.nextToken(); // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } else { parser.nextToken(); // depends on control dependency: [if], data = [none] parser.skipChildren(); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public Post params(String ... namesAndValues){ if(namesAndValues == null ){ throw new NullPointerException("'names and values' cannot be null"); } if(namesAndValues.length % 2 != 0){ throw new IllegalArgumentException("mus pas even number of arguments"); } for (int i = 0; i < namesAndValues.length - 1; i += 2) { if (namesAndValues[i] == null) throw new IllegalArgumentException("parameter names cannot be nulls"); params.put(namesAndValues[i], namesAndValues[i + 1]); } return this; } }
public class class_name { public Post params(String ... namesAndValues){ if(namesAndValues == null ){ throw new NullPointerException("'names and values' cannot be null"); } if(namesAndValues.length % 2 != 0){ throw new IllegalArgumentException("mus pas even number of arguments"); } for (int i = 0; i < namesAndValues.length - 1; i += 2) { if (namesAndValues[i] == null) throw new IllegalArgumentException("parameter names cannot be nulls"); params.put(namesAndValues[i], namesAndValues[i + 1]); // depends on control dependency: [for], data = [i] } return this; } }
public class class_name { protected void parseOption(CliParserState parserState, String option, CliOptionContainer optionContainer, CliParameterConsumer parameterConsumer) { CliValueContainer valueContainer = this.valueMap.getOrCreate(optionContainer); PojoPropertyAccessorOneArg setter = optionContainer.getSetter(); Class<?> propertyClass = setter.getPropertyClass(); String argument; if (optionContainer.isTrigger()) { argument = "true"; } else if (Boolean.class.equals(propertyClass)) { String lookahead = parameterConsumer.getCurrent(); if ("true".equalsIgnoreCase(lookahead)) { parameterConsumer.getNext(); argument = "true"; } else if ("false".equalsIgnoreCase(lookahead)) { parameterConsumer.getNext(); argument = "false"; } else { // option (e.g. "--trigger") is not followed by "true" or "false" CliStyleHandling handling = this.cliState.getCliStyle().optionMissingBooleanValue(); if (handling != CliStyleHandling.OK) { handling.handle(getLogger(), new CliOptionMissingValueException(option)); } argument = "true"; } } else { if (!parameterConsumer.hasNext()) { throw new CliOptionMissingValueException(option); } argument = parameterConsumer.getNext(); } valueContainer.setValue(argument); } }
public class class_name { protected void parseOption(CliParserState parserState, String option, CliOptionContainer optionContainer, CliParameterConsumer parameterConsumer) { CliValueContainer valueContainer = this.valueMap.getOrCreate(optionContainer); PojoPropertyAccessorOneArg setter = optionContainer.getSetter(); Class<?> propertyClass = setter.getPropertyClass(); String argument; if (optionContainer.isTrigger()) { argument = "true"; // depends on control dependency: [if], data = [none] } else if (Boolean.class.equals(propertyClass)) { String lookahead = parameterConsumer.getCurrent(); if ("true".equalsIgnoreCase(lookahead)) { parameterConsumer.getNext(); // depends on control dependency: [if], data = [none] argument = "true"; // depends on control dependency: [if], data = [none] } else if ("false".equalsIgnoreCase(lookahead)) { parameterConsumer.getNext(); // depends on control dependency: [if], data = [none] argument = "false"; // depends on control dependency: [if], data = [none] } else { // option (e.g. "--trigger") is not followed by "true" or "false" CliStyleHandling handling = this.cliState.getCliStyle().optionMissingBooleanValue(); if (handling != CliStyleHandling.OK) { handling.handle(getLogger(), new CliOptionMissingValueException(option)); // depends on control dependency: [if], data = [none] } argument = "true"; // depends on control dependency: [if], data = [none] } } else { if (!parameterConsumer.hasNext()) { throw new CliOptionMissingValueException(option); } argument = parameterConsumer.getNext(); // depends on control dependency: [if], data = [none] } valueContainer.setValue(argument); } }
public class class_name { public long count(String field, Object val) throws PersistenceException { logger.debug("enter - count(String,Object)"); try { if( logger.isDebugEnabled() ) { logger.debug("For: " + cache.getTarget().getName() + "/" + field + "/" + val); } Class<? extends Execution> cls; SearchTerm[] terms = new SearchTerm[field == null ? 0 : 1]; if( field != null ) { terms[0] = new SearchTerm(field, Operator.EQUALS, val); } String key = getExecKey(terms, false); Map<String,Object> params = toParams(terms); synchronized( this ) { while( !counters.containsKey(key) ) { compileCounter(terms, counters); try { wait(1000L); } catch( InterruptedException ignore ) { /* ignore this */ } } cls = counters.get(key); } if( cls == null ) { throw new PersistenceException("Unable to compile a default counter for field: " + field); } return count(cls, params); } finally { logger.debug("exit - count(String,Object)"); } } }
public class class_name { public long count(String field, Object val) throws PersistenceException { logger.debug("enter - count(String,Object)"); try { if( logger.isDebugEnabled() ) { logger.debug("For: " + cache.getTarget().getName() + "/" + field + "/" + val); // depends on control dependency: [if], data = [none] } Class<? extends Execution> cls; SearchTerm[] terms = new SearchTerm[field == null ? 0 : 1]; if( field != null ) { terms[0] = new SearchTerm(field, Operator.EQUALS, val); // depends on control dependency: [if], data = [none] } String key = getExecKey(terms, false); Map<String,Object> params = toParams(terms); synchronized( this ) { while( !counters.containsKey(key) ) { compileCounter(terms, counters); // depends on control dependency: [while], data = [none] try { wait(1000L); } // depends on control dependency: [try], data = [none] catch( InterruptedException ignore ) { /* ignore this */ } // depends on control dependency: [catch], data = [none] } cls = counters.get(key); } if( cls == null ) { throw new PersistenceException("Unable to compile a default counter for field: " + field); } return count(cls, params); } finally { logger.debug("exit - count(String,Object)"); } } }
public class class_name { private void isolateNextStep(String selector, int start, StepProperties stepProperties) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) tc.entry(cclass, "isolateNextStep", "selector: " + selector + ", start: " + start); int end = -1; boolean wrapWholeStep = false; String subSelector = selector.substring(start); char[] chars = subSelector.toCharArray(); // Is a full stop acceptable - at this stage in processing we should only // have decimal points left. Might want to stop testing this. boolean acceptDot = false; // If we locate a * we assume that we'll need to wrap the whole location step. We // cannot currently distinguish between single levelwildcards and multiplication signs. boolean acceptStar = true; // becomes false on non-separator, true on separator boolean acceptOrdinary = true; // becomes true on separator boolean prevSeparator = true; // Square bracket related boolean acceptOpenBracket = true; boolean acceptCloseBracket = false; int openBracketCount = 0; boolean acceptOpenRoundBracket = false; boolean acceptCloseRoundBracket = false; int openRoundBracketCount = 0; //boolean withinPredicate = false; boolean maybeIntegerPredicate = false; // Process the string character by character try { int subSelectorLength = chars.length; for (int i = 0; i < subSelectorLength; i++) { char cand = chars[i]; // First lets attempt to catch the case where we have a position predicate if(openBracketCount > 0 && maybeIntegerPredicate) { // If we're in a predicate check to see if its integral if(!Character.isDigit(cand) && cand != ']') { maybeIntegerPredicate = false; } } if (cand == MatchSpace.SUBTOPIC_MATCHONE_CHAR) { if (acceptStar) { wrapWholeStep = true; acceptStar = false; //acceptOrdinary = false; acceptDot = false; prevSeparator = false; } else { throw new QuerySyntaxException("Wilcard error: " + subSelector + ", at: " + (i+1)); } } else if (cand == MatchSpace.SUBTOPIC_STOP_CHAR) { if (acceptDot) { if(prevSeparator) { acceptOrdinary = false; } else { acceptOrdinary = true; } acceptStar = prevSeparator = false; } else { throw new QuerySyntaxException("Dot error: " + subSelector + ", at: " + (i+1)); } } else if (cand == MatchSpace.SUBTOPIC_SEPARATOR_CHAR) { // Key bit of code here // Is the separator within brackets? Is it part of a wildcard? or have // we determined the end of a location step? if(openBracketCount == 0 && openRoundBracketCount == 0) { // This is the end of the location step end = i; break; } acceptStar=true; acceptOrdinary = true; acceptDot = true; prevSeparator = true; } else if( cand == '[') { if (acceptOpenBracket) { // Start of a predicate acceptStar = true; acceptOrdinary = true; prevSeparator = false; acceptDot = true; openBracketCount++; // Check for nested predicates if(openBracketCount>1) { wrapWholeStep = true; } //acceptOpenBracket = false; acceptCloseBracket = true; acceptOpenRoundBracket = true; maybeIntegerPredicate = true; } else { throw new QuerySyntaxException("Open Bracket error: " + subSelector + ", at: " + (i+1)); } } else if( cand == ']') { if (acceptCloseBracket) { // End of a predicate acceptStar = true; acceptOrdinary = true; prevSeparator = false; acceptDot = true; acceptOpenBracket = true; openBracketCount--; if(openBracketCount < 0) { throw new QuerySyntaxException("Bracket error: " + subSelector + ", at: " + (i+1)); } //acceptCloseBracket = false; // Test to see whether the predicate was entirely numeric // Looking for department[2], etc if(maybeIntegerPredicate) { maybeIntegerPredicate = false; wrapWholeStep = true; } } else { throw new QuerySyntaxException("Close Bracket error: " + subSelector + ", at: " + (i+1)); } } else if( cand == '(') { if (acceptOpenRoundBracket) { // A function wrapWholeStep = true; acceptStar = true; acceptOrdinary = true; prevSeparator = false; acceptDot = true; acceptOpenRoundBracket = false; acceptCloseRoundBracket = true; openRoundBracketCount++; } else { throw new QuerySyntaxException("Open Round Bracket error: " + subSelector + ", at: " + (i+1)); } } else if( cand == ')') { if (acceptCloseRoundBracket) { // End of a predicate acceptStar = true; acceptOrdinary = true; prevSeparator = false; acceptDot = true; acceptOpenRoundBracket = true; acceptCloseRoundBracket = false; openRoundBracketCount--; } else { throw new QuerySyntaxException("Close Round Bracket error: " + subSelector + ", at: " + (i+1)); } } else // Ordinary character { if (acceptOrdinary) { acceptStar = true; prevSeparator = false; acceptDot = true; acceptOpenRoundBracket = true; } else { throw new QuerySyntaxException("Character error: " + subSelector + ", at: " + (i+1)); } } } // Finished processing char by char, did the brackets pair up ok? if(openBracketCount != 0) { throw new QuerySyntaxException("Matching Bracket error: " + subSelector + ", non-matching square brackets"); } } catch (QuerySyntaxException qex) { // No FFDC Code Needed. // FFDC driven by wrapper class. // This signals that the character parsing encountered a problem, we FFDC // but continue processing FFDC.processException(cclass, "com.ibm.ws.sib.matchspace.selector.impl.XPath10ParserImpl", qex, "1:1377:1.16"); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) tc.debug(this,cclass, "isolateNextStep", qex); } // Set the StepProperties if(wrapWholeStep) stepProperties.wrapStep = true; else stepProperties.wrapStep = false; // Set the end of step value if(end == -1) stepProperties.endOfStep = -1; else { stepProperties.endOfStep = end+start; } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) tc.exit(this,cclass, "isolateNextStep"); } }
public class class_name { private void isolateNextStep(String selector, int start, StepProperties stepProperties) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) tc.entry(cclass, "isolateNextStep", "selector: " + selector + ", start: " + start); int end = -1; boolean wrapWholeStep = false; String subSelector = selector.substring(start); char[] chars = subSelector.toCharArray(); // Is a full stop acceptable - at this stage in processing we should only // have decimal points left. Might want to stop testing this. boolean acceptDot = false; // If we locate a * we assume that we'll need to wrap the whole location step. We // cannot currently distinguish between single levelwildcards and multiplication signs. boolean acceptStar = true; // becomes false on non-separator, true on separator boolean acceptOrdinary = true; // becomes true on separator boolean prevSeparator = true; // Square bracket related boolean acceptOpenBracket = true; boolean acceptCloseBracket = false; int openBracketCount = 0; boolean acceptOpenRoundBracket = false; boolean acceptCloseRoundBracket = false; int openRoundBracketCount = 0; //boolean withinPredicate = false; boolean maybeIntegerPredicate = false; // Process the string character by character try { int subSelectorLength = chars.length; for (int i = 0; i < subSelectorLength; i++) { char cand = chars[i]; // First lets attempt to catch the case where we have a position predicate if(openBracketCount > 0 && maybeIntegerPredicate) { // If we're in a predicate check to see if its integral if(!Character.isDigit(cand) && cand != ']') { maybeIntegerPredicate = false; // depends on control dependency: [if], data = [none] } } if (cand == MatchSpace.SUBTOPIC_MATCHONE_CHAR) { if (acceptStar) { wrapWholeStep = true; // depends on control dependency: [if], data = [none] acceptStar = false; // depends on control dependency: [if], data = [none] //acceptOrdinary = false; acceptDot = false; // depends on control dependency: [if], data = [none] prevSeparator = false; // depends on control dependency: [if], data = [none] } else { throw new QuerySyntaxException("Wilcard error: " + subSelector + ", at: " + (i+1)); } } else if (cand == MatchSpace.SUBTOPIC_STOP_CHAR) { if (acceptDot) { if(prevSeparator) { acceptOrdinary = false; // depends on control dependency: [if], data = [none] } else { acceptOrdinary = true; // depends on control dependency: [if], data = [none] } acceptStar = prevSeparator = false; // depends on control dependency: [if], data = [none] } else { throw new QuerySyntaxException("Dot error: " + subSelector + ", at: " + (i+1)); } } else if (cand == MatchSpace.SUBTOPIC_SEPARATOR_CHAR) { // Key bit of code here // Is the separator within brackets? Is it part of a wildcard? or have // we determined the end of a location step? if(openBracketCount == 0 && openRoundBracketCount == 0) { // This is the end of the location step end = i; // depends on control dependency: [if], data = [none] break; } acceptStar=true; // depends on control dependency: [if], data = [none] acceptOrdinary = true; // depends on control dependency: [if], data = [none] acceptDot = true; // depends on control dependency: [if], data = [none] prevSeparator = true; // depends on control dependency: [if], data = [none] } else if( cand == '[') { if (acceptOpenBracket) { // Start of a predicate acceptStar = true; // depends on control dependency: [if], data = [none] acceptOrdinary = true; // depends on control dependency: [if], data = [none] prevSeparator = false; // depends on control dependency: [if], data = [none] acceptDot = true; // depends on control dependency: [if], data = [none] openBracketCount++; // depends on control dependency: [if], data = [none] // Check for nested predicates if(openBracketCount>1) { wrapWholeStep = true; // depends on control dependency: [if], data = [none] } //acceptOpenBracket = false; acceptCloseBracket = true; // depends on control dependency: [if], data = [none] acceptOpenRoundBracket = true; // depends on control dependency: [if], data = [none] maybeIntegerPredicate = true; // depends on control dependency: [if], data = [none] } else { throw new QuerySyntaxException("Open Bracket error: " + subSelector + ", at: " + (i+1)); } } else if( cand == ']') { if (acceptCloseBracket) { // End of a predicate acceptStar = true; // depends on control dependency: [if], data = [none] acceptOrdinary = true; // depends on control dependency: [if], data = [none] prevSeparator = false; // depends on control dependency: [if], data = [none] acceptDot = true; // depends on control dependency: [if], data = [none] acceptOpenBracket = true; // depends on control dependency: [if], data = [none] openBracketCount--; // depends on control dependency: [if], data = [none] if(openBracketCount < 0) { throw new QuerySyntaxException("Bracket error: " + subSelector + ", at: " + (i+1)); } //acceptCloseBracket = false; // Test to see whether the predicate was entirely numeric // Looking for department[2], etc if(maybeIntegerPredicate) { maybeIntegerPredicate = false; // depends on control dependency: [if], data = [none] wrapWholeStep = true; // depends on control dependency: [if], data = [none] } } else { throw new QuerySyntaxException("Close Bracket error: " + subSelector + ", at: " + (i+1)); } } else if( cand == '(') { if (acceptOpenRoundBracket) { // A function wrapWholeStep = true; // depends on control dependency: [if], data = [none] acceptStar = true; // depends on control dependency: [if], data = [none] acceptOrdinary = true; // depends on control dependency: [if], data = [none] prevSeparator = false; // depends on control dependency: [if], data = [none] acceptDot = true; // depends on control dependency: [if], data = [none] acceptOpenRoundBracket = false; // depends on control dependency: [if], data = [none] acceptCloseRoundBracket = true; // depends on control dependency: [if], data = [none] openRoundBracketCount++; // depends on control dependency: [if], data = [none] } else { throw new QuerySyntaxException("Open Round Bracket error: " + subSelector + ", at: " + (i+1)); } } else if( cand == ')') { if (acceptCloseRoundBracket) { // End of a predicate acceptStar = true; // depends on control dependency: [if], data = [none] acceptOrdinary = true; // depends on control dependency: [if], data = [none] prevSeparator = false; // depends on control dependency: [if], data = [none] acceptDot = true; // depends on control dependency: [if], data = [none] acceptOpenRoundBracket = true; // depends on control dependency: [if], data = [none] acceptCloseRoundBracket = false; // depends on control dependency: [if], data = [none] openRoundBracketCount--; // depends on control dependency: [if], data = [none] } else { throw new QuerySyntaxException("Close Round Bracket error: " + subSelector + ", at: " + (i+1)); } } else // Ordinary character { if (acceptOrdinary) { acceptStar = true; // depends on control dependency: [if], data = [none] prevSeparator = false; // depends on control dependency: [if], data = [none] acceptDot = true; // depends on control dependency: [if], data = [none] acceptOpenRoundBracket = true; // depends on control dependency: [if], data = [none] } else { throw new QuerySyntaxException("Character error: " + subSelector + ", at: " + (i+1)); } } } // Finished processing char by char, did the brackets pair up ok? if(openBracketCount != 0) { throw new QuerySyntaxException("Matching Bracket error: " + subSelector + ", non-matching square brackets"); } } catch (QuerySyntaxException qex) { // No FFDC Code Needed. // FFDC driven by wrapper class. // This signals that the character parsing encountered a problem, we FFDC // but continue processing FFDC.processException(cclass, "com.ibm.ws.sib.matchspace.selector.impl.XPath10ParserImpl", qex, "1:1377:1.16"); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) tc.debug(this,cclass, "isolateNextStep", qex); } // Set the StepProperties if(wrapWholeStep) stepProperties.wrapStep = true; else stepProperties.wrapStep = false; // Set the end of step value if(end == -1) stepProperties.endOfStep = -1; else { stepProperties.endOfStep = end+start; } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) tc.exit(this,cclass, "isolateNextStep"); } }
public class class_name { public String exportRules(Engine engine) { StringBuilder result = new StringBuilder(); result.append("[Rules]\n"); for (RuleBlock ruleBlock : engine.getRuleBlocks()) { if (engine.numberOfRuleBlocks() > 1) { result.append(String.format("# RuleBlock %d", 1 + engine.getRuleBlocks().indexOf(ruleBlock))); } for (Rule rule : ruleBlock.getRules()) { if (rule.isLoaded()) { result.append(exportRule(rule, engine)).append("\n"); } } } return result.toString(); } }
public class class_name { public String exportRules(Engine engine) { StringBuilder result = new StringBuilder(); result.append("[Rules]\n"); for (RuleBlock ruleBlock : engine.getRuleBlocks()) { if (engine.numberOfRuleBlocks() > 1) { result.append(String.format("# RuleBlock %d", 1 + engine.getRuleBlocks().indexOf(ruleBlock))); // depends on control dependency: [if], data = [none] } for (Rule rule : ruleBlock.getRules()) { if (rule.isLoaded()) { result.append(exportRule(rule, engine)).append("\n"); // depends on control dependency: [if], data = [none] } } } return result.toString(); } }
public class class_name { protected List<Message> getMessages(int prefetchBatchSize) throws InterruptedException { assert prefetchBatchSize > 0; ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(queueUrl) .withMaxNumberOfMessages(prefetchBatchSize) .withAttributeNames(ALL) .withMessageAttributeNames(ALL) .withWaitTimeSeconds(WAIT_TIME_SECONDS); //if the receive request is for FIFO queue, provide a unique receive request attempt it, so that //failed calls retried by SDK will claim the same messages if (sqsDestination.isFifo()) { receiveMessageRequest.withReceiveRequestAttemptId(UUID.randomUUID().toString()); } List<Message> messages = null; try { ReceiveMessageResult receivedMessageResult = amazonSQSClient.receiveMessage(receiveMessageRequest); messages = receivedMessageResult.getMessages(); retriesAttempted = 0; } catch (JMSException e) { LOG.warn("Encountered exception during receive in ConsumerPrefetch thread", e); try { sleep(backoffStrategy.delayBeforeNextRetry(retriesAttempted++)); } catch (InterruptedException ex) { LOG.warn("Interrupted while retrying on receive", ex); throw ex; } } return messages; } }
public class class_name { protected List<Message> getMessages(int prefetchBatchSize) throws InterruptedException { assert prefetchBatchSize > 0; ReceiveMessageRequest receiveMessageRequest = new ReceiveMessageRequest(queueUrl) .withMaxNumberOfMessages(prefetchBatchSize) .withAttributeNames(ALL) .withMessageAttributeNames(ALL) .withWaitTimeSeconds(WAIT_TIME_SECONDS); //if the receive request is for FIFO queue, provide a unique receive request attempt it, so that //failed calls retried by SDK will claim the same messages if (sqsDestination.isFifo()) { receiveMessageRequest.withReceiveRequestAttemptId(UUID.randomUUID().toString()); } List<Message> messages = null; try { ReceiveMessageResult receivedMessageResult = amazonSQSClient.receiveMessage(receiveMessageRequest); messages = receivedMessageResult.getMessages(); retriesAttempted = 0; } catch (JMSException e) { LOG.warn("Encountered exception during receive in ConsumerPrefetch thread", e); try { sleep(backoffStrategy.delayBeforeNextRetry(retriesAttempted++)); // depends on control dependency: [try], data = [none] } catch (InterruptedException ex) { LOG.warn("Interrupted while retrying on receive", ex); throw ex; } // depends on control dependency: [catch], data = [none] } return messages; } }
public class class_name { @FromString public static Hours parse(CharSequence text) { Objects.requireNonNull(text, "text"); Matcher matcher = PATTERN.matcher(text); if (matcher.matches()) { int negate = "-".equals(matcher.group(1)) ? -1 : 1; String daysStr = matcher.group(2); String hoursStr = matcher.group(3); if (daysStr != null || hoursStr != null) { int hours = 0; if (hoursStr != null) { try { hours = Integer.parseInt(hoursStr); } catch (NumberFormatException ex) { throw new DateTimeParseException("Text cannot be parsed to Hours, non-numeric hours", text, 0, ex); } } if (daysStr != null) { try { int daysAsHours = Math.multiplyExact(Integer.parseInt(daysStr), HOURS_PER_DAY); hours = Math.addExact(hours, daysAsHours); } catch (NumberFormatException ex) { throw new DateTimeParseException("Text cannot be parsed to Hours, non-numeric days", text, 0, ex); } } return of(Math.multiplyExact(hours, negate)); } } throw new DateTimeParseException("Text cannot be parsed to Hours", text, 0); } }
public class class_name { @FromString public static Hours parse(CharSequence text) { Objects.requireNonNull(text, "text"); Matcher matcher = PATTERN.matcher(text); if (matcher.matches()) { int negate = "-".equals(matcher.group(1)) ? -1 : 1; String daysStr = matcher.group(2); String hoursStr = matcher.group(3); if (daysStr != null || hoursStr != null) { int hours = 0; if (hoursStr != null) { try { hours = Integer.parseInt(hoursStr); // depends on control dependency: [try], data = [none] } catch (NumberFormatException ex) { throw new DateTimeParseException("Text cannot be parsed to Hours, non-numeric hours", text, 0, ex); } // depends on control dependency: [catch], data = [none] } if (daysStr != null) { try { int daysAsHours = Math.multiplyExact(Integer.parseInt(daysStr), HOURS_PER_DAY); hours = Math.addExact(hours, daysAsHours); // depends on control dependency: [try], data = [none] } catch (NumberFormatException ex) { throw new DateTimeParseException("Text cannot be parsed to Hours, non-numeric days", text, 0, ex); } // depends on control dependency: [catch], data = [none] } return of(Math.multiplyExact(hours, negate)); // depends on control dependency: [if], data = [none] } } throw new DateTimeParseException("Text cannot be parsed to Hours", text, 0); } }
public class class_name { protected void validateNew(final CmsAliasTableRow newEntry) { CmsRpcAction<CmsAliasEditValidationReply> action = new CmsRpcAction<CmsAliasEditValidationReply>() { @Override public void execute() { start(200, true); CmsAliasEditValidationRequest validationRequest = new CmsAliasEditValidationRequest(); List<CmsAliasTableRow> rows = m_view.getLiveData(); validationRequest.setEditedData(rows); validationRequest.setNewEntry(newEntry); validationRequest.setOriginalData(m_initialData); getService().validateAliases(validationRequest, this); } @Override public void onResponse(CmsAliasEditValidationReply result) { stop(false); List<CmsAliasTableRow> tableRows = result.getChangedRows(); CmsAliasTableRow validatedNewEntry = result.getValidatedNewEntry(); if (validatedNewEntry.hasErrors()) { m_view.setNewAliasPathError(validatedNewEntry.getAliasError()); m_view.setNewAliasResourceError(validatedNewEntry.getPathError()); } else { m_view.clearNew(); tableRows.add(validatedNewEntry); } m_view.update(tableRows); updateValidationStatus(); } }; action.execute(); } }
public class class_name { protected void validateNew(final CmsAliasTableRow newEntry) { CmsRpcAction<CmsAliasEditValidationReply> action = new CmsRpcAction<CmsAliasEditValidationReply>() { @Override public void execute() { start(200, true); CmsAliasEditValidationRequest validationRequest = new CmsAliasEditValidationRequest(); List<CmsAliasTableRow> rows = m_view.getLiveData(); validationRequest.setEditedData(rows); validationRequest.setNewEntry(newEntry); validationRequest.setOriginalData(m_initialData); getService().validateAliases(validationRequest, this); } @Override public void onResponse(CmsAliasEditValidationReply result) { stop(false); List<CmsAliasTableRow> tableRows = result.getChangedRows(); CmsAliasTableRow validatedNewEntry = result.getValidatedNewEntry(); if (validatedNewEntry.hasErrors()) { m_view.setNewAliasPathError(validatedNewEntry.getAliasError()); // depends on control dependency: [if], data = [none] m_view.setNewAliasResourceError(validatedNewEntry.getPathError()); // depends on control dependency: [if], data = [none] } else { m_view.clearNew(); // depends on control dependency: [if], data = [none] tableRows.add(validatedNewEntry); // depends on control dependency: [if], data = [none] } m_view.update(tableRows); updateValidationStatus(); } }; action.execute(); } }
public class class_name { static String pidListKey(List<String> allJmxAclPids, ObjectName objectName) throws NoSuchAlgorithmException, UnsupportedEncodingException { List<String> pidCandidates = iterateDownPids(nameSegments(objectName)); MessageDigest md = MessageDigest.getInstance("MD5"); for (String pc : pidCandidates) { String generalPid = getGeneralPid(allJmxAclPids, pc); if (generalPid.length() > 0) { md.update(generalPid.getBytes("UTF-8")); } } return Hex.encodeHexString(md.digest()); } }
public class class_name { static String pidListKey(List<String> allJmxAclPids, ObjectName objectName) throws NoSuchAlgorithmException, UnsupportedEncodingException { List<String> pidCandidates = iterateDownPids(nameSegments(objectName)); MessageDigest md = MessageDigest.getInstance("MD5"); for (String pc : pidCandidates) { String generalPid = getGeneralPid(allJmxAclPids, pc); if (generalPid.length() > 0) { md.update(generalPid.getBytes("UTF-8")); // depends on control dependency: [if], data = [none] } } return Hex.encodeHexString(md.digest()); } }
public class class_name { private boolean sendErrorMail(String content, String title) { String localName = ""; try { InetAddress addr = InetAddress.getLocalHost(); localName = addr.getHostName().toString(); } catch (UnknownHostException e) { LOG.warn("When send alarm mail,we can't get hostname", e); } String mailTitle = localName + " /" + ALARM_MAIL_TITLE + "/" + getSystemDate(); int len = 0; int lenLimit = ALARM_MAIL_TITLE_LENGTH; if (title != null) { len = title.length(); if (len > lenLimit) { len = lenLimit; } mailTitle += title.substring(0, len); } String mailTo = emailProperties.getEmailReceiver(); String mailFrom = emailProperties.getFromEmail(); String[] mailToList = mailTo.split(";"); if (content == null) { return false; } else { try { mailBean.sendHtmlMail(mailFrom, mailToList, mailTitle, content); } catch (Exception e) { LOG.warn("When send alarm mail,we can't send it", e); return false; } } return true; } }
public class class_name { private boolean sendErrorMail(String content, String title) { String localName = ""; try { InetAddress addr = InetAddress.getLocalHost(); localName = addr.getHostName().toString(); // depends on control dependency: [try], data = [none] } catch (UnknownHostException e) { LOG.warn("When send alarm mail,we can't get hostname", e); } // depends on control dependency: [catch], data = [none] String mailTitle = localName + " /" + ALARM_MAIL_TITLE + "/" + getSystemDate(); int len = 0; int lenLimit = ALARM_MAIL_TITLE_LENGTH; if (title != null) { len = title.length(); // depends on control dependency: [if], data = [none] if (len > lenLimit) { len = lenLimit; // depends on control dependency: [if], data = [none] } mailTitle += title.substring(0, len); // depends on control dependency: [if], data = [none] } String mailTo = emailProperties.getEmailReceiver(); String mailFrom = emailProperties.getFromEmail(); String[] mailToList = mailTo.split(";"); if (content == null) { return false; // depends on control dependency: [if], data = [none] } else { try { mailBean.sendHtmlMail(mailFrom, mailToList, mailTitle, content); // depends on control dependency: [try], data = [none] } catch (Exception e) { LOG.warn("When send alarm mail,we can't send it", e); return false; } // depends on control dependency: [catch], data = [none] } return true; } }
public class class_name { protected Response createResponse(Status status, NlsRuntimeException error, Map<String, List<String>> errorsMap) { String message; if (this.exposeInternalErrorDetails) { message = getExposedErrorDetails(error); } else { message = error.getLocalizedMessage(); } return createResponse(status, error, message, errorsMap); } }
public class class_name { protected Response createResponse(Status status, NlsRuntimeException error, Map<String, List<String>> errorsMap) { String message; if (this.exposeInternalErrorDetails) { message = getExposedErrorDetails(error); // depends on control dependency: [if], data = [none] } else { message = error.getLocalizedMessage(); // depends on control dependency: [if], data = [none] } return createResponse(status, error, message, errorsMap); } }
public class class_name { public <T> Collection<T> getCollection(String prefix, Function<String, T> factory) { Collection<T> collection = new ArrayList<>(); for (String property : properties.stringPropertyNames()) { if (property.startsWith(prefix + ".")) { collection.add(factory.apply(property)); } } return collection; } }
public class class_name { public <T> Collection<T> getCollection(String prefix, Function<String, T> factory) { Collection<T> collection = new ArrayList<>(); for (String property : properties.stringPropertyNames()) { if (property.startsWith(prefix + ".")) { collection.add(factory.apply(property)); // depends on control dependency: [if], data = [none] } } return collection; } }
public class class_name { public final void removeDirectory(final File directory) { try { FileUtils.deleteDirectory(directory); } catch (IOException e) { LOGGER.error("Unable to delete directory '{}'", directory); } } }
public class class_name { public final void removeDirectory(final File directory) { try { FileUtils.deleteDirectory(directory); // depends on control dependency: [try], data = [none] } catch (IOException e) { LOGGER.error("Unable to delete directory '{}'", directory); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public Result isUTF8(byte[] buffer, boolean rejectNulls) { boolean onlyAscii = true; for (int i = 0; i < buffer.length; i++) { byte len; // make it unsigned for the comparisons int c = (0xFF) & buffer[i]; if (rejectNulls && c == 0) { return Result.INVALID; } if ((c & 0b10000000) == 0) { len = 0; } else if (c >= 194 && c < 224) { len = 1; } else if ((c & 0b11110000) == 0b11100000) { len = 2; } else if ((c & 0b11111000) == 0b11110000) { len = 3; } else { return Result.INVALID; } while (len > 0) { i++; if (i >= buffer.length) { break; } c = (0xFF) & buffer[i]; onlyAscii = false; // first 2 bits should be 10 if ((c & 0b11000000) != 0b10000000) { return Result.INVALID; } len--; } } return onlyAscii ? new Result(Validation.MAYBE, StandardCharsets.UTF_8) : Result.newValid(StandardCharsets.UTF_8); } }
public class class_name { public Result isUTF8(byte[] buffer, boolean rejectNulls) { boolean onlyAscii = true; for (int i = 0; i < buffer.length; i++) { byte len; // make it unsigned for the comparisons int c = (0xFF) & buffer[i]; if (rejectNulls && c == 0) { return Result.INVALID; // depends on control dependency: [if], data = [none] } if ((c & 0b10000000) == 0) { len = 0; // depends on control dependency: [if], data = [none] } else if (c >= 194 && c < 224) { len = 1; // depends on control dependency: [if], data = [none] } else if ((c & 0b11110000) == 0b11100000) { len = 2; // depends on control dependency: [if], data = [none] } else if ((c & 0b11111000) == 0b11110000) { len = 3; // depends on control dependency: [if], data = [none] } else { return Result.INVALID; // depends on control dependency: [if], data = [none] } while (len > 0) { i++; // depends on control dependency: [while], data = [none] if (i >= buffer.length) { break; } c = (0xFF) & buffer[i]; // depends on control dependency: [while], data = [none] onlyAscii = false; // depends on control dependency: [while], data = [none] // first 2 bits should be 10 if ((c & 0b11000000) != 0b10000000) { return Result.INVALID; // depends on control dependency: [if], data = [none] } len--; // depends on control dependency: [while], data = [none] } } return onlyAscii ? new Result(Validation.MAYBE, StandardCharsets.UTF_8) : Result.newValid(StandardCharsets.UTF_8); } }
public class class_name { public static boolean containsThrowableOfType(Throwable throwable, Class<?>... throwableTypes) { List<Throwable> alreadyProcessedThrowables = new ArrayList<Throwable>(); while (true) { if (throwable == null) { // end of the list of causes return false; } else if (alreadyProcessedThrowables.contains(throwable)) { // infinite loop in causes return false; } else { for (Class<?> throwableType : throwableTypes) { if (throwableType.isAssignableFrom(throwable.getClass())) { return true; } } alreadyProcessedThrowables.add(throwable); throwable = throwable.getCause(); } } } }
public class class_name { public static boolean containsThrowableOfType(Throwable throwable, Class<?>... throwableTypes) { List<Throwable> alreadyProcessedThrowables = new ArrayList<Throwable>(); while (true) { if (throwable == null) { // end of the list of causes return false; // depends on control dependency: [if], data = [none] } else if (alreadyProcessedThrowables.contains(throwable)) { // infinite loop in causes return false; // depends on control dependency: [if], data = [none] } else { for (Class<?> throwableType : throwableTypes) { if (throwableType.isAssignableFrom(throwable.getClass())) { return true; // depends on control dependency: [if], data = [none] } } alreadyProcessedThrowables.add(throwable); // depends on control dependency: [if], data = [none] throwable = throwable.getCause(); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public static IndexedContainer getAvailableGroupsContainerWithout( CmsObject cms, String ouFqn, String propCaption, String propIcon, String propOu, List<CmsGroup> blackList, java.util.function.Function<CmsGroup, CmsCssIcon> iconProvider) { if (blackList == null) { blackList = new ArrayList<CmsGroup>(); } IndexedContainer res = new IndexedContainer(); res.addContainerProperty(propCaption, String.class, ""); res.addContainerProperty(propOu, String.class, ""); if (propIcon != null) { res.addContainerProperty(propIcon, CmsCssIcon.class, null); } try { for (CmsGroup group : OpenCms.getRoleManager().getManageableGroups(cms, ouFqn, true)) { if (!blackList.contains(group)) { Item item = res.addItem(group); if (item == null) { continue; } if (iconProvider != null) { item.getItemProperty(propIcon).setValue(iconProvider.apply(group)); } item.getItemProperty(propCaption).setValue(group.getSimpleName()); item.getItemProperty(propOu).setValue(group.getOuFqn()); } } } catch (CmsException e) { LOG.error("Unable to read groups", e); } return res; } }
public class class_name { public static IndexedContainer getAvailableGroupsContainerWithout( CmsObject cms, String ouFqn, String propCaption, String propIcon, String propOu, List<CmsGroup> blackList, java.util.function.Function<CmsGroup, CmsCssIcon> iconProvider) { if (blackList == null) { blackList = new ArrayList<CmsGroup>(); // depends on control dependency: [if], data = [none] } IndexedContainer res = new IndexedContainer(); res.addContainerProperty(propCaption, String.class, ""); res.addContainerProperty(propOu, String.class, ""); if (propIcon != null) { res.addContainerProperty(propIcon, CmsCssIcon.class, null); // depends on control dependency: [if], data = [(propIcon] } try { for (CmsGroup group : OpenCms.getRoleManager().getManageableGroups(cms, ouFqn, true)) { if (!blackList.contains(group)) { Item item = res.addItem(group); if (item == null) { continue; } if (iconProvider != null) { item.getItemProperty(propIcon).setValue(iconProvider.apply(group)); // depends on control dependency: [if], data = [(iconProvider] } item.getItemProperty(propCaption).setValue(group.getSimpleName()); // depends on control dependency: [if], data = [none] item.getItemProperty(propOu).setValue(group.getOuFqn()); // depends on control dependency: [if], data = [none] } } } catch (CmsException e) { LOG.error("Unable to read groups", e); } // depends on control dependency: [catch], data = [none] return res; } }
public class class_name { public Service withDurationHistogram(HistogramEntry... durationHistogram) { if (this.durationHistogram == null) { setDurationHistogram(new java.util.ArrayList<HistogramEntry>(durationHistogram.length)); } for (HistogramEntry ele : durationHistogram) { this.durationHistogram.add(ele); } return this; } }
public class class_name { public Service withDurationHistogram(HistogramEntry... durationHistogram) { if (this.durationHistogram == null) { setDurationHistogram(new java.util.ArrayList<HistogramEntry>(durationHistogram.length)); // depends on control dependency: [if], data = [none] } for (HistogramEntry ele : durationHistogram) { this.durationHistogram.add(ele); // depends on control dependency: [for], data = [ele] } return this; } }
public class class_name { protected WsByteBuffer[] putByte(byte data, WsByteBuffer[] inBuffers) { WsByteBuffer[] buffers = inBuffers; this.byteCache[this.bytePosition] = data; this.bytePosition++; if (this.bytePosition >= this.byteCacheSize) { // full cache, flush it buffers = flushFullCache(buffers); } return buffers; } }
public class class_name { protected WsByteBuffer[] putByte(byte data, WsByteBuffer[] inBuffers) { WsByteBuffer[] buffers = inBuffers; this.byteCache[this.bytePosition] = data; this.bytePosition++; if (this.bytePosition >= this.byteCacheSize) { // full cache, flush it buffers = flushFullCache(buffers); // depends on control dependency: [if], data = [none] } return buffers; } }
public class class_name { public void start(Map<String, Object> options) { MethodCallFilter methodFilter = new MethodCallFilter(); ThreadRunFilter threadFilter = new ThreadRunFilter(); Map<String, Object> opts = new HashMap(defaultOptions); opts.putAll(options); methodFilter.addIncludes((List) opts.get("includeMethods")); methodFilter.addExcludes((List) opts.get("excludeMethods")); threadFilter.addIncludes((List) opts.get("includeThreads")); threadFilter.addExcludes((List) opts.get("excludeThreads")); if (interceptor == null) { this.interceptor = new CallInterceptor(methodFilter, threadFilter); } proxyMetaClasses(); List<Reference> refs = (List) opts.get("references"); if (refs != null) { proxyPerInstanceMetaClasses(refs); } } }
public class class_name { public void start(Map<String, Object> options) { MethodCallFilter methodFilter = new MethodCallFilter(); ThreadRunFilter threadFilter = new ThreadRunFilter(); Map<String, Object> opts = new HashMap(defaultOptions); opts.putAll(options); methodFilter.addIncludes((List) opts.get("includeMethods")); methodFilter.addExcludes((List) opts.get("excludeMethods")); threadFilter.addIncludes((List) opts.get("includeThreads")); threadFilter.addExcludes((List) opts.get("excludeThreads")); if (interceptor == null) { this.interceptor = new CallInterceptor(methodFilter, threadFilter); // depends on control dependency: [if], data = [none] } proxyMetaClasses(); List<Reference> refs = (List) opts.get("references"); if (refs != null) { proxyPerInstanceMetaClasses(refs); // depends on control dependency: [if], data = [(refs] } } }
public class class_name { @Override public void generateSpecializedPart(SQLiteModelMethod method, TypeSpec.Builder classBuilder, MethodSpec.Builder methodBuilder, Set<JQLProjection> fieldList, boolean mapFields) { SQLiteEntity entity = method.getEntity(); ParameterizedTypeName listenerType = ParameterizedTypeName.get(ClassName.get(OnReadBeanListener.class), TypeName.get(entity.getElement().asType())); // List<SQLProperty> fields = fieldList.value1; TypeName entityClass = typeName(entity.getElement()); int counter = SqlBuilderHelper.countParameterOfType(method, listenerType); if (counter == 0) { // non listener found throw (new InvalidMethodSignException(method, "there is no parameter of type \"ReadCursorListener\"")); } if (counter > 1) { // more than one listener found throw (new InvalidMethodSignException(method, "there are more than one parameter of type \"ReadCursorListener\"")); } String listenerName = SqlSelectBuilder.getNameParameterOfType(method, listenerType); // immutable management if (entity.isImmutablePojo()) { methodBuilder.addStatement("$T resultBean=null", entityClass); methodBuilder.addCode("\n"); methodBuilder.addComment("initialize temporary variable for immutable POJO"); ImmutableUtility.generateImmutableVariableInit(entity, methodBuilder); } else { methodBuilder.addStatement("$T resultBean=new $T()", entityClass, entityClass); } methodBuilder.beginControlFlow("if (_cursor.moveToFirst())"); // generate index from columns methodBuilder.addCode("\n"); { int i = 0; for (JQLProjection a : fieldList) { SQLProperty item = a.property; methodBuilder.addStatement("int index$L=_cursor.getColumnIndex($S)", (i++), item.columnName); if (item.hasTypeAdapter()) { methodBuilder.addStatement("$T $LAdapter=$T.getAdapter($T.class)", item.typeAdapter.getAdapterTypeName(), item.getName(), SQLTypeAdapterUtils.class, item.typeAdapter.getAdapterTypeName()); } } } methodBuilder.addCode("\n"); methodBuilder.addCode("int rowCount=_cursor.getCount();\n"); methodBuilder.beginControlFlow("do\n"); // reset mapping methodBuilder.addCode("// reset mapping\n"); { int i = 0; for (SQLProperty item : entity.getCollection()) { if (item.isNullable()) { SQLTransformer.resetBean(methodBuilder, entityClass, "resultBean", item, "_cursor", "index" + i + ""); methodBuilder.addCode(";"); methodBuilder.addCode("\n"); } else { methodBuilder.addCode("// " + item.getName() + " does not need reset (it will be taken from db)\n"); } i++; } } methodBuilder.addCode("\n"); // generate mapping methodBuilder.addCode("// generate mapping\n"); { int i = 0; for (JQLProjection a : fieldList) { SQLProperty item = a.property; if (item.isNullable()) { methodBuilder.addCode("if (!_cursor.isNull(index$L)) { ", i); } SQLTransformer.cursor2Java(methodBuilder, typeName(entity.getElement()), item, "resultBean", "_cursor", "index" + i + ""); methodBuilder.addCode(";"); if (item.isNullable()) { methodBuilder.addCode(" }"); } methodBuilder.addCode("\n"); i++; } } methodBuilder.addCode("\n"); // immutable management if (entity.isImmutablePojo()) { methodBuilder.addComment("define immutable POJO"); ImmutableUtility.generateImmutableEntityCreation(entity, methodBuilder, "resultBean", false); } methodBuilder.addCode("$L.onRead(resultBean, _cursor.getPosition(), rowCount);\n", listenerName); methodBuilder.endControlFlow("while (_cursor.moveToNext())"); // close try { open cursor methodBuilder.endControlFlow(); // close method methodBuilder.endControlFlow(); } }
public class class_name { @Override public void generateSpecializedPart(SQLiteModelMethod method, TypeSpec.Builder classBuilder, MethodSpec.Builder methodBuilder, Set<JQLProjection> fieldList, boolean mapFields) { SQLiteEntity entity = method.getEntity(); ParameterizedTypeName listenerType = ParameterizedTypeName.get(ClassName.get(OnReadBeanListener.class), TypeName.get(entity.getElement().asType())); // List<SQLProperty> fields = fieldList.value1; TypeName entityClass = typeName(entity.getElement()); int counter = SqlBuilderHelper.countParameterOfType(method, listenerType); if (counter == 0) { // non listener found throw (new InvalidMethodSignException(method, "there is no parameter of type \"ReadCursorListener\"")); } if (counter > 1) { // more than one listener found throw (new InvalidMethodSignException(method, "there are more than one parameter of type \"ReadCursorListener\"")); } String listenerName = SqlSelectBuilder.getNameParameterOfType(method, listenerType); // immutable management if (entity.isImmutablePojo()) { methodBuilder.addStatement("$T resultBean=null", entityClass); // depends on control dependency: [if], data = [none] methodBuilder.addCode("\n"); // depends on control dependency: [if], data = [none] methodBuilder.addComment("initialize temporary variable for immutable POJO"); // depends on control dependency: [if], data = [none] ImmutableUtility.generateImmutableVariableInit(entity, methodBuilder); // depends on control dependency: [if], data = [none] } else { methodBuilder.addStatement("$T resultBean=new $T()", entityClass, entityClass); // depends on control dependency: [if], data = [none] } methodBuilder.beginControlFlow("if (_cursor.moveToFirst())"); // generate index from columns methodBuilder.addCode("\n"); { int i = 0; for (JQLProjection a : fieldList) { SQLProperty item = a.property; methodBuilder.addStatement("int index$L=_cursor.getColumnIndex($S)", (i++), item.columnName); // depends on control dependency: [for], data = [a] if (item.hasTypeAdapter()) { methodBuilder.addStatement("$T $LAdapter=$T.getAdapter($T.class)", item.typeAdapter.getAdapterTypeName(), item.getName(), SQLTypeAdapterUtils.class, item.typeAdapter.getAdapterTypeName()); // depends on control dependency: [if], data = [none] } } } methodBuilder.addCode("\n"); methodBuilder.addCode("int rowCount=_cursor.getCount();\n"); methodBuilder.beginControlFlow("do\n"); // reset mapping methodBuilder.addCode("// reset mapping\n"); { int i = 0; for (SQLProperty item : entity.getCollection()) { if (item.isNullable()) { SQLTransformer.resetBean(methodBuilder, entityClass, "resultBean", item, "_cursor", "index" + i + ""); // depends on control dependency: [if], data = [none] methodBuilder.addCode(";"); // depends on control dependency: [if], data = [none] methodBuilder.addCode("\n"); // depends on control dependency: [if], data = [none] } else { methodBuilder.addCode("// " + item.getName() + " does not need reset (it will be taken from db)\n"); } i++; // depends on control dependency: [if], data = [none] } } methodBuilder.addCode("\n"); // generate mapping methodBuilder.addCode("// generate mapping\n"); { int i = 0; for (JQLProjection a : fieldList) { SQLProperty item = a.property; if (item.isNullable()) { methodBuilder.addCode("if (!_cursor.isNull(index$L)) { ", i); // depends on control dependency: [if], data = [none] } SQLTransformer.cursor2Java(methodBuilder, typeName(entity.getElement()), item, "resultBean", "_cursor", "index" + i + ""); // depends on control dependency: [for], data = [a] methodBuilder.addCode(";"); // depends on control dependency: [for], data = [a] if (item.isNullable()) { methodBuilder.addCode(" }"); // depends on control dependency: [if], data = [none] } methodBuilder.addCode("\n"); // depends on control dependency: [for], data = [a] i++; // depends on control dependency: [for], data = [none] } } methodBuilder.addCode("\n"); // immutable management if (entity.isImmutablePojo()) { methodBuilder.addComment("define immutable POJO"); ImmutableUtility.generateImmutableEntityCreation(entity, methodBuilder, "resultBean", false); } methodBuilder.addCode("$L.onRead(resultBean, _cursor.getPosition(), rowCount);\n", listenerName); methodBuilder.endControlFlow("while (_cursor.moveToNext())"); // close try { open cursor methodBuilder.endControlFlow(); // close method methodBuilder.endControlFlow(); } }
public class class_name { public static AssociationKeyMetadata getInverseAssociationKeyMetadata(OgmEntityPersister mainSidePersister, int propertyIndex) { Type propertyType = mainSidePersister.getPropertyTypes()[propertyIndex]; SessionFactoryImplementor factory = mainSidePersister.getFactory(); // property represents no association, so no inverse meta-data can exist if ( !propertyType.isAssociationType() ) { return null; } Joinable mainSideJoinable = ( (AssociationType) propertyType ).getAssociatedJoinable( factory ); OgmEntityPersister inverseSidePersister = null; // to-many association if ( mainSideJoinable.isCollection() ) { inverseSidePersister = (OgmEntityPersister) ( (OgmCollectionPersister) mainSideJoinable ).getElementPersister(); } // to-one else { inverseSidePersister = (OgmEntityPersister) mainSideJoinable; mainSideJoinable = mainSidePersister; } String mainSideProperty = mainSidePersister.getPropertyNames()[propertyIndex]; // property is a one-to-one association (a many-to-one cannot be on the inverse side) -> get the meta-data // straight from the main-side persister AssociationKeyMetadata inverseOneToOneMetadata = mainSidePersister.getInverseOneToOneAssociationKeyMetadata( mainSideProperty ); if ( inverseOneToOneMetadata != null ) { return inverseOneToOneMetadata; } // process properties of inverse side and try to find association back to main side for ( String candidateProperty : inverseSidePersister.getPropertyNames() ) { Type type = inverseSidePersister.getPropertyType( candidateProperty ); // candidate is a *-to-many association if ( type.isCollectionType() ) { OgmCollectionPersister inverseCollectionPersister = getPersister( factory, (CollectionType) type ); String mappedByProperty = inverseCollectionPersister.getMappedByProperty(); if ( mainSideProperty.equals( mappedByProperty ) ) { if ( isCollectionMatching( mainSideJoinable, inverseCollectionPersister ) ) { return inverseCollectionPersister.getAssociationKeyMetadata(); } } } } return null; } }
public class class_name { public static AssociationKeyMetadata getInverseAssociationKeyMetadata(OgmEntityPersister mainSidePersister, int propertyIndex) { Type propertyType = mainSidePersister.getPropertyTypes()[propertyIndex]; SessionFactoryImplementor factory = mainSidePersister.getFactory(); // property represents no association, so no inverse meta-data can exist if ( !propertyType.isAssociationType() ) { return null; // depends on control dependency: [if], data = [none] } Joinable mainSideJoinable = ( (AssociationType) propertyType ).getAssociatedJoinable( factory ); OgmEntityPersister inverseSidePersister = null; // to-many association if ( mainSideJoinable.isCollection() ) { inverseSidePersister = (OgmEntityPersister) ( (OgmCollectionPersister) mainSideJoinable ).getElementPersister(); // depends on control dependency: [if], data = [none] } // to-one else { inverseSidePersister = (OgmEntityPersister) mainSideJoinable; // depends on control dependency: [if], data = [none] mainSideJoinable = mainSidePersister; // depends on control dependency: [if], data = [none] } String mainSideProperty = mainSidePersister.getPropertyNames()[propertyIndex]; // property is a one-to-one association (a many-to-one cannot be on the inverse side) -> get the meta-data // straight from the main-side persister AssociationKeyMetadata inverseOneToOneMetadata = mainSidePersister.getInverseOneToOneAssociationKeyMetadata( mainSideProperty ); if ( inverseOneToOneMetadata != null ) { return inverseOneToOneMetadata; // depends on control dependency: [if], data = [none] } // process properties of inverse side and try to find association back to main side for ( String candidateProperty : inverseSidePersister.getPropertyNames() ) { Type type = inverseSidePersister.getPropertyType( candidateProperty ); // candidate is a *-to-many association if ( type.isCollectionType() ) { OgmCollectionPersister inverseCollectionPersister = getPersister( factory, (CollectionType) type ); String mappedByProperty = inverseCollectionPersister.getMappedByProperty(); if ( mainSideProperty.equals( mappedByProperty ) ) { if ( isCollectionMatching( mainSideJoinable, inverseCollectionPersister ) ) { return inverseCollectionPersister.getAssociationKeyMetadata(); // depends on control dependency: [if], data = [none] } } } } return null; } }
public class class_name { public void setUrl(String url) { Properties p = org.postgresql.Driver.parseURL(url, null); if (p == null) { throw new IllegalArgumentException("URL invalid " + url); } for (PGProperty property : PGProperty.values()) { if (!this.properties.containsKey(property.getName())) { setProperty(property, property.get(p)); } } } }
public class class_name { public void setUrl(String url) { Properties p = org.postgresql.Driver.parseURL(url, null); if (p == null) { throw new IllegalArgumentException("URL invalid " + url); } for (PGProperty property : PGProperty.values()) { if (!this.properties.containsKey(property.getName())) { setProperty(property, property.get(p)); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public FontChooser setSelectedFontStyle(int style) { for (int i = 0; i < FONT_STYLE_CODES.length; i++) { if (FONT_STYLE_CODES[i] == style) { getFontStyleList().setSelectedIndex(i); break; } } updateSampleFont(); return this; } }
public class class_name { public FontChooser setSelectedFontStyle(int style) { for (int i = 0; i < FONT_STYLE_CODES.length; i++) { if (FONT_STYLE_CODES[i] == style) { getFontStyleList().setSelectedIndex(i); // depends on control dependency: [if], data = [none] break; } } updateSampleFont(); return this; } }
public class class_name { private static Provider getDefaultProvider() { // approach 1 try { String providerClass = System.getProperty("org.joda.time.DateTimeZone.Provider"); if (providerClass != null) { try { // do not initialize the class until the type has been checked Class<?> cls = Class.forName(providerClass, false, DateTimeZone.class.getClassLoader()); if (!Provider.class.isAssignableFrom(cls)) { throw new IllegalArgumentException("System property referred to class that does not implement " + Provider.class); } Provider provider = cls.asSubclass(Provider.class).getConstructor().newInstance(); return validateProvider(provider); } catch (Exception ex) { throw new RuntimeException(ex); } } } catch (SecurityException ex) { // ignored } // approach 2 try { String dataFolder = System.getProperty("org.joda.time.DateTimeZone.Folder"); if (dataFolder != null) { try { Provider provider = new ZoneInfoProvider(new File(dataFolder)); return validateProvider(provider); } catch (Exception ex) { throw new RuntimeException(ex); } } } catch (SecurityException ex) { // ignored } // approach 3 try { Provider provider = new ZoneInfoProvider(DEFAULT_TZ_DATA_PATH); return validateProvider(provider); } catch (Exception ex) { ex.printStackTrace(); } // approach 4 return new UTCProvider(); } }
public class class_name { private static Provider getDefaultProvider() { // approach 1 try { String providerClass = System.getProperty("org.joda.time.DateTimeZone.Provider"); if (providerClass != null) { try { // do not initialize the class until the type has been checked Class<?> cls = Class.forName(providerClass, false, DateTimeZone.class.getClassLoader()); if (!Provider.class.isAssignableFrom(cls)) { throw new IllegalArgumentException("System property referred to class that does not implement " + Provider.class); } Provider provider = cls.asSubclass(Provider.class).getConstructor().newInstance(); return validateProvider(provider); // depends on control dependency: [try], data = [none] } catch (Exception ex) { throw new RuntimeException(ex); } // depends on control dependency: [catch], data = [none] } } catch (SecurityException ex) { // ignored } // depends on control dependency: [catch], data = [none] // approach 2 try { String dataFolder = System.getProperty("org.joda.time.DateTimeZone.Folder"); if (dataFolder != null) { try { Provider provider = new ZoneInfoProvider(new File(dataFolder)); return validateProvider(provider); // depends on control dependency: [try], data = [none] } catch (Exception ex) { throw new RuntimeException(ex); } // depends on control dependency: [catch], data = [none] } } catch (SecurityException ex) { // ignored } // depends on control dependency: [catch], data = [none] // approach 3 try { Provider provider = new ZoneInfoProvider(DEFAULT_TZ_DATA_PATH); return validateProvider(provider); // depends on control dependency: [try], data = [none] } catch (Exception ex) { ex.printStackTrace(); } // depends on control dependency: [catch], data = [none] // approach 4 return new UTCProvider(); } }
public class class_name { public List<Type> getAllInterfaces(Type type, Configuration configuration, boolean sort) { Map<ClassDoc,Type> results = sort ? new TreeMap<ClassDoc,Type>() : new LinkedHashMap<ClassDoc,Type>(); Type[] interfaceTypes = null; Type superType = null; if (type instanceof ParameterizedType) { interfaceTypes = ((ParameterizedType) type).interfaceTypes(); superType = ((ParameterizedType) type).superclassType(); } else if (type instanceof ClassDoc) { interfaceTypes = ((ClassDoc) type).interfaceTypes(); superType = ((ClassDoc) type).superclassType(); } else { interfaceTypes = type.asClassDoc().interfaceTypes(); superType = type.asClassDoc().superclassType(); } for (Type interfaceType : interfaceTypes) { ClassDoc interfaceClassDoc = interfaceType.asClassDoc(); if (!(interfaceClassDoc.isPublic() || (configuration == null || isLinkable(interfaceClassDoc, configuration)))) { continue; } results.put(interfaceClassDoc, interfaceType); for (Type t : getAllInterfaces(interfaceType, configuration, sort)) { results.put(t.asClassDoc(), t); } } if (superType == null) return new ArrayList<>(results.values()); //Try walking the tree. addAllInterfaceTypes(results, superType, interfaceTypesOf(superType), false, configuration); List<Type> resultsList = new ArrayList<>(results.values()); if (sort) { Collections.sort(resultsList, new TypeComparator()); } return resultsList; } }
public class class_name { public List<Type> getAllInterfaces(Type type, Configuration configuration, boolean sort) { Map<ClassDoc,Type> results = sort ? new TreeMap<ClassDoc,Type>() : new LinkedHashMap<ClassDoc,Type>(); Type[] interfaceTypes = null; Type superType = null; if (type instanceof ParameterizedType) { interfaceTypes = ((ParameterizedType) type).interfaceTypes(); // depends on control dependency: [if], data = [none] superType = ((ParameterizedType) type).superclassType(); // depends on control dependency: [if], data = [none] } else if (type instanceof ClassDoc) { interfaceTypes = ((ClassDoc) type).interfaceTypes(); // depends on control dependency: [if], data = [none] superType = ((ClassDoc) type).superclassType(); // depends on control dependency: [if], data = [none] } else { interfaceTypes = type.asClassDoc().interfaceTypes(); // depends on control dependency: [if], data = [none] superType = type.asClassDoc().superclassType(); // depends on control dependency: [if], data = [none] } for (Type interfaceType : interfaceTypes) { ClassDoc interfaceClassDoc = interfaceType.asClassDoc(); if (!(interfaceClassDoc.isPublic() || (configuration == null || isLinkable(interfaceClassDoc, configuration)))) { continue; } results.put(interfaceClassDoc, interfaceType); // depends on control dependency: [for], data = [interfaceType] for (Type t : getAllInterfaces(interfaceType, configuration, sort)) { results.put(t.asClassDoc(), t); // depends on control dependency: [for], data = [t] } } if (superType == null) return new ArrayList<>(results.values()); //Try walking the tree. addAllInterfaceTypes(results, superType, interfaceTypesOf(superType), false, configuration); List<Type> resultsList = new ArrayList<>(results.values()); if (sort) { Collections.sort(resultsList, new TypeComparator()); // depends on control dependency: [if], data = [none] } return resultsList; } }
public class class_name { public void notifyClients() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "notifyClients"); // We'll only fire events if eventing is enabled or depths are being monitored // (510343) if (isThresholdNotificationRequired()) { long totalItems = getTotalMsgCount(); synchronized (this) { if (wlmRemoved && ((_destLowMsgs == -1) || (totalItems <= _destLowMsgs))) { wlmRemoved = false; // Fire event fireDepthThresholdReachedEvent(getControlAdapter(), false, totalItems, _destLowMsgs); // Reached low } else if (!wlmRemoved && (_destHighMsgs != -1) && (_destLowMsgs != -1) && (totalItems >= _destHighMsgs)) { wlmRemoved = true; // Fire event fireDepthThresholdReachedEvent(getControlAdapter(), true, totalItems, _destHighMsgs); // Reached High } } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "notifyClients"); } }
public class class_name { public void notifyClients() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "notifyClients"); // We'll only fire events if eventing is enabled or depths are being monitored // (510343) if (isThresholdNotificationRequired()) { long totalItems = getTotalMsgCount(); synchronized (this) // depends on control dependency: [if], data = [none] { if (wlmRemoved && ((_destLowMsgs == -1) || (totalItems <= _destLowMsgs))) { wlmRemoved = false; // depends on control dependency: [if], data = [none] // Fire event fireDepthThresholdReachedEvent(getControlAdapter(), false, totalItems, _destLowMsgs); // Reached low // depends on control dependency: [if], data = [none] } else if (!wlmRemoved && (_destHighMsgs != -1) && (_destLowMsgs != -1) && (totalItems >= _destHighMsgs)) { wlmRemoved = true; // depends on control dependency: [if], data = [none] // Fire event fireDepthThresholdReachedEvent(getControlAdapter(), true, totalItems, _destHighMsgs); // Reached High // depends on control dependency: [if], data = [none] } } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "notifyClients"); } }
public class class_name { @SuppressWarnings("unchecked") public <T> T get(EventLocal<T> key) { EventLocalMap<EventLocal<?>, Object> map = getMap(key); if (null == map) { return key.initialValue(); } return (T) map.get(key); } }
public class class_name { @SuppressWarnings("unchecked") public <T> T get(EventLocal<T> key) { EventLocalMap<EventLocal<?>, Object> map = getMap(key); if (null == map) { return key.initialValue(); // depends on control dependency: [if], data = [none] } return (T) map.get(key); } }