code
stringlengths
130
281k
code_dependency
stringlengths
182
306k
public class class_name { public static boolean setStyle(PolylineOptions polylineOptions, StyleRow style, float density) { if (style != null) { Color color = style.getColorOrDefault(); polylineOptions.color(color.getColorWithAlpha()); double width = style.getWidthOrDefault(); polylineOptions.width((float) width * density); } return style != null; } }
public class class_name { public static boolean setStyle(PolylineOptions polylineOptions, StyleRow style, float density) { if (style != null) { Color color = style.getColorOrDefault(); polylineOptions.color(color.getColorWithAlpha()); // depends on control dependency: [if], data = [none] double width = style.getWidthOrDefault(); polylineOptions.width((float) width * density); // depends on control dependency: [if], data = [none] } return style != null; } }
public class class_name { public static InetAddress getIPHostAddress(String host) { InetAddress result = null; Matcher matcher = IPV4_QUADS.matcher(host); if (matcher == null || !matcher.matches()) { return result; } try { // Doing an Inet.getByAddress() avoids a lookup. result = InetAddress.getByAddress(host, new byte[] { (byte)(new Integer(matcher.group(1)).intValue()), (byte)(new Integer(matcher.group(2)).intValue()), (byte)(new Integer(matcher.group(3)).intValue()), (byte)(new Integer(matcher.group(4)).intValue())}); } catch (NumberFormatException e) { logger.warning(e.getMessage()); } catch (UnknownHostException e) { logger.warning(e.getMessage()); } return result; } }
public class class_name { public static InetAddress getIPHostAddress(String host) { InetAddress result = null; Matcher matcher = IPV4_QUADS.matcher(host); if (matcher == null || !matcher.matches()) { return result; // depends on control dependency: [if], data = [none] } try { // Doing an Inet.getByAddress() avoids a lookup. result = InetAddress.getByAddress(host, new byte[] { (byte)(new Integer(matcher.group(1)).intValue()), (byte)(new Integer(matcher.group(2)).intValue()), (byte)(new Integer(matcher.group(3)).intValue()), (byte)(new Integer(matcher.group(4)).intValue())}); // depends on control dependency: [try], data = [none] } catch (NumberFormatException e) { logger.warning(e.getMessage()); } catch (UnknownHostException e) { // depends on control dependency: [catch], data = [none] logger.warning(e.getMessage()); } // depends on control dependency: [catch], data = [none] return result; } }
public class class_name { protected <E extends RaftLogEntry> CompletableFuture<Indexed<E>> appendAndCompact(E entry, int attempt) { if (attempt == MAX_APPEND_ATTEMPTS) { return Futures.exceptionalFuture(new StorageException.OutOfDiskSpace("Not enough space to append entry")); } else { try { return CompletableFuture.completedFuture(raft.getLogWriter().append(entry)) .thenApply(indexed -> { log.trace("Appended {}", indexed); return indexed; }); } catch (StorageException.TooLarge e) { return Futures.exceptionalFuture(e); } catch (StorageException.OutOfDiskSpace e) { log.warn("Caught OutOfDiskSpace error! Force compacting logs..."); return raft.getServiceManager().compact().thenCompose(v -> appendAndCompact(entry, attempt + 1)); } } } }
public class class_name { protected <E extends RaftLogEntry> CompletableFuture<Indexed<E>> appendAndCompact(E entry, int attempt) { if (attempt == MAX_APPEND_ATTEMPTS) { return Futures.exceptionalFuture(new StorageException.OutOfDiskSpace("Not enough space to append entry")); // depends on control dependency: [if], data = [none] } else { try { return CompletableFuture.completedFuture(raft.getLogWriter().append(entry)) .thenApply(indexed -> { log.trace("Appended {}", indexed); // depends on control dependency: [try], data = [none] return indexed; // depends on control dependency: [try], data = [none] }); } catch (StorageException.TooLarge e) { return Futures.exceptionalFuture(e); } catch (StorageException.OutOfDiskSpace e) { // depends on control dependency: [catch], data = [none] log.warn("Caught OutOfDiskSpace error! Force compacting logs..."); return raft.getServiceManager().compact().thenCompose(v -> appendAndCompact(entry, attempt + 1)); } // depends on control dependency: [catch], data = [none] } } }
public class class_name { private static void transform(final String xmlFileName, final String xsltFileName, final String outputFileName) { Source xsltSource = null; if (StringUtils.isNotBlank(xsltFileName)) { // Use the given stylesheet. xsltSource = new StreamSource(new File(xsltFileName)); } else { // Use the default stylesheet. xsltSource = new StreamSource(Thread.currentThread().getContextClassLoader().getResourceAsStream(DEFAULT_XSLT_SHEET)); } // Transform the given input file and put the result in the given output file. final Source xmlSource = new StreamSource(new File(xmlFileName)); final Result xmlResult = new StreamResult(new File(outputFileName)); XmlUtils.transform(xmlSource, xsltSource, xmlResult); } }
public class class_name { private static void transform(final String xmlFileName, final String xsltFileName, final String outputFileName) { Source xsltSource = null; if (StringUtils.isNotBlank(xsltFileName)) { // Use the given stylesheet. xsltSource = new StreamSource(new File(xsltFileName)); // depends on control dependency: [if], data = [none] } else { // Use the default stylesheet. xsltSource = new StreamSource(Thread.currentThread().getContextClassLoader().getResourceAsStream(DEFAULT_XSLT_SHEET)); // depends on control dependency: [if], data = [none] } // Transform the given input file and put the result in the given output file. final Source xmlSource = new StreamSource(new File(xmlFileName)); final Result xmlResult = new StreamResult(new File(outputFileName)); XmlUtils.transform(xmlSource, xsltSource, xmlResult); } }
public class class_name { @Override @SuppressWarnings("unchecked") public <T> T fromValueMap(final Map<String, Value> valueMap, final Class<T> cls) { T newInstance = Reflection.newInstance( cls ); ValueMap map = ( ValueMap ) ( Map ) valueMap; Map<String, FieldAccess> fields = fieldsAccessor.getFields( cls); Map.Entry<String, Object>[] entries; FieldAccess field = null; String fieldName = null; Map.Entry<String, Object> entry; int size; /* if the map is not hydrated get its entries right form the array to avoid collection creations. */ if ( !map.hydrated() ) { size = map.len(); entries = map.items(); } else { size = map.size(); entries = ( Map.Entry<String, Object>[] ) map.entrySet().toArray( new Map.Entry[size] ); } /* guard. We should check if this is still needed. * I might have added it for debugging and forgot to remove it.*/ if ( size == 0 || entries == null ) { return newInstance; } /* Iterate through the entries. */ for ( int index = 0; index < size; index++ ) { Object value = null; try { entry = entries[index]; fieldName = entry.getKey(); if ( ignoreSet != null ) { if ( ignoreSet.contains( fieldName ) ) { continue; } } field = fields.get(fieldsAccessor.isCaseInsensitive() ? fieldName.toLowerCase() : fieldName); if ( field == null ) { continue; } if ( view != null ) { if ( !field.isViewActive( view ) ) { continue; } } if ( respectIgnore ) { if ( field.ignore() ) { continue; } } value = entry.getValue(); if ( value instanceof Value ) { fromValueMapHandleValueCase( newInstance, field, ( Value ) value ); } else { fromMapHandleNonValueCase( newInstance, field, value ); } }catch (Exception ex) { return (T) Exceptions.handle(Object.class, ex, "fieldName", fieldName, "of class", cls, "had issues for value", value, "for field", field); } } return newInstance; } }
public class class_name { @Override @SuppressWarnings("unchecked") public <T> T fromValueMap(final Map<String, Value> valueMap, final Class<T> cls) { T newInstance = Reflection.newInstance( cls ); ValueMap map = ( ValueMap ) ( Map ) valueMap; Map<String, FieldAccess> fields = fieldsAccessor.getFields( cls); Map.Entry<String, Object>[] entries; FieldAccess field = null; String fieldName = null; Map.Entry<String, Object> entry; int size; /* if the map is not hydrated get its entries right form the array to avoid collection creations. */ if ( !map.hydrated() ) { size = map.len(); // depends on control dependency: [if], data = [none] entries = map.items(); // depends on control dependency: [if], data = [none] } else { size = map.size(); // depends on control dependency: [if], data = [none] entries = ( Map.Entry<String, Object>[] ) map.entrySet().toArray( new Map.Entry[size] ); // depends on control dependency: [if], data = [none] } /* guard. We should check if this is still needed. * I might have added it for debugging and forgot to remove it.*/ if ( size == 0 || entries == null ) { return newInstance; // depends on control dependency: [if], data = [none] } /* Iterate through the entries. */ for ( int index = 0; index < size; index++ ) { Object value = null; try { entry = entries[index]; // depends on control dependency: [try], data = [none] fieldName = entry.getKey(); // depends on control dependency: [try], data = [none] if ( ignoreSet != null ) { if ( ignoreSet.contains( fieldName ) ) { continue; } } field = fields.get(fieldsAccessor.isCaseInsensitive() ? fieldName.toLowerCase() : fieldName); // depends on control dependency: [try], data = [none] if ( field == null ) { continue; } if ( view != null ) { if ( !field.isViewActive( view ) ) { continue; } } if ( respectIgnore ) { if ( field.ignore() ) { continue; } } value = entry.getValue(); // depends on control dependency: [try], data = [none] if ( value instanceof Value ) { fromValueMapHandleValueCase( newInstance, field, ( Value ) value ); // depends on control dependency: [if], data = [none] } else { fromMapHandleNonValueCase( newInstance, field, value ); // depends on control dependency: [if], data = [none] } }catch (Exception ex) { return (T) Exceptions.handle(Object.class, ex, "fieldName", fieldName, "of class", cls, "had issues for value", value, "for field", field); } // depends on control dependency: [catch], data = [none] } return newInstance; } }
public class class_name { public static boolean containsUnpackedBootstrap(IPath directory) { final IFile location = ResourcesPlugin.getWorkspace().getRoot().getFile(directory); if (location != null) { final IPath path = location.getLocation(); if (path != null) { final File file = path.toFile(); if (file.exists()) { if (file.isDirectory()) { return containsUnpackedBootstrap(file); } return false; } } } return containsUnpackedBootstrap(directory.makeAbsolute().toFile()); } }
public class class_name { public static boolean containsUnpackedBootstrap(IPath directory) { final IFile location = ResourcesPlugin.getWorkspace().getRoot().getFile(directory); if (location != null) { final IPath path = location.getLocation(); if (path != null) { final File file = path.toFile(); if (file.exists()) { if (file.isDirectory()) { return containsUnpackedBootstrap(file); // depends on control dependency: [if], data = [none] } return false; // depends on control dependency: [if], data = [none] } } } return containsUnpackedBootstrap(directory.makeAbsolute().toFile()); } }
public class class_name { private boolean onSuggestionsKey(View v, int keyCode, KeyEvent event) { // guard against possible race conditions (late arrival after dismiss) if (mSearchable == null) { return false; } if (mSuggestionsAdapter == null) { return false; } if (event.getAction() == KeyEvent.ACTION_DOWN && KeyEventCompat.hasNoModifiers(event)) { // First, check for enter or search (both of which we'll treat as a // "click") if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_SEARCH || keyCode == KeyEvent.KEYCODE_TAB) { int position = mQueryTextView.getListSelection(); return onItemClicked(position, KeyEvent.KEYCODE_UNKNOWN, null); } // Next, check for left/right moves, which we use to "return" the // user to the edit view if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) { // give "focus" to text editor, with cursor at the beginning if // left key, at end if right key // TODO: Reverse left/right for right-to-left languages, e.g. // Arabic int selPoint = (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) ? 0 : mQueryTextView .length(); mQueryTextView.setSelection(selPoint); mQueryTextView.setListSelection(0); mQueryTextView.clearListSelection(); ensureImeVisible(mQueryTextView, true); return true; } // Next, check for an "up and out" move if (keyCode == KeyEvent.KEYCODE_DPAD_UP && 0 == mQueryTextView.getListSelection()) { // TODO: restoreUserQuery(); // let ACTV complete the move return false; } // Next, check for an "action key" // TODO SearchableInfo.ActionKeyInfo actionKey = mSearchable.findActionKey(keyCode); // TODO if ((actionKey != null) // TODO && ((actionKey.getSuggestActionMsg() != null) || (actionKey // TODO .getSuggestActionMsgColumn() != null))) { // TODO // launch suggestion using action key column // TODO int position = mQueryTextView.getListSelection(); // TODO if (position != ListView.INVALID_POSITION) { // TODO Cursor c = mSuggestionsAdapter.getCursor(); // TODO if (c.moveToPosition(position)) { // TODO final String actionMsg = getActionKeyMessage(c, actionKey); // TODO if (actionMsg != null && (actionMsg.length() > 0)) { // TODO return onItemClicked(position, keyCode, actionMsg); // TODO } // TODO } // TODO } // TODO } } return false; } }
public class class_name { private boolean onSuggestionsKey(View v, int keyCode, KeyEvent event) { // guard against possible race conditions (late arrival after dismiss) if (mSearchable == null) { return false; // depends on control dependency: [if], data = [none] } if (mSuggestionsAdapter == null) { return false; // depends on control dependency: [if], data = [none] } if (event.getAction() == KeyEvent.ACTION_DOWN && KeyEventCompat.hasNoModifiers(event)) { // First, check for enter or search (both of which we'll treat as a // "click") if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_SEARCH || keyCode == KeyEvent.KEYCODE_TAB) { int position = mQueryTextView.getListSelection(); return onItemClicked(position, KeyEvent.KEYCODE_UNKNOWN, null); // depends on control dependency: [if], data = [none] } // Next, check for left/right moves, which we use to "return" the // user to the edit view if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT || keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) { // give "focus" to text editor, with cursor at the beginning if // left key, at end if right key // TODO: Reverse left/right for right-to-left languages, e.g. // Arabic int selPoint = (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) ? 0 : mQueryTextView .length(); mQueryTextView.setSelection(selPoint); // depends on control dependency: [if], data = [none] mQueryTextView.setListSelection(0); // depends on control dependency: [if], data = [none] mQueryTextView.clearListSelection(); // depends on control dependency: [if], data = [none] ensureImeVisible(mQueryTextView, true); // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } // Next, check for an "up and out" move if (keyCode == KeyEvent.KEYCODE_DPAD_UP && 0 == mQueryTextView.getListSelection()) { // TODO: restoreUserQuery(); // let ACTV complete the move return false; // depends on control dependency: [if], data = [none] } // Next, check for an "action key" // TODO SearchableInfo.ActionKeyInfo actionKey = mSearchable.findActionKey(keyCode); // TODO if ((actionKey != null) // TODO && ((actionKey.getSuggestActionMsg() != null) || (actionKey // TODO .getSuggestActionMsgColumn() != null))) { // TODO // launch suggestion using action key column // TODO int position = mQueryTextView.getListSelection(); // TODO if (position != ListView.INVALID_POSITION) { // TODO Cursor c = mSuggestionsAdapter.getCursor(); // TODO if (c.moveToPosition(position)) { // TODO final String actionMsg = getActionKeyMessage(c, actionKey); // TODO if (actionMsg != null && (actionMsg.length() > 0)) { // TODO return onItemClicked(position, keyCode, actionMsg); // TODO } // TODO } // TODO } // TODO } } return false; } }
public class class_name { protected boolean setChecked(WebElement checkElement, WebElement clickElement, boolean checked) { log.debug("check.element", checkElement, clickElement, checked); if (checkElement.isSelected() != checked) { click(clickElement); return true; } return false; } }
public class class_name { protected boolean setChecked(WebElement checkElement, WebElement clickElement, boolean checked) { log.debug("check.element", checkElement, clickElement, checked); if (checkElement.isSelected() != checked) { click(clickElement); // depends on control dependency: [if], data = [none] return true; // depends on control dependency: [if], data = [none] } return false; } }
public class class_name { public static final void fileDump(String fileName, byte[] data) { System.out.println("FILE DUMP"); try { FileOutputStream os = new FileOutputStream(fileName); os.write(data); os.close(); } catch (IOException ex) { ex.printStackTrace(); } } }
public class class_name { public static final void fileDump(String fileName, byte[] data) { System.out.println("FILE DUMP"); try { FileOutputStream os = new FileOutputStream(fileName); os.write(data); // depends on control dependency: [try], data = [none] os.close(); // depends on control dependency: [try], data = [none] } catch (IOException ex) { ex.printStackTrace(); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private boolean isRecording(Endpoint endpoint) { List<RecordProcessor> processors = endpoint.getRecordProcessors(); if (processors == null || processors.isEmpty()) { return false; } for (RecordProcessor processor : processors) { if (processor.isRecording()) { return true; } } return false; } }
public class class_name { private boolean isRecording(Endpoint endpoint) { List<RecordProcessor> processors = endpoint.getRecordProcessors(); if (processors == null || processors.isEmpty()) { return false; // depends on control dependency: [if], data = [none] } for (RecordProcessor processor : processors) { if (processor.isRecording()) { return true; // depends on control dependency: [if], data = [none] } } return false; } }
public class class_name { public void setMetrics(java.util.Collection<String> metrics) { if (metrics == null) { this.metrics = null; return; } this.metrics = new java.util.ArrayList<String>(metrics); } }
public class class_name { public void setMetrics(java.util.Collection<String> metrics) { if (metrics == null) { this.metrics = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.metrics = new java.util.ArrayList<String>(metrics); } }
public class class_name { protected void addNamespaceContext() { NamespaceMap prefixmap = new NamespaceMap(); NamespacePrefixList npl = getXsd().getNamespaceContext(); if (npl == null) { /* We get an NPE if we don't add this. */ prefixmap.add("", XMLConstants.W3C_XML_SCHEMA_NS_URI); } else { for (int i = 0; i < npl.getDeclaredPrefixes().length; i++) { prefixmap.add(npl.getDeclaredPrefixes()[i], npl.getNamespaceURI(npl.getDeclaredPrefixes()[i])); } } prefixmap.add(getCOXBNamespacePrefix(), getCOXBNamespace()); getXsd().setNamespaceContext(prefixmap); } }
public class class_name { protected void addNamespaceContext() { NamespaceMap prefixmap = new NamespaceMap(); NamespacePrefixList npl = getXsd().getNamespaceContext(); if (npl == null) { /* We get an NPE if we don't add this. */ prefixmap.add("", XMLConstants.W3C_XML_SCHEMA_NS_URI); // depends on control dependency: [if], data = [none] } else { for (int i = 0; i < npl.getDeclaredPrefixes().length; i++) { prefixmap.add(npl.getDeclaredPrefixes()[i], npl.getNamespaceURI(npl.getDeclaredPrefixes()[i])); // depends on control dependency: [for], data = [i] } } prefixmap.add(getCOXBNamespacePrefix(), getCOXBNamespace()); getXsd().setNamespaceContext(prefixmap); } }
public class class_name { public synchronized void add(String logSinkClass) { try { if (logSinkClass==null || logSinkClass.length()==0) logSinkClass="org.browsermob.proxy.jetty.log.OutputStreamLogSink"; Class sinkClass = Loader.loadClass(this.getClass(),logSinkClass); LogSink sink=(LogSink)sinkClass.newInstance(); add(sink); } catch(Exception e) { message(WARN,e,2); throw new IllegalArgumentException(e.toString()); } } }
public class class_name { public synchronized void add(String logSinkClass) { try { if (logSinkClass==null || logSinkClass.length()==0) logSinkClass="org.browsermob.proxy.jetty.log.OutputStreamLogSink"; Class sinkClass = Loader.loadClass(this.getClass(),logSinkClass); // depends on control dependency: [try], data = [none] LogSink sink=(LogSink)sinkClass.newInstance(); add(sink); // depends on control dependency: [try], data = [none] } catch(Exception e) { message(WARN,e,2); throw new IllegalArgumentException(e.toString()); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static String parseNamePartFromEmailAddressIfNecessary(final String username) { if (StringUtils.isBlank(username)) { return null; } final int idx = username.indexOf('@'); if (idx == -1) { return username; } return username.substring(0, idx); } }
public class class_name { public static String parseNamePartFromEmailAddressIfNecessary(final String username) { if (StringUtils.isBlank(username)) { return null; // depends on control dependency: [if], data = [none] } final int idx = username.indexOf('@'); if (idx == -1) { return username; // depends on control dependency: [if], data = [none] } return username.substring(0, idx); } }
public class class_name { private void readCommands() { try { final Enumeration<URL> urls = Thread.currentThread().getContextClassLoader() .getResources(XmlCommands.FILEPATH); while (urls.hasMoreElements()) { URL url = urls.nextElement(); InputStream in = url.openStream(); for (Command command : XmlCommands.fromXml(in)) { commands.put(command.getCommand(), command); } } } catch (IOException e) { throw new RuntimeException(e); } } }
public class class_name { private void readCommands() { try { final Enumeration<URL> urls = Thread.currentThread().getContextClassLoader() .getResources(XmlCommands.FILEPATH); while (urls.hasMoreElements()) { URL url = urls.nextElement(); InputStream in = url.openStream(); for (Command command : XmlCommands.fromXml(in)) { commands.put(command.getCommand(), command); // depends on control dependency: [for], data = [command] } } } catch (IOException e) { throw new RuntimeException(e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static BigDecimal sumBtgValue(HashMap<String, String> sepaParams, Integer max) { if (max == null) return new BigDecimal(sepaParams.get("btg.value")); BigDecimal sum = BigDecimal.ZERO; String curr = null; for (int index = 0; index <= max; index++) { sum = sum.add(new BigDecimal(sepaParams.get(insertIndex("btg.value", index)))); // Sicherstellen, dass alle Transaktionen die gleiche Währung verwenden String indexCurr = sepaParams.get(insertIndex("btg.curr", index)); if (curr != null) { if (!curr.equals(indexCurr)) { throw new InvalidArgumentException("mixed currencies on multiple transactions"); } } else { curr = indexCurr; } } return sum; } }
public class class_name { public static BigDecimal sumBtgValue(HashMap<String, String> sepaParams, Integer max) { if (max == null) return new BigDecimal(sepaParams.get("btg.value")); BigDecimal sum = BigDecimal.ZERO; String curr = null; for (int index = 0; index <= max; index++) { sum = sum.add(new BigDecimal(sepaParams.get(insertIndex("btg.value", index)))); // Sicherstellen, dass alle Transaktionen die gleiche Währung verwenden String indexCurr = sepaParams.get(insertIndex("btg.curr", index)); if (curr != null) { if (!curr.equals(indexCurr)) { throw new InvalidArgumentException("mixed currencies on multiple transactions"); } } else { curr = indexCurr; // depends on control dependency: [if], data = [none] } } return sum; } }
public class class_name { public EClass getIfcPositivePlaneAngleMeasure() { if (ifcPositivePlaneAngleMeasureEClass == null) { ifcPositivePlaneAngleMeasureEClass = (EClass) EPackage.Registry.INSTANCE .getEPackage(Ifc2x3tc1Package.eNS_URI).getEClassifiers().get(768); } return ifcPositivePlaneAngleMeasureEClass; } }
public class class_name { public EClass getIfcPositivePlaneAngleMeasure() { if (ifcPositivePlaneAngleMeasureEClass == null) { ifcPositivePlaneAngleMeasureEClass = (EClass) EPackage.Registry.INSTANCE .getEPackage(Ifc2x3tc1Package.eNS_URI).getEClassifiers().get(768); // depends on control dependency: [if], data = [none] } return ifcPositivePlaneAngleMeasureEClass; } }
public class class_name { public IGlobalScope getGlobal(String name) { if (name == null) { return null; } return globals.get(name); } }
public class class_name { public IGlobalScope getGlobal(String name) { if (name == null) { return null; // depends on control dependency: [if], data = [none] } return globals.get(name); } }
public class class_name { private void saveToPropertyVfsBundle() throws CmsException { for (Locale l : m_changedTranslations) { SortedProperties props = m_localizations.get(l); LockedFile f = m_lockedBundleFiles.get(l); if ((null != props) && (null != f)) { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Writer writer = new OutputStreamWriter(outputStream, f.getEncoding()); props.store(writer, null); byte[] contentBytes = outputStream.toByteArray(); CmsFile file = f.getFile(); file.setContents(contentBytes); String contentEncodingProperty = m_cms.readPropertyObject( file, CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING, false).getValue(); if ((null == contentEncodingProperty) || !contentEncodingProperty.equals(f.getEncoding())) { m_cms.writePropertyObject( m_cms.getSitePath(file), new CmsProperty( CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING, f.getEncoding(), f.getEncoding())); } m_cms.writeFile(file); } catch (IOException e) { LOG.error( Messages.get().getBundle().key( Messages.ERR_READING_FILE_UNSUPPORTED_ENCODING_2, f.getFile().getRootPath(), f.getEncoding()), e); } } } } }
public class class_name { private void saveToPropertyVfsBundle() throws CmsException { for (Locale l : m_changedTranslations) { SortedProperties props = m_localizations.get(l); LockedFile f = m_lockedBundleFiles.get(l); if ((null != props) && (null != f)) { try { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Writer writer = new OutputStreamWriter(outputStream, f.getEncoding()); props.store(writer, null); // depends on control dependency: [try], data = [none] byte[] contentBytes = outputStream.toByteArray(); CmsFile file = f.getFile(); file.setContents(contentBytes); // depends on control dependency: [try], data = [none] String contentEncodingProperty = m_cms.readPropertyObject( file, CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING, false).getValue(); if ((null == contentEncodingProperty) || !contentEncodingProperty.equals(f.getEncoding())) { m_cms.writePropertyObject( m_cms.getSitePath(file), new CmsProperty( CmsPropertyDefinition.PROPERTY_CONTENT_ENCODING, f.getEncoding(), f.getEncoding())); // depends on control dependency: [if], data = [none] } m_cms.writeFile(file); // depends on control dependency: [try], data = [none] } catch (IOException e) { LOG.error( Messages.get().getBundle().key( Messages.ERR_READING_FILE_UNSUPPORTED_ENCODING_2, f.getFile().getRootPath(), f.getEncoding()), e); } // depends on control dependency: [catch], data = [none] } } } }
public class class_name { private JMethod getAddHandlerMethodForObject(JClassType objectType, JClassType handlerType) throws UnableToCompleteException { JMethod handlerMethod = null; JMethod alternativeHandlerMethod = null; for (JMethod method : objectType.getInheritableMethods()) { // Condition 1: returns HandlerRegistration? if (method.getReturnType() == handlerRegistrationJClass) { // Condition 2: single parameter of the same type of // handlerType? JParameter[] parameters = method.getParameters(); if (parameters.length != 1) { continue; } JType subjectHandler = parameters[0].getType(); if (handlerType.equals(subjectHandler)) { // Condition 3: does more than one method match the // condition? if (handlerMethod != null) { logger.die( ("This handler cannot be generated. Methods '%s' and '%s' are " + "ambiguous. Which one to pick?"), method, handlerMethod); } handlerMethod = method; } /** * Normalize the parameter and check for an alternative handler * method. Might be the case where the given objectType is * generic. In this situation we need to normalize the method * parameter to test for equality. For instance: * * handlerType => TableHandler<String> subjectHandler => * TableHandler * * This is done as an alternative handler method to preserve the * original logic. */ JParameterizedType ptype = handlerType.isParameterized(); if (ptype != null) { if (subjectHandler.equals(ptype.getRawType())) { alternativeHandlerMethod = method; } } } } return (handlerMethod != null) ? handlerMethod : alternativeHandlerMethod; } }
public class class_name { private JMethod getAddHandlerMethodForObject(JClassType objectType, JClassType handlerType) throws UnableToCompleteException { JMethod handlerMethod = null; JMethod alternativeHandlerMethod = null; for (JMethod method : objectType.getInheritableMethods()) { // Condition 1: returns HandlerRegistration? if (method.getReturnType() == handlerRegistrationJClass) { // Condition 2: single parameter of the same type of // handlerType? JParameter[] parameters = method.getParameters(); if (parameters.length != 1) { continue; } JType subjectHandler = parameters[0].getType(); if (handlerType.equals(subjectHandler)) { // Condition 3: does more than one method match the // condition? if (handlerMethod != null) { logger.die( ("This handler cannot be generated. Methods '%s' and '%s' are " + "ambiguous. Which one to pick?"), method, handlerMethod); // depends on control dependency: [if], data = [none] } handlerMethod = method; // depends on control dependency: [if], data = [none] } /** * Normalize the parameter and check for an alternative handler * method. Might be the case where the given objectType is * generic. In this situation we need to normalize the method * parameter to test for equality. For instance: * * handlerType => TableHandler<String> subjectHandler => * TableHandler * * This is done as an alternative handler method to preserve the * original logic. */ JParameterizedType ptype = handlerType.isParameterized(); if (ptype != null) { if (subjectHandler.equals(ptype.getRawType())) { alternativeHandlerMethod = method; // depends on control dependency: [if], data = [none] } } } } return (handlerMethod != null) ? handlerMethod : alternativeHandlerMethod; } }
public class class_name { public static List<BankInfo> searchBankInfo(String query) { if (query != null) query = query.trim(); List<BankInfo> list = new LinkedList<BankInfo>(); if (query == null || query.length() < 3) return list; query = query.toLowerCase(); for (BankInfo info : banks.values()) { String blz = info.getBlz(); String bic = info.getBic(); String name = info.getName(); String loc = info.getLocation(); // Anhand der BLZ? if (blz != null && blz.startsWith(query)) { list.add(info); continue; } // Anhand der BIC? if (bic != null && bic.toLowerCase().startsWith(query)) { list.add(info); continue; } // Anhand des Namens? if (name != null && name.toLowerCase().contains(query)) { list.add(info); continue; } // Anhand des Orts? if (loc != null && loc.toLowerCase().contains(query)) { list.add(info); continue; } } Collections.sort(list, new Comparator<BankInfo>() { /** * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ @Override public int compare(BankInfo o1, BankInfo o2) { if (o1 == null || o1.getBlz() == null) return -1; if (o2 == null || o2.getBlz() == null) return 1; return o1.getBlz().compareTo(o2.getBlz()); } }); return list; } }
public class class_name { public static List<BankInfo> searchBankInfo(String query) { if (query != null) query = query.trim(); List<BankInfo> list = new LinkedList<BankInfo>(); if (query == null || query.length() < 3) return list; query = query.toLowerCase(); for (BankInfo info : banks.values()) { String blz = info.getBlz(); String bic = info.getBic(); String name = info.getName(); String loc = info.getLocation(); // Anhand der BLZ? if (blz != null && blz.startsWith(query)) { list.add(info); // depends on control dependency: [if], data = [none] continue; } // Anhand der BIC? if (bic != null && bic.toLowerCase().startsWith(query)) { list.add(info); // depends on control dependency: [if], data = [none] continue; } // Anhand des Namens? if (name != null && name.toLowerCase().contains(query)) { list.add(info); // depends on control dependency: [if], data = [none] continue; } // Anhand des Orts? if (loc != null && loc.toLowerCase().contains(query)) { list.add(info); // depends on control dependency: [if], data = [none] continue; } } Collections.sort(list, new Comparator<BankInfo>() { /** * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ @Override public int compare(BankInfo o1, BankInfo o2) { if (o1 == null || o1.getBlz() == null) return -1; if (o2 == null || o2.getBlz() == null) return 1; return o1.getBlz().compareTo(o2.getBlz()); } }); return list; } }
public class class_name { public final List<TargetFile> createTargetFileList() { if (tflProducerConfig == null) { LOG.info("Using target file list: {} elements", targetFiles.size()); return targetFiles; } final TargetFileListProducer producer = tflProducerConfig.getTargetFileListProducer(); LOG.info("Using target file list producer: {}", producer.getClass().getName()); return producer.createTargetFiles(); } }
public class class_name { public final List<TargetFile> createTargetFileList() { if (tflProducerConfig == null) { LOG.info("Using target file list: {} elements", targetFiles.size()); // depends on control dependency: [if], data = [none] return targetFiles; // depends on control dependency: [if], data = [none] } final TargetFileListProducer producer = tflProducerConfig.getTargetFileListProducer(); LOG.info("Using target file list producer: {}", producer.getClass().getName()); return producer.createTargetFiles(); } }
public class class_name { public Matrix4f setColumn(int column, Vector4fc src) throws IndexOutOfBoundsException { switch (column) { case 0: if (src instanceof Vector4f) { MemUtil.INSTANCE.getColumn0(this, (Vector4f) src); } else { this._m00(src.x()); this._m01(src.y()); this._m02(src.z()); this._m03(src.w()); } break; case 1: if (src instanceof Vector4f) { MemUtil.INSTANCE.getColumn1(this, (Vector4f) src); } else { this._m10(src.x()); this._m11(src.y()); this._m12(src.z()); this._m13(src.w()); } break; case 2: if (src instanceof Vector4f) { MemUtil.INSTANCE.getColumn2(this, (Vector4f) src); } else { this._m20(src.x()); this._m21(src.y()); this._m22(src.z()); this._m23(src.w()); } break; case 3: if (src instanceof Vector4f) { MemUtil.INSTANCE.getColumn3(this, (Vector4f) src); } else { this._m30(src.x()); this._m31(src.y()); this._m32(src.z()); this._m33(src.w()); } break; default: throw new IndexOutOfBoundsException(); } _properties(0); return this; } }
public class class_name { public Matrix4f setColumn(int column, Vector4fc src) throws IndexOutOfBoundsException { switch (column) { case 0: if (src instanceof Vector4f) { MemUtil.INSTANCE.getColumn0(this, (Vector4f) src); // depends on control dependency: [if], data = [none] } else { this._m00(src.x()); // depends on control dependency: [if], data = [none] this._m01(src.y()); // depends on control dependency: [if], data = [none] this._m02(src.z()); // depends on control dependency: [if], data = [none] this._m03(src.w()); // depends on control dependency: [if], data = [none] } break; case 1: if (src instanceof Vector4f) { MemUtil.INSTANCE.getColumn1(this, (Vector4f) src); // depends on control dependency: [if], data = [none] } else { this._m10(src.x()); // depends on control dependency: [if], data = [none] this._m11(src.y()); // depends on control dependency: [if], data = [none] this._m12(src.z()); // depends on control dependency: [if], data = [none] this._m13(src.w()); // depends on control dependency: [if], data = [none] } break; case 2: if (src instanceof Vector4f) { MemUtil.INSTANCE.getColumn2(this, (Vector4f) src); // depends on control dependency: [if], data = [none] } else { this._m20(src.x()); // depends on control dependency: [if], data = [none] this._m21(src.y()); // depends on control dependency: [if], data = [none] this._m22(src.z()); // depends on control dependency: [if], data = [none] this._m23(src.w()); // depends on control dependency: [if], data = [none] } break; case 3: if (src instanceof Vector4f) { MemUtil.INSTANCE.getColumn3(this, (Vector4f) src); // depends on control dependency: [if], data = [none] } else { this._m30(src.x()); // depends on control dependency: [if], data = [none] this._m31(src.y()); // depends on control dependency: [if], data = [none] this._m32(src.z()); // depends on control dependency: [if], data = [none] this._m33(src.w()); // depends on control dependency: [if], data = [none] } break; default: throw new IndexOutOfBoundsException(); } _properties(0); return this; } }
public class class_name { public static boolean sendHttpResponse( boolean isSuccess, HttpExchange exchange, byte[] response) { int returnCode = isSuccess ? HttpURLConnection.HTTP_OK : HttpURLConnection.HTTP_UNAVAILABLE; try { exchange.sendResponseHeaders(returnCode, response.length); } catch (IOException e) { LOG.log(Level.SEVERE, "Failed to send response headers: ", e); return false; } OutputStream os = exchange.getResponseBody(); try { os.write(response); } catch (IOException e) { LOG.log(Level.SEVERE, "Failed to send http response: ", e); return false; } finally { try { os.close(); } catch (IOException e) { LOG.log(Level.SEVERE, "Failed to close OutputStream: ", e); return false; } } return true; } }
public class class_name { public static boolean sendHttpResponse( boolean isSuccess, HttpExchange exchange, byte[] response) { int returnCode = isSuccess ? HttpURLConnection.HTTP_OK : HttpURLConnection.HTTP_UNAVAILABLE; try { exchange.sendResponseHeaders(returnCode, response.length); // depends on control dependency: [try], data = [none] } catch (IOException e) { LOG.log(Level.SEVERE, "Failed to send response headers: ", e); return false; } // depends on control dependency: [catch], data = [none] OutputStream os = exchange.getResponseBody(); try { os.write(response); // depends on control dependency: [try], data = [none] } catch (IOException e) { LOG.log(Level.SEVERE, "Failed to send http response: ", e); return false; } finally { // depends on control dependency: [catch], data = [none] try { os.close(); // depends on control dependency: [try], data = [none] } catch (IOException e) { LOG.log(Level.SEVERE, "Failed to close OutputStream: ", e); return false; } // depends on control dependency: [catch], data = [none] } return true; } }
public class class_name { public void repairLocalCommandsVersion(final Queue<ListCommand> localCommands, final ListCommand originalRemoteCommand) { localCommands.add(repairCommand(localCommands.poll(), originalRemoteCommand.getListVersionChange() .getToVersion(), randomUUID())); final int count = localCommands.size(); for (int i = 1; i < count; i++) { localCommands.add(repairCommand(localCommands.poll(), randomUUID(), randomUUID())); } } }
public class class_name { public void repairLocalCommandsVersion(final Queue<ListCommand> localCommands, final ListCommand originalRemoteCommand) { localCommands.add(repairCommand(localCommands.poll(), originalRemoteCommand.getListVersionChange() .getToVersion(), randomUUID())); final int count = localCommands.size(); for (int i = 1; i < count; i++) { localCommands.add(repairCommand(localCommands.poll(), randomUUID(), randomUUID())); // depends on control dependency: [for], data = [none] } } }
public class class_name { static Set<String> serviceNames(Service<HttpRequest, HttpResponse> service) { if (thriftServiceClass == null || entriesMethod == null || interfacesMethod == null) { return ImmutableSet.of(); } return service.as(thriftServiceClass) .map(s -> { @SuppressWarnings("unchecked") final Map<String, ?> entries = (Map<String, ?>) invokeMethod(entriesMethod, s); assert entries != null; return toServiceName(entries.values()); }) .orElse(ImmutableSet.of()); } }
public class class_name { static Set<String> serviceNames(Service<HttpRequest, HttpResponse> service) { if (thriftServiceClass == null || entriesMethod == null || interfacesMethod == null) { return ImmutableSet.of(); // depends on control dependency: [if], data = [none] } return service.as(thriftServiceClass) .map(s -> { @SuppressWarnings("unchecked") final Map<String, ?> entries = (Map<String, ?>) invokeMethod(entriesMethod, s); assert entries != null; return toServiceName(entries.values()); }) .orElse(ImmutableSet.of()); } }
public class class_name { public void setForeground(Drawable drawable) { if (mForeground != drawable) { if (mForeground != null) { mForeground.setCallback(null); unscheduleDrawable(mForeground); } mForeground = drawable; if (drawable != null) { setWillNotDraw(false); drawable.setCallback(this); if (drawable.isStateful()) { drawable.setState(getDrawableState()); } if (mForegroundGravity == Gravity.FILL) { Rect padding = new Rect(); drawable.getPadding(padding); } } else { setWillNotDraw(true); } requestLayout(); invalidate(); } } }
public class class_name { public void setForeground(Drawable drawable) { if (mForeground != drawable) { if (mForeground != null) { mForeground.setCallback(null); // depends on control dependency: [if], data = [null)] unscheduleDrawable(mForeground); // depends on control dependency: [if], data = [(mForeground] } mForeground = drawable; // depends on control dependency: [if], data = [none] if (drawable != null) { setWillNotDraw(false); // depends on control dependency: [if], data = [none] drawable.setCallback(this); // depends on control dependency: [if], data = [none] if (drawable.isStateful()) { drawable.setState(getDrawableState()); // depends on control dependency: [if], data = [none] } if (mForegroundGravity == Gravity.FILL) { Rect padding = new Rect(); drawable.getPadding(padding); // depends on control dependency: [if], data = [none] } } else { setWillNotDraw(true); // depends on control dependency: [if], data = [none] } requestLayout(); // depends on control dependency: [if], data = [none] invalidate(); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void copyTo(RelatedItemAdditionalProperties copyTo) { copyTo.numberOfProperties = numberOfProperties; RelatedItemAdditionalProperty[] copyToProperties = copyTo.additionalProperties; RelatedItemAdditionalProperty[] srcToProperties = this.additionalProperties; for(int i=0;i<numberOfProperties;i++) { srcToProperties[i].copyTo(copyToProperties[i]); } } }
public class class_name { public void copyTo(RelatedItemAdditionalProperties copyTo) { copyTo.numberOfProperties = numberOfProperties; RelatedItemAdditionalProperty[] copyToProperties = copyTo.additionalProperties; RelatedItemAdditionalProperty[] srcToProperties = this.additionalProperties; for(int i=0;i<numberOfProperties;i++) { srcToProperties[i].copyTo(copyToProperties[i]); // depends on control dependency: [for], data = [i] } } }
public class class_name { public void clearHandleList() { final boolean isTracingEnabled = TraceComponent.isAnyTracingEnabled(); if (isTracingEnabled && tc.isDebugEnabled()) { Tr.debug(this, tc, "Clear the McWrapper handlelist for the following MCWrapper: " + this); } // since we know we are only in this method on a destroy or clean up // of a MCWrapper ,we can double check that all the handles that this MCWrapper // owns are removed from the handlelist on thread local storage before clearing the // handlelist in the MCWrapper class. I tried to be really careful to avoid NPEs // // Liberty doesn't have real HandleList so don't need to remove anything // mcwHandleList.clear(); } }
public class class_name { public void clearHandleList() { final boolean isTracingEnabled = TraceComponent.isAnyTracingEnabled(); if (isTracingEnabled && tc.isDebugEnabled()) { Tr.debug(this, tc, "Clear the McWrapper handlelist for the following MCWrapper: " + this); // depends on control dependency: [if], data = [none] } // since we know we are only in this method on a destroy or clean up // of a MCWrapper ,we can double check that all the handles that this MCWrapper // owns are removed from the handlelist on thread local storage before clearing the // handlelist in the MCWrapper class. I tried to be really careful to avoid NPEs // // Liberty doesn't have real HandleList so don't need to remove anything // mcwHandleList.clear(); } }
public class class_name { @Override public void ok(Object value) { ViewResolver<Object> resolver = viewResolver(); if (resolver != null && resolver.render(this, value)) { return; } log.warning(L.l("{0} does not have a matching view type", value)); halt(HttpStatus.INTERNAL_SERVER_ERROR); } }
public class class_name { @Override public void ok(Object value) { ViewResolver<Object> resolver = viewResolver(); if (resolver != null && resolver.render(this, value)) { return; // depends on control dependency: [if], data = [none] } log.warning(L.l("{0} does not have a matching view type", value)); halt(HttpStatus.INTERNAL_SERVER_ERROR); } }
public class class_name { void setKeyFrame(Planar<I> input, ImagePixelTo3D pixelTo3D) { InputSanityCheck.checkSameShape(derivX,input); wrapI.wrap(input); keypixels.reset(); for (int y = 0; y < input.height; y++) { for (int x = 0; x < input.width; x++) { // See if there's a valid 3D point at this location if( !pixelTo3D.process(x,y) ) { continue; } float P_x = (float)pixelTo3D.getX(); float P_y = (float)pixelTo3D.getY(); float P_z = (float)pixelTo3D.getZ(); float P_w = (float)pixelTo3D.getW(); // skip point if it's at infinity or has a negative value if( P_w <= 0 ) continue; // save the results Pixel p = keypixels.grow(); p.valid = true; wrapI.get(x,y,p.bands); p.x = x; p.y = y; p.p3.set(P_x/P_w,P_y/P_w,P_z/P_w); } } } }
public class class_name { void setKeyFrame(Planar<I> input, ImagePixelTo3D pixelTo3D) { InputSanityCheck.checkSameShape(derivX,input); wrapI.wrap(input); keypixels.reset(); for (int y = 0; y < input.height; y++) { for (int x = 0; x < input.width; x++) { // See if there's a valid 3D point at this location if( !pixelTo3D.process(x,y) ) { continue; } float P_x = (float)pixelTo3D.getX(); float P_y = (float)pixelTo3D.getY(); float P_z = (float)pixelTo3D.getZ(); float P_w = (float)pixelTo3D.getW(); // skip point if it's at infinity or has a negative value if( P_w <= 0 ) continue; // save the results Pixel p = keypixels.grow(); p.valid = true; // depends on control dependency: [for], data = [none] wrapI.get(x,y,p.bands); // depends on control dependency: [for], data = [x] p.x = x; // depends on control dependency: [for], data = [x] p.y = y; // depends on control dependency: [for], data = [none] p.p3.set(P_x/P_w,P_y/P_w,P_z/P_w); // depends on control dependency: [for], data = [none] } } } }
public class class_name { public synchronized void initPathToResourceBundleMap(List<JoinableResourceBundle> bundles) throws IOException { for (JoinableResourceBundle bundle : bundles) { // Remove bundle reference from existing mapping if exists removePathMappingFromPathMap(bundle); List<PathMapping> mappings = bundle.getMappings(); for (PathMapping pathMapping : mappings) { register(pathMapping); } // Register file path mapping for linked resources List<FilePathMapping> fMappings = bundle.getLinkedFilePathMappings(); for (FilePathMapping fMapping : fMappings) { register(fMapping); } } } }
public class class_name { public synchronized void initPathToResourceBundleMap(List<JoinableResourceBundle> bundles) throws IOException { for (JoinableResourceBundle bundle : bundles) { // Remove bundle reference from existing mapping if exists removePathMappingFromPathMap(bundle); List<PathMapping> mappings = bundle.getMappings(); for (PathMapping pathMapping : mappings) { register(pathMapping); // depends on control dependency: [for], data = [pathMapping] } // Register file path mapping for linked resources List<FilePathMapping> fMappings = bundle.getLinkedFilePathMappings(); for (FilePathMapping fMapping : fMappings) { register(fMapping); // depends on control dependency: [for], data = [fMapping] } } } }
public class class_name { @Override public Object convert(String value) { if (value == null || value.isEmpty()) { return value; } Object result = Ints.tryParse(value); if (result != null) { return result; } result = Longs.tryParse(value); if (result != null) { return result; } result = Doubles.tryParse(value); if (result != null) { return result; } return value; } }
public class class_name { @Override public Object convert(String value) { if (value == null || value.isEmpty()) { return value; // depends on control dependency: [if], data = [none] } Object result = Ints.tryParse(value); if (result != null) { return result; // depends on control dependency: [if], data = [none] } result = Longs.tryParse(value); if (result != null) { return result; // depends on control dependency: [if], data = [none] } result = Doubles.tryParse(value); if (result != null) { return result; // depends on control dependency: [if], data = [none] } return value; } }
public class class_name { protected final void reply(WebSocketSession session, Event event, Message reply) { try { if (StringUtils.isEmpty(reply.getType())) { reply.setType(EventType.MESSAGE.name().toLowerCase()); } reply.setText(encode(reply.getText())); if (reply.getChannel() == null && event.getChannelId() != null) { reply.setChannel(event.getChannelId()); } synchronized (sendMessageLock) { session.sendMessage(new TextMessage(reply.toJSONString())); } if (logger.isDebugEnabled()) { // For debugging purpose only logger.debug("Reply (Message): {}", reply.toJSONString()); } } catch (IOException e) { logger.error("Error sending event: {}. Exception: {}", event.getText(), e.getMessage()); } } }
public class class_name { protected final void reply(WebSocketSession session, Event event, Message reply) { try { if (StringUtils.isEmpty(reply.getType())) { reply.setType(EventType.MESSAGE.name().toLowerCase()); // depends on control dependency: [if], data = [none] } reply.setText(encode(reply.getText())); // depends on control dependency: [try], data = [none] if (reply.getChannel() == null && event.getChannelId() != null) { reply.setChannel(event.getChannelId()); // depends on control dependency: [if], data = [none] } synchronized (sendMessageLock) { // depends on control dependency: [try], data = [none] session.sendMessage(new TextMessage(reply.toJSONString())); } if (logger.isDebugEnabled()) { // For debugging purpose only logger.debug("Reply (Message): {}", reply.toJSONString()); // depends on control dependency: [if], data = [none] } } catch (IOException e) { logger.error("Error sending event: {}. Exception: {}", event.getText(), e.getMessage()); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static String interpolateWithProperties(String original, Properties... props) { String result = original; // cap number of interpolations as guard against unending loop inter: for(int i =0; i < original.length()*2; i++) { Matcher m = TextUtils.getMatcher(propRefPattern, result); while(m.find()) { String key = m.group(1); String value = ""; for(Properties properties : props) { value = properties.getProperty(key, ""); if(StringUtils.isNotEmpty(value)) { break; } } result = result.substring(0,m.start()) + value + result.substring(m.end()); continue inter; } // we only hit here if there were no interpolations last while loop break; } return result; } }
public class class_name { public static String interpolateWithProperties(String original, Properties... props) { String result = original; // cap number of interpolations as guard against unending loop inter: for(int i =0; i < original.length()*2; i++) { Matcher m = TextUtils.getMatcher(propRefPattern, result); while(m.find()) { String key = m.group(1); String value = ""; for(Properties properties : props) { value = properties.getProperty(key, ""); // depends on control dependency: [for], data = [properties] if(StringUtils.isNotEmpty(value)) { break; } } result = result.substring(0,m.start()) + value + result.substring(m.end()); // depends on control dependency: [while], data = [none] continue inter; } // we only hit here if there were no interpolations last while loop break; } return result; } }
public class class_name { public void renameNodesWithAttributeValue(String oldName, String newName, String attributeName, String attributeValue) { List<Node> nodes = getNodesFromTreeByName(oldName); Iterator i = nodes.iterator(); while (i.hasNext()) { Node n = (Node) i.next(); n.setName(newName); } } }
public class class_name { public void renameNodesWithAttributeValue(String oldName, String newName, String attributeName, String attributeValue) { List<Node> nodes = getNodesFromTreeByName(oldName); Iterator i = nodes.iterator(); while (i.hasNext()) { Node n = (Node) i.next(); n.setName(newName); // depends on control dependency: [while], data = [none] } } }
public class class_name { public Expression next(int precedence) throws ParseException { ParserToken token; Expression result; do { token = tokenStream.consume(); if (token == null) { return null; } result = grammar.parse(this, token); } while (result == null); //Consume things that will be skipped while (grammar.skip(tokenStream.lookAhead(0))) { tokenStream.consume(); } while (precedence < grammar.precedence(tokenStream.lookAhead(0))) { token = tokenStream.consume(); result = grammar.parse(this, result, token); } return result; } }
public class class_name { public Expression next(int precedence) throws ParseException { ParserToken token; Expression result; do { token = tokenStream.consume(); if (token == null) { return null; // depends on control dependency: [if], data = [none] } result = grammar.parse(this, token); } while (result == null); //Consume things that will be skipped while (grammar.skip(tokenStream.lookAhead(0))) { tokenStream.consume(); } while (precedence < grammar.precedence(tokenStream.lookAhead(0))) { token = tokenStream.consume(); result = grammar.parse(this, result, token); } return result; } }
public class class_name { public void marshall(JobExecutionState jobExecutionState, ProtocolMarshaller protocolMarshaller) { if (jobExecutionState == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(jobExecutionState.getStatus(), STATUS_BINDING); protocolMarshaller.marshall(jobExecutionState.getStatusDetails(), STATUSDETAILS_BINDING); protocolMarshaller.marshall(jobExecutionState.getVersionNumber(), VERSIONNUMBER_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(JobExecutionState jobExecutionState, ProtocolMarshaller protocolMarshaller) { if (jobExecutionState == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(jobExecutionState.getStatus(), STATUS_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(jobExecutionState.getStatusDetails(), STATUSDETAILS_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(jobExecutionState.getVersionNumber(), VERSIONNUMBER_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { protected void refresh() { if (log.isDebugEnabled()) log.debug("Refresh this transaction for reuse: " + this); try { // we reuse ObjectEnvelopeTable instance objectEnvelopeTable.refresh(); } catch (Exception e) { if (log.isDebugEnabled()) { log.debug("error closing object envelope table : " + e.getMessage()); e.printStackTrace(); } } cleanupBroker(); // clear the temporary used named roots map // we should do that, because same tx instance // could be used several times broker = null; clearRegistrationList(); unmaterializedLocks.clear(); txStatus = Status.STATUS_NO_TRANSACTION; } }
public class class_name { protected void refresh() { if (log.isDebugEnabled()) log.debug("Refresh this transaction for reuse: " + this); try { // we reuse ObjectEnvelopeTable instance objectEnvelopeTable.refresh(); // depends on control dependency: [try], data = [none] } catch (Exception e) { if (log.isDebugEnabled()) { log.debug("error closing object envelope table : " + e.getMessage()); // depends on control dependency: [if], data = [none] e.printStackTrace(); // depends on control dependency: [if], data = [none] } } // depends on control dependency: [catch], data = [none] cleanupBroker(); // clear the temporary used named roots map // we should do that, because same tx instance // could be used several times broker = null; clearRegistrationList(); unmaterializedLocks.clear(); txStatus = Status.STATUS_NO_TRANSACTION; } }
public class class_name { @Override protected void uploadTusFiles() throws IOException, ProtocolException { setState(State.UPLOADING); while (uploads.size() > 0) { final TusUploader tusUploader; // don't recreate uploader if it already exists. // this is to avoid multiple connections being open. And to avoid some connections left unclosed. if (lastTusUploader != null) { tusUploader = lastTusUploader; lastTusUploader = null; } else { tusUploader = tusClient.resumeOrCreateUpload(uploads.get(0)); if (getUploadChunkSize() > 0) { tusUploader.setChunkSize(getUploadChunkSize()); } } TusExecutor tusExecutor = new TusExecutor() { @Override protected void makeAttempt() throws ProtocolException, IOException { while (state == State.UPLOADING) { int chunkUploaded = tusUploader.uploadChunk(); if (chunkUploaded > 0) { uploadedBytes += chunkUploaded; listener.onUploadPogress(uploadedBytes, totalUploadSize); } else { // upload is complete break; } } } }; tusExecutor.makeAttempts(); if (state != State.UPLOADING) { // if upload is paused, save the uploader so it can be reused on resume, then leave the method early. lastTusUploader = tusUploader; return; } // remove upload instance from list uploads.remove(0); tusUploader.finish(); } setState(State.UPLOAD_COMPLETE); } }
public class class_name { @Override protected void uploadTusFiles() throws IOException, ProtocolException { setState(State.UPLOADING); while (uploads.size() > 0) { final TusUploader tusUploader; // don't recreate uploader if it already exists. // this is to avoid multiple connections being open. And to avoid some connections left unclosed. if (lastTusUploader != null) { tusUploader = lastTusUploader; lastTusUploader = null; } else { tusUploader = tusClient.resumeOrCreateUpload(uploads.get(0)); if (getUploadChunkSize() > 0) { tusUploader.setChunkSize(getUploadChunkSize()); // depends on control dependency: [if], data = [(getUploadChunkSize()] } } TusExecutor tusExecutor = new TusExecutor() { @Override protected void makeAttempt() throws ProtocolException, IOException { while (state == State.UPLOADING) { int chunkUploaded = tusUploader.uploadChunk(); if (chunkUploaded > 0) { uploadedBytes += chunkUploaded; listener.onUploadPogress(uploadedBytes, totalUploadSize); } else { // upload is complete break; } } } }; tusExecutor.makeAttempts(); if (state != State.UPLOADING) { // if upload is paused, save the uploader so it can be reused on resume, then leave the method early. lastTusUploader = tusUploader; return; } // remove upload instance from list uploads.remove(0); tusUploader.finish(); } setState(State.UPLOAD_COMPLETE); } }
public class class_name { private TextWatcher createTextChangeListener() { return new TextWatcher() { @Override public final void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) { } @Override public final void onTextChanged(final CharSequence s, final int start, final int before, final int count) { } @Override public final void afterTextChanged(final Editable s) { if (isValidatedOnValueChange()) { validate(); } adaptMaxNumberOfCharactersMessage(); } }; } }
public class class_name { private TextWatcher createTextChangeListener() { return new TextWatcher() { @Override public final void beforeTextChanged(final CharSequence s, final int start, final int count, final int after) { } @Override public final void onTextChanged(final CharSequence s, final int start, final int before, final int count) { } @Override public final void afterTextChanged(final Editable s) { if (isValidatedOnValueChange()) { validate(); // depends on control dependency: [if], data = [none] } adaptMaxNumberOfCharactersMessage(); } }; } }
public class class_name { public static final int getTotalMonomerCount(HELM2Notation helm2notation) { int result = 0; for (PolymerNotation polymer : helm2notation.getListOfPolymers()) { result += PolymerUtils.getTotalMonomerCount(polymer); } return result; } }
public class class_name { public static final int getTotalMonomerCount(HELM2Notation helm2notation) { int result = 0; for (PolymerNotation polymer : helm2notation.getListOfPolymers()) { result += PolymerUtils.getTotalMonomerCount(polymer); // depends on control dependency: [for], data = [polymer] } return result; } }
public class class_name { public void updateFields(Record record, BaseMessage message, boolean bUpdateOnlyIfFieldNotModified) { String strField = (String)message.get(DBParams.FIELD); if (MULTIPLE_FIELDS.equalsIgnoreCase(strField)) { // Process multiple fields for (int iFieldSeq = 0; iFieldSeq < record.getFieldCount(); iFieldSeq++) { BaseField field = record.getField(iFieldSeq); Object objFieldNameValue = message.get(field.getFieldName()); if (objFieldNameValue != null) if ((!bUpdateOnlyIfFieldNotModified) || (!field.isModified())) { if (objFieldNameValue instanceof String) field.setString((String)objFieldNameValue); else { try { objFieldNameValue = Converter.convertObjectToDatatype(objFieldNameValue, field.getDataClass(), null); } catch (Exception ex) { objFieldNameValue = null; } field.setData(objFieldNameValue); } } } } else { String strValue = (String)message.get(DBParams.VALUE); BaseField field = record.getField(strField); if (field != null) if ((!bUpdateOnlyIfFieldNotModified) || (!field.isModified())) field.setString(strValue); } } }
public class class_name { public void updateFields(Record record, BaseMessage message, boolean bUpdateOnlyIfFieldNotModified) { String strField = (String)message.get(DBParams.FIELD); if (MULTIPLE_FIELDS.equalsIgnoreCase(strField)) { // Process multiple fields for (int iFieldSeq = 0; iFieldSeq < record.getFieldCount(); iFieldSeq++) { BaseField field = record.getField(iFieldSeq); Object objFieldNameValue = message.get(field.getFieldName()); if (objFieldNameValue != null) if ((!bUpdateOnlyIfFieldNotModified) || (!field.isModified())) { if (objFieldNameValue instanceof String) field.setString((String)objFieldNameValue); else { try { objFieldNameValue = Converter.convertObjectToDatatype(objFieldNameValue, field.getDataClass(), null); // depends on control dependency: [try], data = [none] } catch (Exception ex) { objFieldNameValue = null; } // depends on control dependency: [catch], data = [none] field.setData(objFieldNameValue); // depends on control dependency: [if], data = [none] } } } } else { String strValue = (String)message.get(DBParams.VALUE); BaseField field = record.getField(strField); if (field != null) if ((!bUpdateOnlyIfFieldNotModified) || (!field.isModified())) field.setString(strValue); } } }
public class class_name { public static synchronized LuceneIndexer getInstance(String lucDirPath) { // super(analyzer); if (indexer == null && lucDirPath != null) { indexer = new LuceneIndexer(lucDirPath); } return indexer; } }
public class class_name { public static synchronized LuceneIndexer getInstance(String lucDirPath) { // super(analyzer); if (indexer == null && lucDirPath != null) { indexer = new LuceneIndexer(lucDirPath); // depends on control dependency: [if], data = [none] } return indexer; } }
public class class_name { @Override public void link(EventLinker.Configuration config) { final Object listenerTemplate = config.getContext(); Set<Method> methods = config.getListenerTargets(EventCategory.TOUCH); for (final Method method : methods) { OnTouchListener onTouchListener = new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { try { if(!method.isAccessible()) method.setAccessible(true); Class<?>[] params = method.getParameterTypes(); Object[] args = new Object[params.length]; boolean argsPopulated = false; if(params.length < 3) { argsPopulated = true; for(int i = 0; i < params.length; i++) { if(View.class.isAssignableFrom(params[i])) { args[i] = v; } else if(MotionEvent.class.isAssignableFrom(params[i])) { args[i] = event; } else { argsPopulated = false; } } } if(argsPopulated) method.invoke(listenerTemplate, args); else method.invoke(listenerTemplate); } catch (Exception e) { StringBuilder builder = new StringBuilder() .append("Invocation of ") .append(method.getName()) .append(" at ") .append(listenerTemplate.getClass().getName()) .append(" failed for event OnTouch."); Log.e(getClass().getName(), builder.toString(), e); } return false; } }; try { int[] views = method.getAnnotation(Touch.class).value(); for (int id : views) { try { if(ContextUtils.isActivity(listenerTemplate)) { ContextUtils.asActivity(listenerTemplate) .findViewById(id).setOnTouchListener(onTouchListener); } else if(ContextUtils.isFragment(listenerTemplate)) { ContextUtils.asFragment(listenerTemplate) .getView().findViewById(id).setOnTouchListener(onTouchListener); } else if(ContextUtils.isSupportFragment(listenerTemplate)) { ContextUtils.asSupportFragment(listenerTemplate) .getView().findViewById(id).setOnTouchListener(onTouchListener); } } catch (Exception e) { StringBuilder builder = new StringBuilder() .append("Touch listener linking failed on method ") .append(method.getName()) .append(" at ") .append(listenerTemplate.getClass().getName()) .append(" for view with ID ") .append(ContextUtils.isActivity(listenerTemplate)? ContextUtils.asActivity(listenerTemplate).getResources().getResourceName(id) :ContextUtils.asFragment(listenerTemplate).getResources().getResourceName(id)) .append("."); Log.e(getClass().getName(), builder.toString(), e); } } } catch (Exception e) { StringBuilder builder = new StringBuilder() .append("Touch listener linking failed on method ") .append(method.getName()) .append(" at ") .append(listenerTemplate.getClass().getName()) .append("."); Log.e(getClass().getName(), builder.toString(), e); } } } }
public class class_name { @Override public void link(EventLinker.Configuration config) { final Object listenerTemplate = config.getContext(); Set<Method> methods = config.getListenerTargets(EventCategory.TOUCH); for (final Method method : methods) { OnTouchListener onTouchListener = new OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { try { if(!method.isAccessible()) method.setAccessible(true); Class<?>[] params = method.getParameterTypes(); Object[] args = new Object[params.length]; boolean argsPopulated = false; // depends on control dependency: [try], data = [none] if(params.length < 3) { argsPopulated = true; // depends on control dependency: [if], data = [none] for(int i = 0; i < params.length; i++) { if(View.class.isAssignableFrom(params[i])) { args[i] = v; // depends on control dependency: [if], data = [none] } else if(MotionEvent.class.isAssignableFrom(params[i])) { args[i] = event; // depends on control dependency: [if], data = [none] } else { argsPopulated = false; // depends on control dependency: [if], data = [none] } } } if(argsPopulated) method.invoke(listenerTemplate, args); else method.invoke(listenerTemplate); } catch (Exception e) { StringBuilder builder = new StringBuilder() .append("Invocation of ") .append(method.getName()) .append(" at ") .append(listenerTemplate.getClass().getName()) .append(" failed for event OnTouch."); Log.e(getClass().getName(), builder.toString(), e); } // depends on control dependency: [catch], data = [none] return false; } }; try { int[] views = method.getAnnotation(Touch.class).value(); for (int id : views) { try { if(ContextUtils.isActivity(listenerTemplate)) { ContextUtils.asActivity(listenerTemplate) .findViewById(id).setOnTouchListener(onTouchListener); // depends on control dependency: [if], data = [none] } else if(ContextUtils.isFragment(listenerTemplate)) { ContextUtils.asFragment(listenerTemplate) .getView().findViewById(id).setOnTouchListener(onTouchListener); // depends on control dependency: [if], data = [none] } else if(ContextUtils.isSupportFragment(listenerTemplate)) { ContextUtils.asSupportFragment(listenerTemplate) .getView().findViewById(id).setOnTouchListener(onTouchListener); // depends on control dependency: [if], data = [none] } } catch (Exception e) { StringBuilder builder = new StringBuilder() .append("Touch listener linking failed on method ") .append(method.getName()) .append(" at ") .append(listenerTemplate.getClass().getName()) .append(" for view with ID ") .append(ContextUtils.isActivity(listenerTemplate)? ContextUtils.asActivity(listenerTemplate).getResources().getResourceName(id) :ContextUtils.asFragment(listenerTemplate).getResources().getResourceName(id)) .append("."); Log.e(getClass().getName(), builder.toString(), e); } // depends on control dependency: [catch], data = [none] } } catch (Exception e) { StringBuilder builder = new StringBuilder() .append("Touch listener linking failed on method ") .append(method.getName()) .append(" at ") .append(listenerTemplate.getClass().getName()) .append("."); Log.e(getClass().getName(), builder.toString(), e); } // depends on control dependency: [catch], data = [none] } } }
public class class_name { @Override public boolean isSubjectValid(Subject subject) { boolean isValid = true; // Step through the list of registered providers Iterator<CredentialProvider> itr = credentialProviders.getServices(); while (itr.hasNext()) { CredentialProvider provider = itr.next(); isValid = isValid && provider.isSubjectValid(subject); //TODO - JwtSSOToken fallback to LTPA if (!isValid) { break; } } return isValid; } }
public class class_name { @Override public boolean isSubjectValid(Subject subject) { boolean isValid = true; // Step through the list of registered providers Iterator<CredentialProvider> itr = credentialProviders.getServices(); while (itr.hasNext()) { CredentialProvider provider = itr.next(); isValid = isValid && provider.isSubjectValid(subject); // depends on control dependency: [while], data = [none] //TODO - JwtSSOToken fallback to LTPA if (!isValid) { break; } } return isValid; } }
public class class_name { public JobEdge getBackwardConnection(final int index) { if (index < this.backwardEdges.size()) { return this.backwardEdges.get(index); } return null; } }
public class class_name { public JobEdge getBackwardConnection(final int index) { if (index < this.backwardEdges.size()) { return this.backwardEdges.get(index); // depends on control dependency: [if], data = [(index] } return null; } }
public class class_name { public final void update( final long newworked, final String msg) { if( newworked > 0 || (msg != null && !msg.equals(_msg)) ) { new JAtomic() { @Override boolean abort(Job job) { return newworked==0 && ((msg==null && _msg==null) || (msg != null && msg.equals(job._msg))); } @Override void update(Job old) { old._worked += newworked; old._msg = msg; } }.apply(this); } } }
public class class_name { public final void update( final long newworked, final String msg) { if( newworked > 0 || (msg != null && !msg.equals(_msg)) ) { new JAtomic() { @Override boolean abort(Job job) { return newworked==0 && ((msg==null && _msg==null) || (msg != null && msg.equals(job._msg))); } @Override void update(Job old) { old._worked += newworked; old._msg = msg; } }.apply(this); // depends on control dependency: [if], data = [none] } } }
public class class_name { String eventSubject(long sessionId) { if (prefix == null) { return String.format("event-%d", sessionId); } else { return String.format("%s-event-%d", prefix, sessionId); } } }
public class class_name { String eventSubject(long sessionId) { if (prefix == null) { return String.format("event-%d", sessionId); // depends on control dependency: [if], data = [none] } else { return String.format("%s-event-%d", prefix, sessionId); // depends on control dependency: [if], data = [none] } } }
public class class_name { @Override public Prediction _predictRecord(Record r) { Set<Object> classesSet = knowledgeBase.getModelParameters().getClasses(); AssociativeArray predictionScores = new AssociativeArray(); for(Object theClass : classesSet) { predictionScores.put(theClass, calculateClassScore(r.getX(), theClass)); } Object predictedClass=getSelectedClassFromClassScores(predictionScores); Descriptives.normalizeExp(predictionScores); return new Prediction(predictedClass, predictionScores); } }
public class class_name { @Override public Prediction _predictRecord(Record r) { Set<Object> classesSet = knowledgeBase.getModelParameters().getClasses(); AssociativeArray predictionScores = new AssociativeArray(); for(Object theClass : classesSet) { predictionScores.put(theClass, calculateClassScore(r.getX(), theClass)); // depends on control dependency: [for], data = [theClass] } Object predictedClass=getSelectedClassFromClassScores(predictionScores); Descriptives.normalizeExp(predictionScores); return new Prediction(predictedClass, predictionScores); } }
public class class_name { public void loadParamFile() throws IOException { SeekableLineReaderFactory fact = null; SeekableLineReaderIterator iter = null; try { fact = GeneralURIStreamFactory.createSeekableStreamFactory( paramFile, false); iter = new SeekableLineReaderIterator(fact.get()); paramSet = new HashSet<String>(); while (iter.hasNext()) { String param = iter.next(); param = param.trim(); if (param.isEmpty() || param.startsWith("#")) { continue; } // Use only the first word, ignore the rest int wordEnd = param.indexOf(delim); if (wordEnd > 0) { param = param.substring(0, wordEnd); } paramSet.add(param); } } finally { if (iter != null) { iter.close(); } if (fact != null) { fact.close(); } } } }
public class class_name { public void loadParamFile() throws IOException { SeekableLineReaderFactory fact = null; SeekableLineReaderIterator iter = null; try { fact = GeneralURIStreamFactory.createSeekableStreamFactory( paramFile, false); iter = new SeekableLineReaderIterator(fact.get()); paramSet = new HashSet<String>(); while (iter.hasNext()) { String param = iter.next(); param = param.trim(); // depends on control dependency: [while], data = [none] if (param.isEmpty() || param.startsWith("#")) { continue; } // Use only the first word, ignore the rest int wordEnd = param.indexOf(delim); if (wordEnd > 0) { param = param.substring(0, wordEnd); // depends on control dependency: [if], data = [none] } paramSet.add(param); // depends on control dependency: [while], data = [none] } } finally { if (iter != null) { iter.close(); // depends on control dependency: [if], data = [none] } if (fact != null) { fact.close(); // depends on control dependency: [if], data = [none] } } } }
public class class_name { protected static OProjection translateDistinct(OProjection projection) { if (projection != null && projection.getItems().size() == 1) { if (isDistinct(projection.getItems().get(0))) { projection = projection.copy(); OProjectionItem item = projection.getItems().get(0); OFunctionCall function = ((OBaseExpression) item.getExpression().getMathExpression()).getIdentifier().getLevelZero() .getFunctionCall(); OExpression exp = function.getParams().get(0); OProjectionItem resultItem = new OProjectionItem(-1); resultItem.setAlias(item.getAlias()); resultItem.setExpression(exp.copy()); OProjection result = new OProjection(-1); result.setItems(new ArrayList<>()); result.setDistinct(true); result.getItems().add(resultItem); return result; } } return projection; } }
public class class_name { protected static OProjection translateDistinct(OProjection projection) { if (projection != null && projection.getItems().size() == 1) { if (isDistinct(projection.getItems().get(0))) { projection = projection.copy(); // depends on control dependency: [if], data = [none] OProjectionItem item = projection.getItems().get(0); OFunctionCall function = ((OBaseExpression) item.getExpression().getMathExpression()).getIdentifier().getLevelZero() .getFunctionCall(); OExpression exp = function.getParams().get(0); OProjectionItem resultItem = new OProjectionItem(-1); resultItem.setAlias(item.getAlias()); // depends on control dependency: [if], data = [none] resultItem.setExpression(exp.copy()); // depends on control dependency: [if], data = [none] OProjection result = new OProjection(-1); result.setItems(new ArrayList<>()); // depends on control dependency: [if], data = [none] result.setDistinct(true); // depends on control dependency: [if], data = [none] result.getItems().add(resultItem); // depends on control dependency: [if], data = [none] return result; // depends on control dependency: [if], data = [none] } } return projection; } }
public class class_name { public void organizeTypeAnnotationsSignatures(final Env<AttrContext> env, final JCClassDecl tree) { annotate.afterRepeated( new Worker() { @Override public void run() { JavaFileObject oldSource = log.useSource(env.toplevel.sourcefile); try { new TypeAnnotationPositions(true).scan(tree); } finally { log.useSource(oldSource); } } } ); } }
public class class_name { public void organizeTypeAnnotationsSignatures(final Env<AttrContext> env, final JCClassDecl tree) { annotate.afterRepeated( new Worker() { @Override public void run() { JavaFileObject oldSource = log.useSource(env.toplevel.sourcefile); try { new TypeAnnotationPositions(true).scan(tree); // depends on control dependency: [try], data = [none] } finally { log.useSource(oldSource); } } } ); } }
public class class_name { public synchronized boolean advanceTo(long endTime) { if (endTime < currentTime || runnables.isEmpty()) { currentTime = endTime; return false; } int runCount = 0; while (nextTaskIsScheduledBefore(endTime)) { runOneTask(); ++runCount; } currentTime = endTime; return runCount > 0; } }
public class class_name { public synchronized boolean advanceTo(long endTime) { if (endTime < currentTime || runnables.isEmpty()) { currentTime = endTime; // depends on control dependency: [if], data = [none] return false; // depends on control dependency: [if], data = [none] } int runCount = 0; while (nextTaskIsScheduledBefore(endTime)) { runOneTask(); // depends on control dependency: [while], data = [none] ++runCount; // depends on control dependency: [while], data = [none] } currentTime = endTime; return runCount > 0; } }
public class class_name { public static Optional<Fix> tryFailToAssertThrows( TryTree tryTree, List<? extends StatementTree> throwingStatements, Optional<Tree> failureMessage, VisitorState state) { List<? extends CatchTree> catchTrees = tryTree.getCatches(); if (catchTrees.size() != 1) { return Optional.empty(); } CatchTree catchTree = Iterables.getOnlyElement(catchTrees); SuggestedFix.Builder fix = SuggestedFix.builder(); StringBuilder fixPrefix = new StringBuilder(); if (throwingStatements.isEmpty()) { return Optional.empty(); } List<? extends StatementTree> catchStatements = catchTree.getBlock().getStatements(); fix.addStaticImport("org.junit.Assert.assertThrows"); if (!catchStatements.isEmpty()) { // TODO(cushon): pick a fresh name for the variable, if necessary fixPrefix.append(String.format("%s = ", state.getSourceForNode(catchTree.getParameter()))); } fixPrefix.append( String.format( "assertThrows(%s%s.class, () -> ", failureMessage // Supplying a constant string adds little value, since a failure here always means // the same thing: the method just called wasn't expected to complete normally, but // it did. .filter(t -> ASTHelpers.constValue(t, String.class) == null) .map(t -> state.getSourceForNode(t) + ", ") .orElse(""), state.getSourceForNode(catchTree.getParameter().getType()))); boolean useExpressionLambda = throwingStatements.size() == 1 && getOnlyElement(throwingStatements).getKind() == Kind.EXPRESSION_STATEMENT; if (!useExpressionLambda) { fixPrefix.append("{"); } fix.replace( ((JCTree) tryTree).getStartPosition(), ((JCTree) throwingStatements.iterator().next()).getStartPosition(), fixPrefix.toString()); if (useExpressionLambda) { fix.postfixWith( ((ExpressionStatementTree) throwingStatements.iterator().next()).getExpression(), ")"); } else { fix.postfixWith(getLast(throwingStatements), "});"); } if (catchStatements.isEmpty()) { fix.replace( state.getEndPosition(getLast(throwingStatements)), state.getEndPosition(tryTree), ""); } else { fix.replace( /* startPos= */ state.getEndPosition(getLast(throwingStatements)), /* endPos= */ ((JCTree) catchStatements.get(0)).getStartPosition(), "\n"); fix.replace( state.getEndPosition(getLast(catchStatements)), state.getEndPosition(tryTree), ""); } return Optional.of(fix.build()); } }
public class class_name { public static Optional<Fix> tryFailToAssertThrows( TryTree tryTree, List<? extends StatementTree> throwingStatements, Optional<Tree> failureMessage, VisitorState state) { List<? extends CatchTree> catchTrees = tryTree.getCatches(); if (catchTrees.size() != 1) { return Optional.empty(); // depends on control dependency: [if], data = [none] } CatchTree catchTree = Iterables.getOnlyElement(catchTrees); SuggestedFix.Builder fix = SuggestedFix.builder(); StringBuilder fixPrefix = new StringBuilder(); if (throwingStatements.isEmpty()) { return Optional.empty(); // depends on control dependency: [if], data = [none] } List<? extends StatementTree> catchStatements = catchTree.getBlock().getStatements(); fix.addStaticImport("org.junit.Assert.assertThrows"); if (!catchStatements.isEmpty()) { // TODO(cushon): pick a fresh name for the variable, if necessary fixPrefix.append(String.format("%s = ", state.getSourceForNode(catchTree.getParameter()))); } fixPrefix.append( String.format( "assertThrows(%s%s.class, () -> ", failureMessage // Supplying a constant string adds little value, since a failure here always means // the same thing: the method just called wasn't expected to complete normally, but // it did. .filter(t -> ASTHelpers.constValue(t, String.class) == null) .map(t -> state.getSourceForNode(t) + ", ") .orElse(""), state.getSourceForNode(catchTree.getParameter().getType()))); boolean useExpressionLambda = throwingStatements.size() == 1 && getOnlyElement(throwingStatements).getKind() == Kind.EXPRESSION_STATEMENT; if (!useExpressionLambda) { fixPrefix.append("{"); } fix.replace( ((JCTree) tryTree).getStartPosition(), ((JCTree) throwingStatements.iterator().next()).getStartPosition(), fixPrefix.toString()); if (useExpressionLambda) { fix.postfixWith( ((ExpressionStatementTree) throwingStatements.iterator().next()).getExpression(), ")"); } else { fix.postfixWith(getLast(throwingStatements), "});"); } if (catchStatements.isEmpty()) { fix.replace( state.getEndPosition(getLast(throwingStatements)), state.getEndPosition(tryTree), ""); } else { fix.replace( /* startPos= */ state.getEndPosition(getLast(throwingStatements)), /* endPos= */ ((JCTree) catchStatements.get(0)).getStartPosition(), "\n"); fix.replace( state.getEndPosition(getLast(catchStatements)), state.getEndPosition(tryTree), ""); } return Optional.of(fix.build()); } }
public class class_name { protected void performSingleResourceOperation(String resourceName, int dialogAction) throws CmsException { // store original name to use for lock action String originalResourceName = resourceName; CmsResource res = getCms().readResource(resourceName, CmsResourceFilter.ALL); if (res.isFolder() && !resourceName.endsWith("/")) { resourceName += "/"; } org.opencms.lock.CmsLock lock = getCms().getLock(res); // perform action depending on dialog uri switch (dialogAction) { case TYPE_LOCKCHANGE: case TYPE_LOCK: if (lock.isNullLock()) { getCms().lockResource(originalResourceName); } else if (!lock.isDirectlyOwnedInProjectBy(getCms())) { getCms().changeLock(resourceName); } break; case TYPE_UNLOCK: default: if (lock.isNullLock()) { break; } if (lock.isOwnedBy(getCms().getRequestContext().getCurrentUser())) { getCms().unlockResource(resourceName); } } } }
public class class_name { protected void performSingleResourceOperation(String resourceName, int dialogAction) throws CmsException { // store original name to use for lock action String originalResourceName = resourceName; CmsResource res = getCms().readResource(resourceName, CmsResourceFilter.ALL); if (res.isFolder() && !resourceName.endsWith("/")) { resourceName += "/"; } org.opencms.lock.CmsLock lock = getCms().getLock(res); // perform action depending on dialog uri switch (dialogAction) { case TYPE_LOCKCHANGE: case TYPE_LOCK: if (lock.isNullLock()) { getCms().lockResource(originalResourceName); // depends on control dependency: [if], data = [none] } else if (!lock.isDirectlyOwnedInProjectBy(getCms())) { getCms().changeLock(resourceName); // depends on control dependency: [if], data = [none] } break; case TYPE_UNLOCK: default: if (lock.isNullLock()) { break; } if (lock.isOwnedBy(getCms().getRequestContext().getCurrentUser())) { getCms().unlockResource(resourceName); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public boolean addAll(FloatArray items) { ensureCapacity(size + items.size); for (int i = 0; i < items.size; i++) { elements[size++] = items.elements[i]; } return items.size > 0; } }
public class class_name { public boolean addAll(FloatArray items) { ensureCapacity(size + items.size); for (int i = 0; i < items.size; i++) { elements[size++] = items.elements[i]; // depends on control dependency: [for], data = [i] } return items.size > 0; } }
public class class_name { public final int step(byte[]bytes, int p, int end, int n) { int q = p; while (n-- > 0) { q += length(bytes, q, end); } return q <= end ? q : -1; } }
public class class_name { public final int step(byte[]bytes, int p, int end, int n) { int q = p; while (n-- > 0) { q += length(bytes, q, end); // depends on control dependency: [while], data = [none] } return q <= end ? q : -1; } }
public class class_name { public Optional<JClassType> getClassFromJsonDeserializeAnnotation( TreeLogger logger, Annotation annotation, String name ) { try { Class asClass = (Class) annotation.getClass().getDeclaredMethod( name ).invoke( annotation ); if ( asClass != Void.class ) { return Optional.fromNullable( getType( asClass.getCanonicalName() ) ); } } catch ( Exception e ) { logger.log( Type.ERROR, "Cannot find method " + name + " on JsonDeserialize annotation", e ); } return Optional.absent(); } }
public class class_name { public Optional<JClassType> getClassFromJsonDeserializeAnnotation( TreeLogger logger, Annotation annotation, String name ) { try { Class asClass = (Class) annotation.getClass().getDeclaredMethod( name ).invoke( annotation ); // depends on control dependency: [try], data = [none] if ( asClass != Void.class ) { return Optional.fromNullable( getType( asClass.getCanonicalName() ) ); // depends on control dependency: [if], data = [( asClass] } } catch ( Exception e ) { logger.log( Type.ERROR, "Cannot find method " + name + " on JsonDeserialize annotation", e ); } // depends on control dependency: [catch], data = [none] return Optional.absent(); } }
public class class_name { public void setShutdownValue(Number value, GpioPinAnalogOutput ... pin){ for(GpioPinAnalogOutput p : pin) { setShutdownValue(value, p.getPin()); } } }
public class class_name { public void setShutdownValue(Number value, GpioPinAnalogOutput ... pin){ for(GpioPinAnalogOutput p : pin) { setShutdownValue(value, p.getPin()); // depends on control dependency: [for], data = [p] } } }
public class class_name { protected void collectProjectArtifactsAndClasspath( List<Artifact> artifacts, List<Path> theClasspathFiles ) { if ( addResourcesToClasspath ) { for ( Resource r : project.getBuild().getResources() ) { theClasspathFiles.add( Paths.get( r.getDirectory() ) ); } } if ( "compile".equals( classpathScope ) ) { artifacts.addAll( project.getCompileArtifacts() ); if ( addOutputToClasspath ) { theClasspathFiles.add( Paths.get( project.getBuild().getOutputDirectory() ) ); } } else if ( "test".equals( classpathScope ) ) { artifacts.addAll( project.getTestArtifacts() ); if ( addOutputToClasspath ) { theClasspathFiles.add( Paths.get( project.getBuild().getTestOutputDirectory() ) ); theClasspathFiles.add( Paths.get( project.getBuild().getOutputDirectory() ) ); } } else if ( "runtime".equals( classpathScope ) ) { artifacts.addAll( project.getRuntimeArtifacts() ); if ( addOutputToClasspath ) { theClasspathFiles.add( Paths.get( project.getBuild().getOutputDirectory() ) ); } } else if ( "system".equals( classpathScope ) ) { artifacts.addAll( project.getSystemArtifacts() ); } else { throw new IllegalStateException( "Invalid classpath scope: " + classpathScope ); } getLog().debug( "Collected project artifacts " + artifacts ); getLog().debug( "Collected project classpath " + theClasspathFiles ); } }
public class class_name { protected void collectProjectArtifactsAndClasspath( List<Artifact> artifacts, List<Path> theClasspathFiles ) { if ( addResourcesToClasspath ) { for ( Resource r : project.getBuild().getResources() ) { theClasspathFiles.add( Paths.get( r.getDirectory() ) ); // depends on control dependency: [for], data = [r] } } if ( "compile".equals( classpathScope ) ) { artifacts.addAll( project.getCompileArtifacts() ); // depends on control dependency: [if], data = [none] if ( addOutputToClasspath ) { theClasspathFiles.add( Paths.get( project.getBuild().getOutputDirectory() ) ); // depends on control dependency: [if], data = [none] } } else if ( "test".equals( classpathScope ) ) { artifacts.addAll( project.getTestArtifacts() ); // depends on control dependency: [if], data = [none] if ( addOutputToClasspath ) { theClasspathFiles.add( Paths.get( project.getBuild().getTestOutputDirectory() ) ); // depends on control dependency: [if], data = [none] theClasspathFiles.add( Paths.get( project.getBuild().getOutputDirectory() ) ); // depends on control dependency: [if], data = [none] } } else if ( "runtime".equals( classpathScope ) ) { artifacts.addAll( project.getRuntimeArtifacts() ); // depends on control dependency: [if], data = [none] if ( addOutputToClasspath ) { theClasspathFiles.add( Paths.get( project.getBuild().getOutputDirectory() ) ); // depends on control dependency: [if], data = [none] } } else if ( "system".equals( classpathScope ) ) { artifacts.addAll( project.getSystemArtifacts() ); // depends on control dependency: [if], data = [none] } else { throw new IllegalStateException( "Invalid classpath scope: " + classpathScope ); } getLog().debug( "Collected project artifacts " + artifacts ); getLog().debug( "Collected project classpath " + theClasspathFiles ); } }
public class class_name { ExtendedStackTraceElement[] toExtendedStackTrace(final Stack<Class<?>> stack, final Map<String, CacheEntry> map, final StackTraceElement[] rootTrace, final StackTraceElement[] stackTrace) { int stackLength; if (rootTrace != null) { int rootIndex = rootTrace.length - 1; int stackIndex = stackTrace.length - 1; while (rootIndex >= 0 && stackIndex >= 0 && rootTrace[rootIndex].equals(stackTrace[stackIndex])) { --rootIndex; --stackIndex; } this.commonElementCount = stackTrace.length - 1 - stackIndex; stackLength = stackIndex + 1; } else { this.commonElementCount = 0; stackLength = stackTrace.length; } final ExtendedStackTraceElement[] extStackTrace = new ExtendedStackTraceElement[stackLength]; Class<?> clazz = stack.isEmpty() ? null : stack.peek(); ClassLoader lastLoader = null; for (int i = stackLength - 1; i >= 0; --i) { final StackTraceElement stackTraceElement = stackTrace[i]; final String className = stackTraceElement.getClassName(); // The stack returned from getCurrentStack may be missing entries for java.lang.reflect.Method.invoke() // and its implementation. The Throwable might also contain stack entries that are no longer // present as those methods have returned. ExtendedClassInfo extClassInfo; if (clazz != null && className.equals(clazz.getName())) { final CacheEntry entry = this.toCacheEntry(stackTraceElement, clazz, true); extClassInfo = entry.element; lastLoader = entry.loader; stack.pop(); clazz = stack.isEmpty() ? null : stack.peek(); } else { final CacheEntry cacheEntry = map.get(className); if (cacheEntry != null) { final CacheEntry entry = cacheEntry; extClassInfo = entry.element; if (entry.loader != null) { lastLoader = entry.loader; } } else { final CacheEntry entry = this.toCacheEntry(stackTraceElement, this.loadClass(lastLoader, className), false); extClassInfo = entry.element; map.put(stackTraceElement.toString(), entry); if (entry.loader != null) { lastLoader = entry.loader; } } } extStackTrace[i] = new ExtendedStackTraceElement(stackTraceElement, extClassInfo); } return extStackTrace; } }
public class class_name { ExtendedStackTraceElement[] toExtendedStackTrace(final Stack<Class<?>> stack, final Map<String, CacheEntry> map, final StackTraceElement[] rootTrace, final StackTraceElement[] stackTrace) { int stackLength; if (rootTrace != null) { int rootIndex = rootTrace.length - 1; int stackIndex = stackTrace.length - 1; while (rootIndex >= 0 && stackIndex >= 0 && rootTrace[rootIndex].equals(stackTrace[stackIndex])) { --rootIndex; --stackIndex; } this.commonElementCount = stackTrace.length - 1 - stackIndex; stackLength = stackIndex + 1; } else { this.commonElementCount = 0; stackLength = stackTrace.length; } final ExtendedStackTraceElement[] extStackTrace = new ExtendedStackTraceElement[stackLength]; Class<?> clazz = stack.isEmpty() ? null : stack.peek(); ClassLoader lastLoader = null; for (int i = stackLength - 1; i >= 0; --i) { final StackTraceElement stackTraceElement = stackTrace[i]; final String className = stackTraceElement.getClassName(); // The stack returned from getCurrentStack may be missing entries for java.lang.reflect.Method.invoke() // and its implementation. The Throwable might also contain stack entries that are no longer // present as those methods have returned. ExtendedClassInfo extClassInfo; if (clazz != null && className.equals(clazz.getName())) { final CacheEntry entry = this.toCacheEntry(stackTraceElement, clazz, true); extClassInfo = entry.element; lastLoader = entry.loader; stack.pop(); clazz = stack.isEmpty() ? null : stack.peek(); } else { final CacheEntry cacheEntry = map.get(className); if (cacheEntry != null) { final CacheEntry entry = cacheEntry; extClassInfo = entry.element; // depends on control dependency: [if], data = [none] if (entry.loader != null) { lastLoader = entry.loader; // depends on control dependency: [if], data = [none] } } else { final CacheEntry entry = this.toCacheEntry(stackTraceElement, this.loadClass(lastLoader, className), false); extClassInfo = entry.element; // depends on control dependency: [if], data = [none] map.put(stackTraceElement.toString(), entry); // depends on control dependency: [if], data = [none] if (entry.loader != null) { lastLoader = entry.loader; // depends on control dependency: [if], data = [none] } } } extStackTrace[i] = new ExtendedStackTraceElement(stackTraceElement, extClassInfo); } return extStackTrace; } }
public class class_name { private boolean isVersionFollowedBy(ElementType<Token> type) { EnumSet<Token.Type> expected = EnumSet.of(NUMERIC, DOT); Iterator<Token> it = tokens.iterator(); Token lookahead = null; while (it.hasNext()) { lookahead = it.next(); if (!expected.contains(lookahead.type)) { break; } } return type.isMatchedBy(lookahead); } }
public class class_name { private boolean isVersionFollowedBy(ElementType<Token> type) { EnumSet<Token.Type> expected = EnumSet.of(NUMERIC, DOT); Iterator<Token> it = tokens.iterator(); Token lookahead = null; while (it.hasNext()) { lookahead = it.next(); // depends on control dependency: [while], data = [none] if (!expected.contains(lookahead.type)) { break; } } return type.isMatchedBy(lookahead); } }
public class class_name { public static final <T extends Comparable<T>> int comparator(T val1, T val2) { if(val1 == null) { return val2 == null? 0 : -1; } else { return val2 == null? 1 : val1.compareTo(val2); } } }
public class class_name { public static final <T extends Comparable<T>> int comparator(T val1, T val2) { if(val1 == null) { return val2 == null? 0 : -1; // depends on control dependency: [if], data = [none] } else { return val2 == null? 1 : val1.compareTo(val2); // depends on control dependency: [if], data = [none] } } }
public class class_name { public Observable<ServiceResponse<SearchResponse>> searchWithServiceResponseAsync(String query, String acceptLanguage, String pragma, String userAgent, String clientId, String clientIp, String location, Integer answerCount, String countryCode, Integer count, Freshness freshness, String market, Integer offset, List<AnswerType> promote, List<AnswerType> responseFilter, SafeSearch safeSearch, String setLang, Boolean textDecorations, TextFormat textFormat) { if (query == null) { throw new IllegalArgumentException("Parameter query is required and cannot be null."); } Validator.validate(promote); Validator.validate(responseFilter); final String xBingApisSDK = "true"; String promoteConverted = this.client.serializerAdapter().serializeList(promote, CollectionFormat.CSV); String responseFilterConverted = this.client.serializerAdapter().serializeList(responseFilter, CollectionFormat.CSV); return service.search(xBingApisSDK, acceptLanguage, pragma, userAgent, clientId, clientIp, location, answerCount, countryCode, count, freshness, market, offset, promoteConverted, query, responseFilterConverted, safeSearch, setLang, textDecorations, textFormat) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<SearchResponse>>>() { @Override public Observable<ServiceResponse<SearchResponse>> call(Response<ResponseBody> response) { try { ServiceResponse<SearchResponse> clientResponse = searchDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } }
public class class_name { public Observable<ServiceResponse<SearchResponse>> searchWithServiceResponseAsync(String query, String acceptLanguage, String pragma, String userAgent, String clientId, String clientIp, String location, Integer answerCount, String countryCode, Integer count, Freshness freshness, String market, Integer offset, List<AnswerType> promote, List<AnswerType> responseFilter, SafeSearch safeSearch, String setLang, Boolean textDecorations, TextFormat textFormat) { if (query == null) { throw new IllegalArgumentException("Parameter query is required and cannot be null."); } Validator.validate(promote); Validator.validate(responseFilter); final String xBingApisSDK = "true"; String promoteConverted = this.client.serializerAdapter().serializeList(promote, CollectionFormat.CSV); String responseFilterConverted = this.client.serializerAdapter().serializeList(responseFilter, CollectionFormat.CSV); return service.search(xBingApisSDK, acceptLanguage, pragma, userAgent, clientId, clientIp, location, answerCount, countryCode, count, freshness, market, offset, promoteConverted, query, responseFilterConverted, safeSearch, setLang, textDecorations, textFormat) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<SearchResponse>>>() { @Override public Observable<ServiceResponse<SearchResponse>> call(Response<ResponseBody> response) { try { ServiceResponse<SearchResponse> clientResponse = searchDelegate(response); return Observable.just(clientResponse); // depends on control dependency: [try], data = [none] } catch (Throwable t) { return Observable.error(t); } // depends on control dependency: [catch], data = [none] } }); } }
public class class_name { public IMolecularFormula isValid(IMolecularFormula formula) { logger.info("Generating the validity of the molecular formula"); if (formula.getIsotopeCount() == 0) { logger.error("Proposed molecular formula has not elements"); return formula; } Iterator<IRule> iterRules = rules.iterator(); try { while (iterRules.hasNext()) { IRule rule = iterRules.next(); double result = rule.validate(formula); formula.setProperty(rule.getClass(), result); } } catch (CDKException e) { e.printStackTrace(); } return formula; } }
public class class_name { public IMolecularFormula isValid(IMolecularFormula formula) { logger.info("Generating the validity of the molecular formula"); if (formula.getIsotopeCount() == 0) { logger.error("Proposed molecular formula has not elements"); // depends on control dependency: [if], data = [none] return formula; // depends on control dependency: [if], data = [none] } Iterator<IRule> iterRules = rules.iterator(); try { while (iterRules.hasNext()) { IRule rule = iterRules.next(); double result = rule.validate(formula); formula.setProperty(rule.getClass(), result); // depends on control dependency: [while], data = [none] } } catch (CDKException e) { e.printStackTrace(); } // depends on control dependency: [catch], data = [none] return formula; } }
public class class_name { public void rawWarning(int pos, String msg) { PrintWriter warnWriter = writers.get(WriterKind.ERROR); if (nwarnings < MaxWarnings && emitWarnings) { printRawDiag(warnWriter, "warning: ", pos, msg); } prompt(); nwarnings++; warnWriter.flush(); } }
public class class_name { public void rawWarning(int pos, String msg) { PrintWriter warnWriter = writers.get(WriterKind.ERROR); if (nwarnings < MaxWarnings && emitWarnings) { printRawDiag(warnWriter, "warning: ", pos, msg); // depends on control dependency: [if], data = [none] } prompt(); nwarnings++; warnWriter.flush(); } }
public class class_name { private void populateSecMechList(TSSCompoundSecMechListConfig mechListConfig, List<LayersData> layersList, Map<String, List<TransportAddress>> addrMap) throws Exception { for (LayersData mech : layersList) { Map<String, TSSCompoundSecMechConfig> tssCompoundSecMechConfigs = extractCompoundSecMech(mech, addrMap); Iterator<Entry<String, TSSCompoundSecMechConfig>> entries = tssCompoundSecMechConfigs.entrySet().iterator(); while (entries.hasNext()) { Entry<String, TSSCompoundSecMechConfig> entry = entries.next(); mechListConfig.add(entry.getValue(), entry.getKey()); } } } }
public class class_name { private void populateSecMechList(TSSCompoundSecMechListConfig mechListConfig, List<LayersData> layersList, Map<String, List<TransportAddress>> addrMap) throws Exception { for (LayersData mech : layersList) { Map<String, TSSCompoundSecMechConfig> tssCompoundSecMechConfigs = extractCompoundSecMech(mech, addrMap); Iterator<Entry<String, TSSCompoundSecMechConfig>> entries = tssCompoundSecMechConfigs.entrySet().iterator(); while (entries.hasNext()) { Entry<String, TSSCompoundSecMechConfig> entry = entries.next(); mechListConfig.add(entry.getValue(), entry.getKey()); // depends on control dependency: [while], data = [none] } } } }
public class class_name { public List<Person> getSpouses() { final List<Person> spouses = new ArrayList<>(); for (final FamilyNavigator nav : familySNavigators) { final Person spouse = nav.getSpouse(visitedPerson); if (spouse.isSet()) { spouses.add(spouse); } } return spouses; } }
public class class_name { public List<Person> getSpouses() { final List<Person> spouses = new ArrayList<>(); for (final FamilyNavigator nav : familySNavigators) { final Person spouse = nav.getSpouse(visitedPerson); if (spouse.isSet()) { spouses.add(spouse); // depends on control dependency: [if], data = [none] } } return spouses; } }
public class class_name { public void replaceUnsolvedAttributes(NamedConcreteElement element){ if (element.getElement() instanceof XsdAttributeGroup){ attributeGroups.stream() .filter(attributeGroup -> attributeGroup instanceof UnsolvedReference && ((UnsolvedReference) attributeGroup).getRef().equals(element.getName())) .findFirst().ifPresent(referenceBase -> { attributeGroups.remove(referenceBase); attributeGroups.add(element); attributes.addAll(element.getElement().getElements()); element.getElement().setParent(getOwner()); }); } if (element.getElement() instanceof XsdAttribute ){ attributes.stream() .filter(attribute -> attribute instanceof UnsolvedReference && ((UnsolvedReference) attribute).getRef().equals(element.getName())) .findFirst().ifPresent(referenceBase -> { attributes.remove(referenceBase); attributes.add(element); element.getElement().setParent(getOwner()); }); } } }
public class class_name { public void replaceUnsolvedAttributes(NamedConcreteElement element){ if (element.getElement() instanceof XsdAttributeGroup){ attributeGroups.stream() .filter(attributeGroup -> attributeGroup instanceof UnsolvedReference && ((UnsolvedReference) attributeGroup).getRef().equals(element.getName())) .findFirst().ifPresent(referenceBase -> { attributeGroups.remove(referenceBase); // depends on control dependency: [if], data = [none] attributeGroups.add(element); // depends on control dependency: [if], data = [none] attributes.addAll(element.getElement().getElements()); // depends on control dependency: [if], data = [none] element.getElement().setParent(getOwner()); // depends on control dependency: [if], data = [none] }); } if (element.getElement() instanceof XsdAttribute ){ attributes.stream() .filter(attribute -> attribute instanceof UnsolvedReference && ((UnsolvedReference) attribute).getRef().equals(element.getName())) .findFirst().ifPresent(referenceBase -> { attributes.remove(referenceBase); attributes.add(element); element.getElement().setParent(getOwner()); }); } } }
public class class_name { @SuppressWarnings("unchecked") protected List<String> mergeRoles(List<String> otherRoles, boolean mergedAccessPrecluded) { if (mergedAccessPrecluded == true || roles.isEmpty() || otherRoles.isEmpty()) { return Collections.EMPTY_LIST; } Set<String> tempRoles = new HashSet<String>(); tempRoles.addAll(otherRoles); tempRoles.addAll(roles); List<String> mergedRoles = new ArrayList<String>(); mergedRoles.addAll(tempRoles); return mergedRoles; } }
public class class_name { @SuppressWarnings("unchecked") protected List<String> mergeRoles(List<String> otherRoles, boolean mergedAccessPrecluded) { if (mergedAccessPrecluded == true || roles.isEmpty() || otherRoles.isEmpty()) { return Collections.EMPTY_LIST; // depends on control dependency: [if], data = [none] } Set<String> tempRoles = new HashSet<String>(); tempRoles.addAll(otherRoles); tempRoles.addAll(roles); List<String> mergedRoles = new ArrayList<String>(); mergedRoles.addAll(tempRoles); return mergedRoles; } }
public class class_name { public static String decode(final String encoded) { if (encoded == null || encoded.length() == 0 || encoded.indexOf('&') == -1) { return encoded; } return DECODE.translate(encoded); } }
public class class_name { public static String decode(final String encoded) { if (encoded == null || encoded.length() == 0 || encoded.indexOf('&') == -1) { return encoded; // depends on control dependency: [if], data = [none] } return DECODE.translate(encoded); } }
public class class_name { public static void optimiseFragmentSets( Collection<EquivalentFragmentSet> fragmentSets, TransactionOLTP tx) { // Repeatedly apply optimisations until they don't alter the query boolean changed = true; while (changed) { changed = false; for (FragmentSetOptimisation optimisation : OPTIMISATIONS) { changed |= optimisation.apply(fragmentSets, tx); } } } }
public class class_name { public static void optimiseFragmentSets( Collection<EquivalentFragmentSet> fragmentSets, TransactionOLTP tx) { // Repeatedly apply optimisations until they don't alter the query boolean changed = true; while (changed) { changed = false; // depends on control dependency: [while], data = [none] for (FragmentSetOptimisation optimisation : OPTIMISATIONS) { changed |= optimisation.apply(fragmentSets, tx); // depends on control dependency: [for], data = [optimisation] } } } }
public class class_name { public void marshall(DescribeRefreshSchemasStatusRequest describeRefreshSchemasStatusRequest, ProtocolMarshaller protocolMarshaller) { if (describeRefreshSchemasStatusRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(describeRefreshSchemasStatusRequest.getEndpointArn(), ENDPOINTARN_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(DescribeRefreshSchemasStatusRequest describeRefreshSchemasStatusRequest, ProtocolMarshaller protocolMarshaller) { if (describeRefreshSchemasStatusRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(describeRefreshSchemasStatusRequest.getEndpointArn(), ENDPOINTARN_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public java.util.List<Alarm> getAlarms() { if (alarms == null) { alarms = new com.amazonaws.internal.SdkInternalList<Alarm>(); } return alarms; } }
public class class_name { public java.util.List<Alarm> getAlarms() { if (alarms == null) { alarms = new com.amazonaws.internal.SdkInternalList<Alarm>(); // depends on control dependency: [if], data = [none] } return alarms; } }
public class class_name { public DescribeVpcEndpointServiceConfigurationsResult withServiceConfigurations(ServiceConfiguration... serviceConfigurations) { if (this.serviceConfigurations == null) { setServiceConfigurations(new com.amazonaws.internal.SdkInternalList<ServiceConfiguration>(serviceConfigurations.length)); } for (ServiceConfiguration ele : serviceConfigurations) { this.serviceConfigurations.add(ele); } return this; } }
public class class_name { public DescribeVpcEndpointServiceConfigurationsResult withServiceConfigurations(ServiceConfiguration... serviceConfigurations) { if (this.serviceConfigurations == null) { setServiceConfigurations(new com.amazonaws.internal.SdkInternalList<ServiceConfiguration>(serviceConfigurations.length)); // depends on control dependency: [if], data = [none] } for (ServiceConfiguration ele : serviceConfigurations) { this.serviceConfigurations.add(ele); // depends on control dependency: [for], data = [ele] } return this; } }
public class class_name { public VariableResolver<String> createVariableResolver(AbstractBuild<?,?> build) { VariableResolver[] resolvers = new VariableResolver[getParameters().size()+1]; int i=0; for (ParameterValue p : getParameters()) { if (p == null) continue; resolvers[i++] = p.createVariableResolver(build); } resolvers[i] = build.getBuildVariableResolver(); return new VariableResolver.Union<String>(resolvers); } }
public class class_name { public VariableResolver<String> createVariableResolver(AbstractBuild<?,?> build) { VariableResolver[] resolvers = new VariableResolver[getParameters().size()+1]; int i=0; for (ParameterValue p : getParameters()) { if (p == null) continue; resolvers[i++] = p.createVariableResolver(build); // depends on control dependency: [for], data = [p] } resolvers[i] = build.getBuildVariableResolver(); return new VariableResolver.Union<String>(resolvers); } }
public class class_name { public String prettyPrintText() { Pattern punctuation = Pattern.compile("[!,-.:;?`]"); StringBuilder sb = new StringBuilder(nodes.length * 8); boolean evenSingleQuote = false; boolean evenDoubleQuote = false; // For quotations boolean skipSpace = false; for (int i = 0; i < nodes.length; ++i) { String token = nodes[i].word(); // If the first token, append it to start the text if (i == 0) sb.append(token); // For all other tokens, decide whether to add a space between this // token and the preceding. else { // If the token is punctuation, or is a contraction, e.g., 's or // n't, then append it directly if (punctuation.matcher(nodes[i].pos()).matches() || punctuation.matcher(token).matches() || token.equals(".") // special case for end of sentence || token.equals("n't") || token.equals("'m") || token.equals("'ll") || token.equals("'re") || token.equals("'ve") || token.equals("'s")) sb.append(token); else if (token.equals("'")) { if (evenSingleQuote) sb.append(token); else { sb.append(' ').append(token); skipSpace = true; } evenSingleQuote = !evenSingleQuote; } else if (token.equals("\"")) { if (evenDoubleQuote) sb.append(token); else { sb.append(' ').append(token); skipSpace= true; } evenDoubleQuote = !evenDoubleQuote; } else if (token.equals("$")) { sb.append(' ').append(token); skipSpace= true; } // For non-punctuation tokens else { if (skipSpace) { sb.append(token); skipSpace = false; } else sb.append(' ').append(token); } } } return sb.toString(); } }
public class class_name { public String prettyPrintText() { Pattern punctuation = Pattern.compile("[!,-.:;?`]"); StringBuilder sb = new StringBuilder(nodes.length * 8); boolean evenSingleQuote = false; boolean evenDoubleQuote = false; // For quotations boolean skipSpace = false; for (int i = 0; i < nodes.length; ++i) { String token = nodes[i].word(); // If the first token, append it to start the text if (i == 0) sb.append(token); // For all other tokens, decide whether to add a space between this // token and the preceding. else { // If the token is punctuation, or is a contraction, e.g., 's or // n't, then append it directly if (punctuation.matcher(nodes[i].pos()).matches() || punctuation.matcher(token).matches() || token.equals(".") // special case for end of sentence || token.equals("n't") || token.equals("'m") || token.equals("'ll") || token.equals("'re") || token.equals("'ve") || token.equals("'s")) sb.append(token); else if (token.equals("'")) { if (evenSingleQuote) sb.append(token); else { sb.append(' ').append(token); // depends on control dependency: [if], data = [none] skipSpace = true; // depends on control dependency: [if], data = [none] } evenSingleQuote = !evenSingleQuote; // depends on control dependency: [if], data = [none] } else if (token.equals("\"")) { if (evenDoubleQuote) sb.append(token); else { sb.append(' ').append(token); // depends on control dependency: [if], data = [none] skipSpace= true; // depends on control dependency: [if], data = [none] } evenDoubleQuote = !evenDoubleQuote; // depends on control dependency: [if], data = [none] } else if (token.equals("$")) { sb.append(' ').append(token); // depends on control dependency: [if], data = [none] skipSpace= true; // depends on control dependency: [if], data = [none] } // For non-punctuation tokens else { if (skipSpace) { sb.append(token); // depends on control dependency: [if], data = [none] skipSpace = false; // depends on control dependency: [if], data = [none] } else sb.append(' ').append(token); } } } return sb.toString(); } }
public class class_name { public void resolveContentType(FileRequestContext context) { String contentType = lookupMimeType(context.file.getName()); if(contentType != null) { context.contentType = contentType; if(contentType.equals("text/html")) { context.contentType += ";charset=UTF-8"; } } } }
public class class_name { public void resolveContentType(FileRequestContext context) { String contentType = lookupMimeType(context.file.getName()); if(contentType != null) { context.contentType = contentType; // depends on control dependency: [if], data = [none] if(contentType.equals("text/html")) { context.contentType += ";charset=UTF-8"; // depends on control dependency: [if], data = [none] } } } }
public class class_name { private synchronized AppModuleName addAppModuleNames(String appName, String moduleAndAppName) { HashSet<String> moduleNames = null; String moduleName = moduleAndAppName.split("#")[1]; if (appModules.containsKey(appName)) { moduleNames = (HashSet<String>) appModules.get(appName); moduleNames.add(moduleName); } else { moduleNames = new HashSet<String>(); moduleNames.add(moduleName); appModules.put(appName, moduleNames); } if (tc.isDebugEnabled()) Tr.debug(tc, "addAppModuleNames(): modules added = " + appModules.toString() + " for app: " + appName); AppModuleName retVal = new AppModuleName(); retVal.appName = appName; retVal.moduleName = moduleName; return retVal; } }
public class class_name { private synchronized AppModuleName addAppModuleNames(String appName, String moduleAndAppName) { HashSet<String> moduleNames = null; String moduleName = moduleAndAppName.split("#")[1]; if (appModules.containsKey(appName)) { moduleNames = (HashSet<String>) appModules.get(appName); // depends on control dependency: [if], data = [none] moduleNames.add(moduleName); // depends on control dependency: [if], data = [none] } else { moduleNames = new HashSet<String>(); // depends on control dependency: [if], data = [none] moduleNames.add(moduleName); // depends on control dependency: [if], data = [none] appModules.put(appName, moduleNames); // depends on control dependency: [if], data = [none] } if (tc.isDebugEnabled()) Tr.debug(tc, "addAppModuleNames(): modules added = " + appModules.toString() + " for app: " + appName); AppModuleName retVal = new AppModuleName(); retVal.appName = appName; retVal.moduleName = moduleName; return retVal; } }
public class class_name { protected void reportAllElementKeyGroups() { Preconditions.checkState(partitioningSource.length >= numberOfElements); for (int i = 0; i < numberOfElements; ++i) { int keyGroup = KeyGroupRangeAssignment.assignToKeyGroup( keyExtractorFunction.extractKeyFromElement(partitioningSource[i]), totalKeyGroups); reportKeyGroupOfElementAtIndex(i, keyGroup); } } }
public class class_name { protected void reportAllElementKeyGroups() { Preconditions.checkState(partitioningSource.length >= numberOfElements); for (int i = 0; i < numberOfElements; ++i) { int keyGroup = KeyGroupRangeAssignment.assignToKeyGroup( keyExtractorFunction.extractKeyFromElement(partitioningSource[i]), totalKeyGroups); reportKeyGroupOfElementAtIndex(i, keyGroup); // depends on control dependency: [for], data = [i] } } }
public class class_name { public static long jenkins(final BitVector bv, final long prefixLength, final long[] aa, final long bb[], final long cc[]) { if (prefixLength == 0) return aa[0] ^ 0x36071e726d0ba0c5L; final int stateOffset = (int) (prefixLength / (3 * Long.SIZE)); long from = (stateOffset * 3) * Long.SIZE; long a = aa[stateOffset]; long b = bb[stateOffset]; long c = cc[stateOffset]; if (prefixLength - from > Long.SIZE * 2) { a += bv.getLong(from, from + Long.SIZE); b += bv.getLong(from + Long.SIZE, from + 2 * Long.SIZE); c += bv.getLong(from + 2 * Long.SIZE, Math.min(from + 3 * Long.SIZE, prefixLength)); a -= b; a -= c; a ^= (c >>> 43); b -= c; b -= a; b ^= (a << 9); c -= a; c -= b; c ^= (b >>> 8); a -= b; a -= c; a ^= (c >>> 38); b -= c; b -= a; b ^= (a << 23); c -= a; c -= b; c ^= (b >>> 5); a -= b; a -= c; a ^= (c >>> 35); b -= c; b -= a; b ^= (a << 49); c -= a; c -= b; c ^= (b >>> 11); a -= b; a -= c; a ^= (c >>> 12); b -= c; b -= a; b ^= (a << 18); c -= a; c -= b; c ^= (b >>> 22); from += 3 * Long.SIZE; } c += prefixLength; long residual = prefixLength - from; if (residual > 0) { if (residual > Long.SIZE) { a += bv.getLong(from, from + Long.SIZE); residual -= Long.SIZE; } if (residual != 0) b += bv.getLong(prefixLength - residual, prefixLength); } a -= b; a -= c; a ^= (c >>> 43); b -= c; b -= a; b ^= (a << 9); c -= a; c -= b; c ^= (b >>> 8); a -= b; a -= c; a ^= (c >>> 38); b -= c; b -= a; b ^= (a << 23); c -= a; c -= b; c ^= (b >>> 5); a -= b; a -= c; a ^= (c >>> 35); b -= c; b -= a; b ^= (a << 49); c -= a; c -= b; c ^= (b >>> 11); a -= b; a -= c; a ^= (c >>> 12); b -= c; b -= a; b ^= (a << 18); c -= a; c -= b; c ^= (b >>> 22); return c; } }
public class class_name { public static long jenkins(final BitVector bv, final long prefixLength, final long[] aa, final long bb[], final long cc[]) { if (prefixLength == 0) return aa[0] ^ 0x36071e726d0ba0c5L; final int stateOffset = (int) (prefixLength / (3 * Long.SIZE)); long from = (stateOffset * 3) * Long.SIZE; long a = aa[stateOffset]; long b = bb[stateOffset]; long c = cc[stateOffset]; if (prefixLength - from > Long.SIZE * 2) { a += bv.getLong(from, from + Long.SIZE); // depends on control dependency: [if], data = [none] b += bv.getLong(from + Long.SIZE, from + 2 * Long.SIZE); // depends on control dependency: [if], data = [none] c += bv.getLong(from + 2 * Long.SIZE, Math.min(from + 3 * Long.SIZE, prefixLength)); // depends on control dependency: [if], data = [none] a -= b; // depends on control dependency: [if], data = [none] a -= c; // depends on control dependency: [if], data = [none] a ^= (c >>> 43); // depends on control dependency: [if], data = [none] b -= c; // depends on control dependency: [if], data = [none] b -= a; // depends on control dependency: [if], data = [none] b ^= (a << 9); // depends on control dependency: [if], data = [none] c -= a; // depends on control dependency: [if], data = [none] c -= b; // depends on control dependency: [if], data = [none] c ^= (b >>> 8); // depends on control dependency: [if], data = [none] a -= b; // depends on control dependency: [if], data = [none] a -= c; // depends on control dependency: [if], data = [none] a ^= (c >>> 38); // depends on control dependency: [if], data = [none] b -= c; // depends on control dependency: [if], data = [none] b -= a; // depends on control dependency: [if], data = [none] b ^= (a << 23); // depends on control dependency: [if], data = [none] c -= a; // depends on control dependency: [if], data = [none] c -= b; // depends on control dependency: [if], data = [none] c ^= (b >>> 5); // depends on control dependency: [if], data = [none] a -= b; // depends on control dependency: [if], data = [none] a -= c; // depends on control dependency: [if], data = [none] a ^= (c >>> 35); // depends on control dependency: [if], data = [none] b -= c; // depends on control dependency: [if], data = [none] b -= a; // depends on control dependency: [if], data = [none] b ^= (a << 49); // depends on control dependency: [if], data = [none] c -= a; // depends on control dependency: [if], data = [none] c -= b; // depends on control dependency: [if], data = [none] c ^= (b >>> 11); // depends on control dependency: [if], data = [none] a -= b; // depends on control dependency: [if], data = [none] a -= c; // depends on control dependency: [if], data = [none] a ^= (c >>> 12); // depends on control dependency: [if], data = [none] b -= c; // depends on control dependency: [if], data = [none] b -= a; // depends on control dependency: [if], data = [none] b ^= (a << 18); // depends on control dependency: [if], data = [none] c -= a; // depends on control dependency: [if], data = [none] c -= b; // depends on control dependency: [if], data = [none] c ^= (b >>> 22); // depends on control dependency: [if], data = [none] from += 3 * Long.SIZE; // depends on control dependency: [if], data = [none] } c += prefixLength; long residual = prefixLength - from; if (residual > 0) { if (residual > Long.SIZE) { a += bv.getLong(from, from + Long.SIZE); // depends on control dependency: [if], data = [Long.SIZE)] residual -= Long.SIZE; // depends on control dependency: [if], data = [none] } if (residual != 0) b += bv.getLong(prefixLength - residual, prefixLength); } a -= b; a -= c; a ^= (c >>> 43); b -= c; b -= a; b ^= (a << 9); c -= a; c -= b; c ^= (b >>> 8); a -= b; a -= c; a ^= (c >>> 38); b -= c; b -= a; b ^= (a << 23); c -= a; c -= b; c ^= (b >>> 5); a -= b; a -= c; a ^= (c >>> 35); b -= c; b -= a; b ^= (a << 49); c -= a; c -= b; c ^= (b >>> 11); a -= b; a -= c; a ^= (c >>> 12); b -= c; b -= a; b ^= (a << 18); c -= a; c -= b; c ^= (b >>> 22); return c; } }
public class class_name { public void setScales(final double[] newScaleDenominators) { TreeSet<Double> sortedSet = new TreeSet<>(Collections.reverseOrder()); for (final double newScaleDenominator: newScaleDenominators) { sortedSet.add(newScaleDenominator); } this.scaleDenominators = new double[sortedSet.size()]; int i = 0; for (Double scaleDenominator: sortedSet) { this.scaleDenominators[i] = scaleDenominator; i++; } } }
public class class_name { public void setScales(final double[] newScaleDenominators) { TreeSet<Double> sortedSet = new TreeSet<>(Collections.reverseOrder()); for (final double newScaleDenominator: newScaleDenominators) { sortedSet.add(newScaleDenominator); // depends on control dependency: [for], data = [newScaleDenominator] } this.scaleDenominators = new double[sortedSet.size()]; int i = 0; for (Double scaleDenominator: sortedSet) { this.scaleDenominators[i] = scaleDenominator; // depends on control dependency: [for], data = [scaleDenominator] i++; // depends on control dependency: [for], data = [none] } } }
public class class_name { public Collection<SlotKey> getChildrenKeys() { if (granularity == Granularity.FULL) { return ImmutableList.of(); } List<SlotKey> result = new ArrayList<SlotKey>(); Granularity finer; try { finer = granularity.finer(); } catch (GranularityException e) { throw new AssertionError("Should not occur."); } int factor = finer.numSlots() / granularity.numSlots(); for (int i = 0; i < factor; i++) { int childSlot = slot * factor + i; SlotKey child = SlotKey.of(finer, childSlot, shard); result.add(child); result.addAll(child.getChildrenKeys()); } return result; } }
public class class_name { public Collection<SlotKey> getChildrenKeys() { if (granularity == Granularity.FULL) { return ImmutableList.of(); // depends on control dependency: [if], data = [none] } List<SlotKey> result = new ArrayList<SlotKey>(); Granularity finer; try { finer = granularity.finer(); // depends on control dependency: [try], data = [none] } catch (GranularityException e) { throw new AssertionError("Should not occur."); } // depends on control dependency: [catch], data = [none] int factor = finer.numSlots() / granularity.numSlots(); for (int i = 0; i < factor; i++) { int childSlot = slot * factor + i; SlotKey child = SlotKey.of(finer, childSlot, shard); result.add(child); // depends on control dependency: [for], data = [none] result.addAll(child.getChildrenKeys()); // depends on control dependency: [for], data = [none] } return result; } }
public class class_name { private <R,T> Predicate createPredicateFromSingleCriteria( CriteriaQuery<R> query, CriteriaBuilder builder, Class<T> queryType, QueryCriteria criteria, QueryWhere queryWhere) { Predicate predicate = null; assert criteria.hasValues() || criteria.hasDateValues() || Integer.parseInt(criteria.getListId()) < 0 : "No values present for criteria with list id: [" + criteria.getListId() + "]"; String listId = criteria.getListId(); Attribute attr = getCriteriaAttributes().get(queryType).get(listId); if( attr != null ) { Expression entityField = getEntityField(query, listId, attr); predicate = basicCreatePredicateFromSingleCriteria(builder, entityField, criteria); } else { predicate = implSpecificCreatePredicateFromSingleCriteria(query, builder, queryType, criteria, queryWhere ); } return predicate; } }
public class class_name { private <R,T> Predicate createPredicateFromSingleCriteria( CriteriaQuery<R> query, CriteriaBuilder builder, Class<T> queryType, QueryCriteria criteria, QueryWhere queryWhere) { Predicate predicate = null; assert criteria.hasValues() || criteria.hasDateValues() || Integer.parseInt(criteria.getListId()) < 0 : "No values present for criteria with list id: [" + criteria.getListId() + "]"; String listId = criteria.getListId(); Attribute attr = getCriteriaAttributes().get(queryType).get(listId); if( attr != null ) { Expression entityField = getEntityField(query, listId, attr); predicate = basicCreatePredicateFromSingleCriteria(builder, entityField, criteria); // depends on control dependency: [if], data = [none] } else { predicate = implSpecificCreatePredicateFromSingleCriteria(query, builder, queryType, criteria, queryWhere ); // depends on control dependency: [if], data = [none] } return predicate; } }
public class class_name { public int refreshBookmark(Object bookmark, int iHandleType, boolean bReReadMessage) { if (bookmark == null) return -1; int iTargetPosition = m_gridBuffer.bookmarkToIndex(bookmark, iHandleType); if (iTargetPosition != -1) { // Refresh the data in the buffer. Object objElement = m_gridBuffer.elementAt(iTargetPosition); if (objElement instanceof DataRecord) { // The only thing that I know for sure is the bookmark is correct. DataRecord dataRecord = (DataRecord)objElement; dataRecord.setBuffer(null); dataRecord.setHandle(null, DBConstants.BOOKMARK_HANDLE); dataRecord.setHandle(null, DBConstants.OBJECT_ID_HANDLE); dataRecord.setHandle(null, DBConstants.DATA_SOURCE_HANDLE); dataRecord.setHandle(null, DBConstants.OBJECT_SOURCE_HANDLE); dataRecord.setHandle(bookmark, iHandleType); if (bReReadMessage) { // Re-read and refresh the cache. try { this.get(iTargetPosition); } catch (DBException ex) { ex.printStackTrace(); } } else { BaseTable table = this; while (true) { // Search down the table links for a cache table and then clear the entry. if (table == null) break; if (DBParams.CLIENT.equals(table.getSourceType())) break; if ((table instanceof PassThruTable) && (((PassThruTable)table).getNextTable() != table)) table = ((PassThruTable)table).getNextTable(); else if (table == table.getCurrentTable()) break; else table = table.getCurrentTable(); } // Note: This works great unless there is a cached copy of the record, so invalidate remote cache copy. if (DBParams.CLIENT.equals(table.getSourceType())) { org.jbundle.thin.base.db.client.CachedRemoteTable cacheTable = (org.jbundle.thin.base.db.client.CachedRemoteTable)table.getRemoteTableType(org.jbundle.thin.base.db.client.CachedRemoteTable.class); if (cacheTable != null) cacheTable.setCache(bookmark, null); // Clear cache, so next read will do a physical read } } } } return iTargetPosition; // Return index } }
public class class_name { public int refreshBookmark(Object bookmark, int iHandleType, boolean bReReadMessage) { if (bookmark == null) return -1; int iTargetPosition = m_gridBuffer.bookmarkToIndex(bookmark, iHandleType); if (iTargetPosition != -1) { // Refresh the data in the buffer. Object objElement = m_gridBuffer.elementAt(iTargetPosition); if (objElement instanceof DataRecord) { // The only thing that I know for sure is the bookmark is correct. DataRecord dataRecord = (DataRecord)objElement; dataRecord.setBuffer(null); // depends on control dependency: [if], data = [none] dataRecord.setHandle(null, DBConstants.BOOKMARK_HANDLE); // depends on control dependency: [if], data = [none] dataRecord.setHandle(null, DBConstants.OBJECT_ID_HANDLE); // depends on control dependency: [if], data = [none] dataRecord.setHandle(null, DBConstants.DATA_SOURCE_HANDLE); // depends on control dependency: [if], data = [none] dataRecord.setHandle(null, DBConstants.OBJECT_SOURCE_HANDLE); // depends on control dependency: [if], data = [none] dataRecord.setHandle(bookmark, iHandleType); // depends on control dependency: [if], data = [none] if (bReReadMessage) { // Re-read and refresh the cache. try { this.get(iTargetPosition); // depends on control dependency: [try], data = [none] } catch (DBException ex) { ex.printStackTrace(); } // depends on control dependency: [catch], data = [none] } else { BaseTable table = this; while (true) { // Search down the table links for a cache table and then clear the entry. if (table == null) break; if (DBParams.CLIENT.equals(table.getSourceType())) break; if ((table instanceof PassThruTable) && (((PassThruTable)table).getNextTable() != table)) table = ((PassThruTable)table).getNextTable(); else if (table == table.getCurrentTable()) break; else table = table.getCurrentTable(); } // Note: This works great unless there is a cached copy of the record, so invalidate remote cache copy. if (DBParams.CLIENT.equals(table.getSourceType())) { org.jbundle.thin.base.db.client.CachedRemoteTable cacheTable = (org.jbundle.thin.base.db.client.CachedRemoteTable)table.getRemoteTableType(org.jbundle.thin.base.db.client.CachedRemoteTable.class); if (cacheTable != null) cacheTable.setCache(bookmark, null); // Clear cache, so next read will do a physical read } } } } return iTargetPosition; // Return index } }
public class class_name { public void copy(int start, int limit, int dest) { if (start == limit && start >= 0 && start <= buf.length()) { return; } char[] text = new char[limit - start]; getChars(start, limit, text, 0); replace(dest, dest, text, 0, limit - start); } }
public class class_name { public void copy(int start, int limit, int dest) { if (start == limit && start >= 0 && start <= buf.length()) { return; // depends on control dependency: [if], data = [none] } char[] text = new char[limit - start]; getChars(start, limit, text, 0); replace(dest, dest, text, 0, limit - start); } }
public class class_name { @Override public double getWeight(double distance, double max, double stddev) { if(stddev <= 0) { return 1; } double normdistance = distance / stddev; return scaling * FastMath.exp(-.5 * normdistance * normdistance) / stddev; } }
public class class_name { @Override public double getWeight(double distance, double max, double stddev) { if(stddev <= 0) { return 1; // depends on control dependency: [if], data = [none] } double normdistance = distance / stddev; return scaling * FastMath.exp(-.5 * normdistance * normdistance) / stddev; } }
public class class_name { static GroundyTask get(Class<? extends GroundyTask> taskClass, Context context) { if (CACHE.containsKey(taskClass)) { return CACHE.get(taskClass); } GroundyTask groundyTask = null; try { L.d(TAG, "Instantiating " + taskClass); Constructor ctc = taskClass.getConstructor(); groundyTask = (GroundyTask) ctc.newInstance(); if (groundyTask.canBeCached()) { CACHE.put(taskClass, groundyTask); } else if (CACHE.containsKey(taskClass)) { CACHE.remove(taskClass); } groundyTask.setContext(context); groundyTask.onCreate(); return groundyTask; } catch (Exception e) { L.e(TAG, "Unable to create value for call " + taskClass, e); } return groundyTask; } }
public class class_name { static GroundyTask get(Class<? extends GroundyTask> taskClass, Context context) { if (CACHE.containsKey(taskClass)) { return CACHE.get(taskClass); // depends on control dependency: [if], data = [none] } GroundyTask groundyTask = null; try { L.d(TAG, "Instantiating " + taskClass); // depends on control dependency: [try], data = [none] Constructor ctc = taskClass.getConstructor(); groundyTask = (GroundyTask) ctc.newInstance(); // depends on control dependency: [try], data = [none] if (groundyTask.canBeCached()) { CACHE.put(taskClass, groundyTask); // depends on control dependency: [if], data = [none] } else if (CACHE.containsKey(taskClass)) { CACHE.remove(taskClass); // depends on control dependency: [if], data = [none] } groundyTask.setContext(context); // depends on control dependency: [try], data = [none] groundyTask.onCreate(); // depends on control dependency: [try], data = [none] return groundyTask; // depends on control dependency: [try], data = [none] } catch (Exception e) { L.e(TAG, "Unable to create value for call " + taskClass, e); } // depends on control dependency: [catch], data = [none] return groundyTask; } }
public class class_name { public Set<IConnection> getClientConnections() { Set<IConnection> result = new HashSet<IConnection>(3); log.debug("Client count: {}", clients.size()); for (IClient cli : clients) { Set<IConnection> set = cli.getConnections(); log.debug("Client connection count: {}", set.size()); if (set.size() > 1) { log.warn("Client connections exceeded expected single count; size: {}", set.size()); } for (IConnection conn : set) { result.add(conn); } } return result; } }
public class class_name { public Set<IConnection> getClientConnections() { Set<IConnection> result = new HashSet<IConnection>(3); log.debug("Client count: {}", clients.size()); for (IClient cli : clients) { Set<IConnection> set = cli.getConnections(); log.debug("Client connection count: {}", set.size()); // depends on control dependency: [for], data = [none] if (set.size() > 1) { log.warn("Client connections exceeded expected single count; size: {}", set.size()); // depends on control dependency: [if], data = [none] } for (IConnection conn : set) { result.add(conn); // depends on control dependency: [for], data = [conn] } } return result; } }
public class class_name { public static void logCount(Logger logger, Level level, int count, String singularMessage, String pluralMessage, Object[] singularParams, Object[] pluralParams) { String countStr = numberFormat.get().format(count); if (count > 1 || count == 0) { logger.log(level, pluralMessage, processLogCountParams(countStr, pluralParams)); } else { logger.log(level, singularMessage, processLogCountParams(countStr, singularParams)); } } }
public class class_name { public static void logCount(Logger logger, Level level, int count, String singularMessage, String pluralMessage, Object[] singularParams, Object[] pluralParams) { String countStr = numberFormat.get().format(count); if (count > 1 || count == 0) { logger.log(level, pluralMessage, processLogCountParams(countStr, pluralParams)); // depends on control dependency: [if], data = [none] } else { logger.log(level, singularMessage, processLogCountParams(countStr, singularParams)); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void setInsertableImages(java.util.Collection<InsertableImage> insertableImages) { if (insertableImages == null) { this.insertableImages = null; return; } this.insertableImages = new java.util.ArrayList<InsertableImage>(insertableImages); } }
public class class_name { public void setInsertableImages(java.util.Collection<InsertableImage> insertableImages) { if (insertableImages == null) { this.insertableImages = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.insertableImages = new java.util.ArrayList<InsertableImage>(insertableImages); } }
public class class_name { void mul(int y, MutableBigInteger z) { if (y == 1) { z.copyValue(this); return; } if (y == 0) { z.clear(); return; } // Perform the multiplication word by word long ylong = y & LONG_MASK; int[] zval = (z.value.length < intLen+1 ? new int[intLen + 1] : z.value); long carry = 0; for (int i = intLen-1; i >= 0; i--) { long product = ylong * (value[i+offset] & LONG_MASK) + carry; zval[i+1] = (int)product; carry = product >>> 32; } if (carry == 0) { z.offset = 1; z.intLen = intLen; } else { z.offset = 0; z.intLen = intLen + 1; zval[0] = (int)carry; } z.value = zval; } }
public class class_name { void mul(int y, MutableBigInteger z) { if (y == 1) { z.copyValue(this); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } if (y == 0) { z.clear(); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } // Perform the multiplication word by word long ylong = y & LONG_MASK; int[] zval = (z.value.length < intLen+1 ? new int[intLen + 1] : z.value); long carry = 0; for (int i = intLen-1; i >= 0; i--) { long product = ylong * (value[i+offset] & LONG_MASK) + carry; zval[i+1] = (int)product; // depends on control dependency: [for], data = [i] carry = product >>> 32; // depends on control dependency: [for], data = [none] } if (carry == 0) { z.offset = 1; // depends on control dependency: [if], data = [none] z.intLen = intLen; // depends on control dependency: [if], data = [none] } else { z.offset = 0; // depends on control dependency: [if], data = [none] z.intLen = intLen + 1; // depends on control dependency: [if], data = [none] zval[0] = (int)carry; // depends on control dependency: [if], data = [none] } z.value = zval; } }
public class class_name { protected Subject createPartialSubject(String username, AuthenticationService authenticationService, String customCacheKey) { Subject partialSubject = null; partialSubject = new Subject(); Hashtable<String, Object> hashtable = new Hashtable<String, Object>(); hashtable.put(AttributeNameConstants.WSCREDENTIAL_USERID, username); // only set the property in the hashtable if the public property is not already set; // this property allows authentication when only the username is supplied if (!authenticationService.isAllowHashTableLoginWithIdOnly()) { hashtable.put(AuthenticationConstants.INTERNAL_ASSERTION_KEY, Boolean.TRUE); } if (customCacheKey != null) { hashtable.put(AttributeNameConstants.WSCREDENTIAL_CACHE_KEY, customCacheKey); } partialSubject.getPublicCredentials().add(hashtable); return partialSubject; } }
public class class_name { protected Subject createPartialSubject(String username, AuthenticationService authenticationService, String customCacheKey) { Subject partialSubject = null; partialSubject = new Subject(); Hashtable<String, Object> hashtable = new Hashtable<String, Object>(); hashtable.put(AttributeNameConstants.WSCREDENTIAL_USERID, username); // only set the property in the hashtable if the public property is not already set; // this property allows authentication when only the username is supplied if (!authenticationService.isAllowHashTableLoginWithIdOnly()) { hashtable.put(AuthenticationConstants.INTERNAL_ASSERTION_KEY, Boolean.TRUE); // depends on control dependency: [if], data = [none] } if (customCacheKey != null) { hashtable.put(AttributeNameConstants.WSCREDENTIAL_CACHE_KEY, customCacheKey); // depends on control dependency: [if], data = [none] } partialSubject.getPublicCredentials().add(hashtable); return partialSubject; } }
public class class_name { public static Component findParentByClassname(final Component childComponent, final Class<? extends Component> parentClass) { Component parent = childComponent.getParent(); while (parent != null) { if (ClassExtensions.equalsByClassName(parentClass, parent.getClass())) { break; } parent = parent.getParent(); } return parent; } }
public class class_name { public static Component findParentByClassname(final Component childComponent, final Class<? extends Component> parentClass) { Component parent = childComponent.getParent(); while (parent != null) { if (ClassExtensions.equalsByClassName(parentClass, parent.getClass())) { break; } parent = parent.getParent(); // depends on control dependency: [while], data = [none] } return parent; } }
public class class_name { private void checkFirstModule(List<JSModule> modules) { if (modules.isEmpty()) { report(JSError.make(EMPTY_MODULE_LIST_ERROR)); } else if (modules.get(0).getInputs().isEmpty() && modules.size() > 1) { // The root module may only be empty if there is exactly 1 module. report(JSError.make(EMPTY_ROOT_MODULE_ERROR, modules.get(0).getName())); } } }
public class class_name { private void checkFirstModule(List<JSModule> modules) { if (modules.isEmpty()) { report(JSError.make(EMPTY_MODULE_LIST_ERROR)); // depends on control dependency: [if], data = [none] } else if (modules.get(0).getInputs().isEmpty() && modules.size() > 1) { // The root module may only be empty if there is exactly 1 module. report(JSError.make(EMPTY_ROOT_MODULE_ERROR, modules.get(0).getName())); // depends on control dependency: [if], data = [none] } } }
public class class_name { private void setProprietaryInformationIndicator( RROtherProjectInfo12Document.RROtherProjectInfo12 rrOtherProjectInfo) { YesNoDataType.Enum answer = null; String propertyInformationAnswer = getAnswer(PROPRIETARY_INFORMATION_INDICATOR, answerHeaders); if (propertyInformationAnswer != null && !propertyInformationAnswer.equals(NOT_ANSWERED)) { answer = YnqConstant.YES.code().equals( propertyInformationAnswer) ? YesNoDataType.Y_YES : YesNoDataType.N_NO; rrOtherProjectInfo.setProprietaryInformationIndicator(answer); } else { rrOtherProjectInfo.setProprietaryInformationIndicator(null); } } }
public class class_name { private void setProprietaryInformationIndicator( RROtherProjectInfo12Document.RROtherProjectInfo12 rrOtherProjectInfo) { YesNoDataType.Enum answer = null; String propertyInformationAnswer = getAnswer(PROPRIETARY_INFORMATION_INDICATOR, answerHeaders); if (propertyInformationAnswer != null && !propertyInformationAnswer.equals(NOT_ANSWERED)) { answer = YnqConstant.YES.code().equals( propertyInformationAnswer) ? YesNoDataType.Y_YES : YesNoDataType.N_NO; // depends on control dependency: [if], data = [none] rrOtherProjectInfo.setProprietaryInformationIndicator(answer); // depends on control dependency: [if], data = [none] } else { rrOtherProjectInfo.setProprietaryInformationIndicator(null); // depends on control dependency: [if], data = [none] } } }
public class class_name { private void importAllResources() throws CmsImportExportException { String source, destination, type, uuidresource, userlastmodified, usercreated, flags, timestamp; long datelastmodified, datecreated; List<Node> fileNodes; List<Node> acentryNodes; Element currentElement, currentEntry; List<CmsProperty> properties = null; // get list of unwanted properties List<String> deleteProperties = OpenCms.getImportExportManager().getIgnoredProperties(); if (deleteProperties == null) { deleteProperties = new ArrayList<String>(); } // get list of immutable resources List<String> immutableResources = OpenCms.getImportExportManager().getImmutableResources(); if (immutableResources == null) { immutableResources = Collections.EMPTY_LIST; } if (LOG.isDebugEnabled()) { LOG.debug( Messages.get().getBundle().key( Messages.LOG_IMPORTEXPORT_IMMUTABLE_RESOURCES_SIZE_1, Integer.toString(immutableResources.size()))); } // get the wanted page type for imported pages m_convertToXmlPage = OpenCms.getImportExportManager().convertToXmlPage(); try { // get all file-nodes fileNodes = m_docXml.selectNodes("//" + A_CmsImport.N_FILE); int importSize = fileNodes.size(); // walk through all files in manifest for (int i = 0; i < fileNodes.size(); i++) { m_report.print( org.opencms.report.Messages.get().container( org.opencms.report.Messages.RPT_SUCCESSION_2, String.valueOf(i + 1), String.valueOf(importSize))); currentElement = (Element)fileNodes.get(i); // get all information for a file-import // <source> source = getChildElementTextValue(currentElement, A_CmsImport.N_SOURCE); // <destintion> destination = getChildElementTextValue(currentElement, A_CmsImport.N_DESTINATION); // <type> type = getChildElementTextValue(currentElement, A_CmsImport.N_TYPE); // <uuidstructure> //uuidstructure = CmsImport.getChildElementTextValue( // currentElement, // CmsImportExportManager.N_UUIDSTRUCTURE); // <uuidresource> uuidresource = getChildElementTextValue(currentElement, A_CmsImport.N_UUIDRESOURCE); // <datelastmodified> timestamp = getChildElementTextValue(currentElement, A_CmsImport.N_DATELASTMODIFIED); if (timestamp != null) { datelastmodified = Long.parseLong(timestamp); } else { datelastmodified = System.currentTimeMillis(); } // <userlastmodified> userlastmodified = getChildElementTextValue(currentElement, A_CmsImport.N_USERLASTMODIFIED); // <datecreated> timestamp = getChildElementTextValue(currentElement, A_CmsImport.N_DATECREATED); if (timestamp != null) { datecreated = Long.parseLong(timestamp); } else { datecreated = System.currentTimeMillis(); } // <usercreated> usercreated = getChildElementTextValue(currentElement, A_CmsImport.N_USERCREATED); // <flags> flags = getChildElementTextValue(currentElement, A_CmsImport.N_FLAGS); String translatedName = m_cms.getRequestContext().addSiteRoot(m_importPath + destination); if (CmsResourceTypeFolder.RESOURCE_TYPE_NAME.equals(type)) { translatedName += "/"; } // translate the name during import translatedName = m_cms.getRequestContext().getDirectoryTranslator().translateResource(translatedName); // check if this resource is immutable boolean resourceNotImmutable = checkImmutable(translatedName, immutableResources); translatedName = m_cms.getRequestContext().removeSiteRoot(translatedName); // if the resource is not immutable and not on the exclude list, import it if (resourceNotImmutable) { // print out the information to the report m_report.print(Messages.get().container(Messages.RPT_IMPORTING_0), I_CmsReport.FORMAT_NOTE); m_report.print( org.opencms.report.Messages.get().container( org.opencms.report.Messages.RPT_ARGUMENT_1, translatedName)); //m_report.print(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_OK_0)); // get all properties properties = readPropertiesFromManifest(currentElement, deleteProperties); // import the resource CmsResource res = importResource( source, destination, type, uuidresource, datelastmodified, userlastmodified, datecreated, usercreated, flags, properties); List<CmsAccessControlEntry> aceList = new ArrayList<CmsAccessControlEntry>(); if (res != null) { // write all imported access control entries for this file acentryNodes = currentElement.selectNodes("*/" + A_CmsImport.N_ACCESSCONTROL_ENTRY); // collect all access control entries for (int j = 0; j < acentryNodes.size(); j++) { currentEntry = (Element)acentryNodes.get(j); // get the data of the access control entry String id = getChildElementTextValue(currentEntry, A_CmsImport.N_ACCESSCONTROL_PRINCIPAL); String acflags = getChildElementTextValue(currentEntry, A_CmsImport.N_FLAGS); String allowed = getChildElementTextValue( currentEntry, A_CmsImport.N_ACCESSCONTROL_PERMISSIONSET + "/" + A_CmsImport.N_ACCESSCONTROL_ALLOWEDPERMISSIONS); String denied = getChildElementTextValue( currentEntry, A_CmsImport.N_ACCESSCONTROL_PERMISSIONSET + "/" + A_CmsImport.N_ACCESSCONTROL_DENIEDPERMISSIONS); // get the correct principal try { String principalId = new CmsUUID().toString(); String principal = id.substring(id.indexOf('.') + 1, id.length()); if (id.startsWith(I_CmsPrincipal.PRINCIPAL_GROUP)) { principal = OpenCms.getImportExportManager().translateGroup(principal); principalId = m_cms.readGroup(principal).getId().toString(); } else { principal = OpenCms.getImportExportManager().translateUser(principal); principalId = m_cms.readUser(principal).getId().toString(); } // add the entry to the list aceList.add(getImportAccessControlEntry(res, principalId, allowed, denied, acflags)); } catch (CmsDataAccessException e) { // user or group not found, so do not import the ace } } importAccessControlEntries(res, aceList); } else { // resource import failed, since no CmsResource was created m_report.print(Messages.get().container(Messages.RPT_SKIPPING_0), I_CmsReport.FORMAT_NOTE); m_report.println( org.opencms.report.Messages.get().container( org.opencms.report.Messages.RPT_ARGUMENT_1, translatedName)); } } else { // skip the file import, just print out the information to the report m_report.print(Messages.get().container(Messages.RPT_SKIPPING_0), I_CmsReport.FORMAT_NOTE); m_report.println( org.opencms.report.Messages.get().container( org.opencms.report.Messages.RPT_ARGUMENT_1, translatedName)); } } } catch (Exception e) { m_report.println(e); m_report.addError(e); CmsMessageContainer message = Messages.get().container( Messages.ERR_IMPORTEXPORT_ERROR_IMPORTING_RESOURCES_0); if (LOG.isDebugEnabled()) { LOG.debug(message.key(), e); } throw new CmsImportExportException(message, e); } } }
public class class_name { private void importAllResources() throws CmsImportExportException { String source, destination, type, uuidresource, userlastmodified, usercreated, flags, timestamp; long datelastmodified, datecreated; List<Node> fileNodes; List<Node> acentryNodes; Element currentElement, currentEntry; List<CmsProperty> properties = null; // get list of unwanted properties List<String> deleteProperties = OpenCms.getImportExportManager().getIgnoredProperties(); if (deleteProperties == null) { deleteProperties = new ArrayList<String>(); } // get list of immutable resources List<String> immutableResources = OpenCms.getImportExportManager().getImmutableResources(); if (immutableResources == null) { immutableResources = Collections.EMPTY_LIST; } if (LOG.isDebugEnabled()) { LOG.debug( Messages.get().getBundle().key( Messages.LOG_IMPORTEXPORT_IMMUTABLE_RESOURCES_SIZE_1, Integer.toString(immutableResources.size()))); } // get the wanted page type for imported pages m_convertToXmlPage = OpenCms.getImportExportManager().convertToXmlPage(); try { // get all file-nodes fileNodes = m_docXml.selectNodes("//" + A_CmsImport.N_FILE); int importSize = fileNodes.size(); // walk through all files in manifest for (int i = 0; i < fileNodes.size(); i++) { m_report.print( org.opencms.report.Messages.get().container( org.opencms.report.Messages.RPT_SUCCESSION_2, String.valueOf(i + 1), String.valueOf(importSize))); currentElement = (Element)fileNodes.get(i); // get all information for a file-import // <source> source = getChildElementTextValue(currentElement, A_CmsImport.N_SOURCE); // <destintion> destination = getChildElementTextValue(currentElement, A_CmsImport.N_DESTINATION); // <type> type = getChildElementTextValue(currentElement, A_CmsImport.N_TYPE); // <uuidstructure> //uuidstructure = CmsImport.getChildElementTextValue( // currentElement, // CmsImportExportManager.N_UUIDSTRUCTURE); // <uuidresource> uuidresource = getChildElementTextValue(currentElement, A_CmsImport.N_UUIDRESOURCE); // <datelastmodified> timestamp = getChildElementTextValue(currentElement, A_CmsImport.N_DATELASTMODIFIED); if (timestamp != null) { datelastmodified = Long.parseLong(timestamp); } else { datelastmodified = System.currentTimeMillis(); } // <userlastmodified> userlastmodified = getChildElementTextValue(currentElement, A_CmsImport.N_USERLASTMODIFIED); // <datecreated> timestamp = getChildElementTextValue(currentElement, A_CmsImport.N_DATECREATED); if (timestamp != null) { datecreated = Long.parseLong(timestamp); } else { datecreated = System.currentTimeMillis(); } // <usercreated> usercreated = getChildElementTextValue(currentElement, A_CmsImport.N_USERCREATED); // <flags> flags = getChildElementTextValue(currentElement, A_CmsImport.N_FLAGS); String translatedName = m_cms.getRequestContext().addSiteRoot(m_importPath + destination); if (CmsResourceTypeFolder.RESOURCE_TYPE_NAME.equals(type)) { translatedName += "/"; } // translate the name during import translatedName = m_cms.getRequestContext().getDirectoryTranslator().translateResource(translatedName); // check if this resource is immutable boolean resourceNotImmutable = checkImmutable(translatedName, immutableResources); translatedName = m_cms.getRequestContext().removeSiteRoot(translatedName); // if the resource is not immutable and not on the exclude list, import it if (resourceNotImmutable) { // print out the information to the report m_report.print(Messages.get().container(Messages.RPT_IMPORTING_0), I_CmsReport.FORMAT_NOTE); m_report.print( org.opencms.report.Messages.get().container( org.opencms.report.Messages.RPT_ARGUMENT_1, translatedName)); //m_report.print(org.opencms.report.Messages.get().container(org.opencms.report.Messages.RPT_OK_0)); // get all properties properties = readPropertiesFromManifest(currentElement, deleteProperties); // import the resource CmsResource res = importResource( source, destination, type, uuidresource, datelastmodified, userlastmodified, datecreated, usercreated, flags, properties); List<CmsAccessControlEntry> aceList = new ArrayList<CmsAccessControlEntry>(); if (res != null) { // write all imported access control entries for this file acentryNodes = currentElement.selectNodes("*/" + A_CmsImport.N_ACCESSCONTROL_ENTRY); // depends on control dependency: [if], data = [none] // collect all access control entries for (int j = 0; j < acentryNodes.size(); j++) { currentEntry = (Element)acentryNodes.get(j); // depends on control dependency: [for], data = [j] // get the data of the access control entry String id = getChildElementTextValue(currentEntry, A_CmsImport.N_ACCESSCONTROL_PRINCIPAL); String acflags = getChildElementTextValue(currentEntry, A_CmsImport.N_FLAGS); String allowed = getChildElementTextValue( currentEntry, A_CmsImport.N_ACCESSCONTROL_PERMISSIONSET + "/" + A_CmsImport.N_ACCESSCONTROL_ALLOWEDPERMISSIONS); String denied = getChildElementTextValue( currentEntry, A_CmsImport.N_ACCESSCONTROL_PERMISSIONSET + "/" + A_CmsImport.N_ACCESSCONTROL_DENIEDPERMISSIONS); // get the correct principal try { String principalId = new CmsUUID().toString(); String principal = id.substring(id.indexOf('.') + 1, id.length()); if (id.startsWith(I_CmsPrincipal.PRINCIPAL_GROUP)) { principal = OpenCms.getImportExportManager().translateGroup(principal); // depends on control dependency: [if], data = [none] principalId = m_cms.readGroup(principal).getId().toString(); // depends on control dependency: [if], data = [none] } else { principal = OpenCms.getImportExportManager().translateUser(principal); // depends on control dependency: [if], data = [none] principalId = m_cms.readUser(principal).getId().toString(); // depends on control dependency: [if], data = [none] } // add the entry to the list aceList.add(getImportAccessControlEntry(res, principalId, allowed, denied, acflags)); // depends on control dependency: [try], data = [none] } catch (CmsDataAccessException e) { // user or group not found, so do not import the ace } // depends on control dependency: [catch], data = [none] } importAccessControlEntries(res, aceList); // depends on control dependency: [if], data = [(res] } else { // resource import failed, since no CmsResource was created m_report.print(Messages.get().container(Messages.RPT_SKIPPING_0), I_CmsReport.FORMAT_NOTE); // depends on control dependency: [if], data = [none] m_report.println( org.opencms.report.Messages.get().container( org.opencms.report.Messages.RPT_ARGUMENT_1, translatedName)); // depends on control dependency: [if], data = [none] } } else { // skip the file import, just print out the information to the report m_report.print(Messages.get().container(Messages.RPT_SKIPPING_0), I_CmsReport.FORMAT_NOTE); m_report.println( org.opencms.report.Messages.get().container( org.opencms.report.Messages.RPT_ARGUMENT_1, translatedName)); } } } catch (Exception e) { m_report.println(e); m_report.addError(e); CmsMessageContainer message = Messages.get().container( Messages.ERR_IMPORTEXPORT_ERROR_IMPORTING_RESOURCES_0); if (LOG.isDebugEnabled()) { LOG.debug(message.key(), e); } throw new CmsImportExportException(message, e); } } }
public class class_name { public boolean isChecksumValid() { if(checksum == 0) return true; int crc = CRCUtils.getCRC(getHeader()); if(data != null && data.length > 0) { crc = CRCUtils.getCRC(data, crc); } return (checksum == crc); } }
public class class_name { public boolean isChecksumValid() { if(checksum == 0) return true; int crc = CRCUtils.getCRC(getHeader()); if(data != null && data.length > 0) { crc = CRCUtils.getCRC(data, crc); // depends on control dependency: [if], data = [(data] } return (checksum == crc); } }
public class class_name { protected void processMessage(String message) throws ActivityException { try { String rcvdMsgDocVar = getAttributeValueSmart(RECEIVED_MESSAGE_DOC_VAR); if (rcvdMsgDocVar != null && !rcvdMsgDocVar.isEmpty()) { Process processVO = getProcessDefinition(); Variable variableVO = processVO.getVariable(rcvdMsgDocVar); if (variableVO == null) throw new ActivityException("Received Message Variable '" + rcvdMsgDocVar + "' is not defined or is not Document Type for process " + processVO.getFullLabel()); if (message != null) { this.setParameterValueAsDocument(rcvdMsgDocVar, variableVO.getType(), message); } } return; } catch (Exception ex) { logger.severeException(ex.getMessage(), ex); return; } } }
public class class_name { protected void processMessage(String message) throws ActivityException { try { String rcvdMsgDocVar = getAttributeValueSmart(RECEIVED_MESSAGE_DOC_VAR); if (rcvdMsgDocVar != null && !rcvdMsgDocVar.isEmpty()) { Process processVO = getProcessDefinition(); Variable variableVO = processVO.getVariable(rcvdMsgDocVar); if (variableVO == null) throw new ActivityException("Received Message Variable '" + rcvdMsgDocVar + "' is not defined or is not Document Type for process " + processVO.getFullLabel()); if (message != null) { this.setParameterValueAsDocument(rcvdMsgDocVar, variableVO.getType(), message); // depends on control dependency: [if], data = [none] } } return; } catch (Exception ex) { logger.severeException(ex.getMessage(), ex); return; } } }