code
stringlengths
130
281k
code_dependency
stringlengths
182
306k
public class class_name { private void handleSelectionRequest(final Request request) { String[] paramValue = request.getParameterValues(getId() + ".selected"); if (paramValue == null) { paramValue = new String[0]; } String[] selectedRows = removeEmptyStrings(paramValue); List<Integer> oldSelections = getSelectedRows(); List<Integer> newSelections; boolean singleSelect = SelectMode.SINGLE.equals(getSelectMode()); if (getDataModel().getRowCount() == 0) { newSelections = new ArrayList<>(); selectedRows = new String[0]; } else if (getPaginationMode() == PaginationMode.NONE || getPaginationMode() == PaginationMode.CLIENT || oldSelections == null) { newSelections = new ArrayList<>(selectedRows.length); } else if (singleSelect && selectedRows.length > 0) { // For single-select, we need to remove the old entries newSelections = new ArrayList<>(1); } else { // For multi-select, we need to entries for the current page only newSelections = new ArrayList<>(oldSelections); int startRow = getCurrentPageStartRow(); int endRow = getCurrentPageEndRow(); newSelections.removeAll(getRowIds(startRow, endRow)); } for (String selectedRow : selectedRows) { try { newSelections.add(Integer.parseInt(selectedRow)); if (singleSelect) { break; } } catch (NumberFormatException e) { LOG.warn("Invalid row id for selection: " + selectedRow); } } setSelectedRows(newSelections); // If there is a selection change action specified, it may need to be fired Action selectionChangeAction = getSelectionChangeAction(); if (selectionChangeAction != null && !newSelections.equals(oldSelections)) { selectionChangeAction.execute(new ActionEvent(this, "selection")); } } }
public class class_name { private void handleSelectionRequest(final Request request) { String[] paramValue = request.getParameterValues(getId() + ".selected"); if (paramValue == null) { paramValue = new String[0]; // depends on control dependency: [if], data = [none] } String[] selectedRows = removeEmptyStrings(paramValue); List<Integer> oldSelections = getSelectedRows(); List<Integer> newSelections; boolean singleSelect = SelectMode.SINGLE.equals(getSelectMode()); if (getDataModel().getRowCount() == 0) { newSelections = new ArrayList<>(); // depends on control dependency: [if], data = [none] selectedRows = new String[0]; // depends on control dependency: [if], data = [none] } else if (getPaginationMode() == PaginationMode.NONE || getPaginationMode() == PaginationMode.CLIENT || oldSelections == null) { newSelections = new ArrayList<>(selectedRows.length); // depends on control dependency: [if], data = [none] } else if (singleSelect && selectedRows.length > 0) { // For single-select, we need to remove the old entries newSelections = new ArrayList<>(1); // depends on control dependency: [if], data = [none] } else { // For multi-select, we need to entries for the current page only newSelections = new ArrayList<>(oldSelections); // depends on control dependency: [if], data = [none] int startRow = getCurrentPageStartRow(); int endRow = getCurrentPageEndRow(); newSelections.removeAll(getRowIds(startRow, endRow)); // depends on control dependency: [if], data = [none] } for (String selectedRow : selectedRows) { try { newSelections.add(Integer.parseInt(selectedRow)); // depends on control dependency: [try], data = [none] if (singleSelect) { break; } } catch (NumberFormatException e) { LOG.warn("Invalid row id for selection: " + selectedRow); } // depends on control dependency: [catch], data = [none] } setSelectedRows(newSelections); // If there is a selection change action specified, it may need to be fired Action selectionChangeAction = getSelectionChangeAction(); if (selectionChangeAction != null && !newSelections.equals(oldSelections)) { selectionChangeAction.execute(new ActionEvent(this, "selection")); // depends on control dependency: [if], data = [none] } } }
public class class_name { @SuppressWarnings("MethodLength") public static UdpChannel parse(final String channelUriString) { try { final ChannelUri channelUri = ChannelUri.parse(channelUriString); validateConfiguration(channelUri); InetSocketAddress endpointAddress = getEndpointAddress(channelUri); final InetSocketAddress explicitControlAddress = getExplicitControlAddress(channelUri); final String tagIdStr = channelUri.channelTag(); final String controlMode = channelUri.get(CommonContext.MDC_CONTROL_MODE_PARAM_NAME); final boolean hasNoDistinguishingCharacteristic = null == endpointAddress && null == explicitControlAddress && null == tagIdStr; if (hasNoDistinguishingCharacteristic && null == controlMode) { throw new IllegalArgumentException( "Aeron URIs for UDP must specify an endpoint address, control address, tag-id, or control-mode"); } if (null != endpointAddress && endpointAddress.isUnresolved()) { throw new UnknownHostException("could not resolve endpoint address: " + endpointAddress); } if (null != explicitControlAddress && explicitControlAddress.isUnresolved()) { throw new UnknownHostException("could not resolve control address: " + explicitControlAddress); } final Context context = new Context() .uriStr(channelUriString) .channelUri(channelUri) .hasNoDistinguishingCharacteristic(hasNoDistinguishingCharacteristic); if (null != tagIdStr) { context.hasTagId(true).tagId(Long.parseLong(tagIdStr)); } if (null == endpointAddress) { endpointAddress = new InetSocketAddress("0.0.0.0", 0); } if (endpointAddress.getAddress().isMulticastAddress()) { final InetSocketAddress controlAddress = getMulticastControlAddress(endpointAddress); final InterfaceSearchAddress searchAddress = getInterfaceSearchAddress(channelUri); final NetworkInterface localInterface = findInterface(searchAddress); final InetSocketAddress resolvedAddress = resolveToAddressOfInterface(localInterface, searchAddress); context .isMulticast(true) .localControlAddress(resolvedAddress) .remoteControlAddress(controlAddress) .localDataAddress(resolvedAddress) .remoteDataAddress(endpointAddress) .localInterface(localInterface) .protocolFamily(getProtocolFamily(endpointAddress.getAddress())) .canonicalForm(canonicalise(resolvedAddress, endpointAddress)); final String ttlValue = channelUri.get(CommonContext.TTL_PARAM_NAME); if (null != ttlValue) { context.hasMulticastTtl(true).multicastTtl(Integer.parseInt(ttlValue)); } } else if (null != explicitControlAddress) { context .hasExplicitControl(true) .remoteControlAddress(endpointAddress) .remoteDataAddress(endpointAddress) .localControlAddress(explicitControlAddress) .localDataAddress(explicitControlAddress) .protocolFamily(getProtocolFamily(endpointAddress.getAddress())) .canonicalForm(canonicalise(explicitControlAddress, endpointAddress)); } else { final InterfaceSearchAddress searchAddress = getInterfaceSearchAddress(channelUri); final InetSocketAddress localAddress = searchAddress.getInetAddress().isAnyLocalAddress() ? searchAddress.getAddress() : resolveToAddressOfInterface(findInterface(searchAddress), searchAddress); final String uniqueCanonicalFormSuffix = hasNoDistinguishingCharacteristic ? ("-" + UNIQUE_CANONICAL_FORM_VALUE.getAndAdd(1)) : ""; context .remoteControlAddress(endpointAddress) .remoteDataAddress(endpointAddress) .localControlAddress(localAddress) .localDataAddress(localAddress) .protocolFamily(getProtocolFamily(endpointAddress.getAddress())) .canonicalForm(canonicalise(localAddress, endpointAddress) + uniqueCanonicalFormSuffix); } return new UdpChannel(context); } catch (final Exception ex) { throw new InvalidChannelException(ErrorCode.INVALID_CHANNEL, ex); } } }
public class class_name { @SuppressWarnings("MethodLength") public static UdpChannel parse(final String channelUriString) { try { final ChannelUri channelUri = ChannelUri.parse(channelUriString); validateConfiguration(channelUri); // depends on control dependency: [try], data = [none] InetSocketAddress endpointAddress = getEndpointAddress(channelUri); final InetSocketAddress explicitControlAddress = getExplicitControlAddress(channelUri); final String tagIdStr = channelUri.channelTag(); final String controlMode = channelUri.get(CommonContext.MDC_CONTROL_MODE_PARAM_NAME); final boolean hasNoDistinguishingCharacteristic = null == endpointAddress && null == explicitControlAddress && null == tagIdStr; if (hasNoDistinguishingCharacteristic && null == controlMode) { throw new IllegalArgumentException( "Aeron URIs for UDP must specify an endpoint address, control address, tag-id, or control-mode"); } if (null != endpointAddress && endpointAddress.isUnresolved()) { throw new UnknownHostException("could not resolve endpoint address: " + endpointAddress); } if (null != explicitControlAddress && explicitControlAddress.isUnresolved()) { throw new UnknownHostException("could not resolve control address: " + explicitControlAddress); } final Context context = new Context() .uriStr(channelUriString) .channelUri(channelUri) .hasNoDistinguishingCharacteristic(hasNoDistinguishingCharacteristic); if (null != tagIdStr) { context.hasTagId(true).tagId(Long.parseLong(tagIdStr)); // depends on control dependency: [if], data = [tagIdStr)] } if (null == endpointAddress) { endpointAddress = new InetSocketAddress("0.0.0.0", 0); // depends on control dependency: [if], data = [none] } if (endpointAddress.getAddress().isMulticastAddress()) { final InetSocketAddress controlAddress = getMulticastControlAddress(endpointAddress); final InterfaceSearchAddress searchAddress = getInterfaceSearchAddress(channelUri); final NetworkInterface localInterface = findInterface(searchAddress); final InetSocketAddress resolvedAddress = resolveToAddressOfInterface(localInterface, searchAddress); context .isMulticast(true) .localControlAddress(resolvedAddress) .remoteControlAddress(controlAddress) .localDataAddress(resolvedAddress) .remoteDataAddress(endpointAddress) .localInterface(localInterface) .protocolFamily(getProtocolFamily(endpointAddress.getAddress())) .canonicalForm(canonicalise(resolvedAddress, endpointAddress)); // depends on control dependency: [if], data = [none] final String ttlValue = channelUri.get(CommonContext.TTL_PARAM_NAME); if (null != ttlValue) { context.hasMulticastTtl(true).multicastTtl(Integer.parseInt(ttlValue)); // depends on control dependency: [if], data = [ttlValue)] } } else if (null != explicitControlAddress) { context .hasExplicitControl(true) .remoteControlAddress(endpointAddress) .remoteDataAddress(endpointAddress) .localControlAddress(explicitControlAddress) .localDataAddress(explicitControlAddress) .protocolFamily(getProtocolFamily(endpointAddress.getAddress())) .canonicalForm(canonicalise(explicitControlAddress, endpointAddress)); // depends on control dependency: [if], data = [none] } else { final InterfaceSearchAddress searchAddress = getInterfaceSearchAddress(channelUri); final InetSocketAddress localAddress = searchAddress.getInetAddress().isAnyLocalAddress() ? searchAddress.getAddress() : resolveToAddressOfInterface(findInterface(searchAddress), searchAddress); final String uniqueCanonicalFormSuffix = hasNoDistinguishingCharacteristic ? ("-" + UNIQUE_CANONICAL_FORM_VALUE.getAndAdd(1)) : ""; context .remoteControlAddress(endpointAddress) .remoteDataAddress(endpointAddress) .localControlAddress(localAddress) .localDataAddress(localAddress) .protocolFamily(getProtocolFamily(endpointAddress.getAddress())) .canonicalForm(canonicalise(localAddress, endpointAddress) + uniqueCanonicalFormSuffix); } return new UdpChannel(context); // depends on control dependency: [try], data = [none] } catch (final Exception ex) { throw new InvalidChannelException(ErrorCode.INVALID_CHANNEL, ex); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static void preloadUidCache(final TSDB tsdb, final ByteMap<UniqueId> uid_cache_map) throws HBaseException { int max_results = tsdb.getConfig().getInt( "tsd.core.preload_uid_cache.max_entries"); LOG.info("Preloading uid cache with max_results=" + max_results); if (max_results <= 0) { return; } Scanner scanner = null; try { int num_rows = 0; scanner = getSuggestScanner(tsdb.getClient(), tsdb.uidTable(), "", null, max_results); for (ArrayList<ArrayList<KeyValue>> rows = scanner.nextRows().join(); rows != null; rows = scanner.nextRows().join()) { for (final ArrayList<KeyValue> row : rows) { for (KeyValue kv: row) { final String name = fromBytes(kv.key()); final byte[] kind = kv.qualifier(); final byte[] id = kv.value(); LOG.debug("id='{}', name='{}', kind='{}'", Arrays.toString(id), name, fromBytes(kind)); UniqueId uid_cache = uid_cache_map.get(kind); if (uid_cache != null) { uid_cache.cacheMapping(name, id); } } num_rows += row.size(); row.clear(); // free() if (num_rows >= max_results) { break; } } } for (UniqueId unique_id_table : uid_cache_map.values()) { LOG.info("After preloading, uid cache '{}' has {} ids and {} names.", unique_id_table.kind(), unique_id_table.use_lru ? unique_id_table.lru_id_cache.size() : unique_id_table.id_cache.size(), unique_id_table.use_lru ? unique_id_table.lru_name_cache.size() : unique_id_table.name_cache.size()); } } catch (Exception e) { if (e instanceof HBaseException) { throw (HBaseException)e; } else if (e instanceof RuntimeException) { throw (RuntimeException)e; } else { throw new RuntimeException("Error while preloading IDs", e); } } finally { if (scanner != null) { scanner.close(); } } } }
public class class_name { public static void preloadUidCache(final TSDB tsdb, final ByteMap<UniqueId> uid_cache_map) throws HBaseException { int max_results = tsdb.getConfig().getInt( "tsd.core.preload_uid_cache.max_entries"); LOG.info("Preloading uid cache with max_results=" + max_results); if (max_results <= 0) { return; } Scanner scanner = null; try { int num_rows = 0; scanner = getSuggestScanner(tsdb.getClient(), tsdb.uidTable(), "", null, max_results); for (ArrayList<ArrayList<KeyValue>> rows = scanner.nextRows().join(); rows != null; rows = scanner.nextRows().join()) { for (final ArrayList<KeyValue> row : rows) { for (KeyValue kv: row) { final String name = fromBytes(kv.key()); final byte[] kind = kv.qualifier(); final byte[] id = kv.value(); LOG.debug("id='{}', name='{}', kind='{}'", Arrays.toString(id), name, fromBytes(kind)); // depends on control dependency: [for], data = [none] UniqueId uid_cache = uid_cache_map.get(kind); if (uid_cache != null) { uid_cache.cacheMapping(name, id); // depends on control dependency: [if], data = [none] } } num_rows += row.size(); row.clear(); // free() if (num_rows >= max_results) { break; } } } for (UniqueId unique_id_table : uid_cache_map.values()) { LOG.info("After preloading, uid cache '{}' has {} ids and {} names.", unique_id_table.kind(), unique_id_table.use_lru ? unique_id_table.lru_id_cache.size() : unique_id_table.id_cache.size(), unique_id_table.use_lru ? unique_id_table.lru_name_cache.size() : unique_id_table.name_cache.size()); } } catch (Exception e) { if (e instanceof HBaseException) { throw (HBaseException)e; } else if (e instanceof RuntimeException) { throw (RuntimeException)e; } else { throw new RuntimeException("Error while preloading IDs", e); } } finally { if (scanner != null) { scanner.close(); } } } }
public class class_name { public static PrimitiveValue parse( final String value, final int length, final String characterEncoding) { if (value.length() > length) { throw new IllegalStateException("value.length=" + value.length() + " greater than length=" + length); } byte[] bytes = value.getBytes(forName(characterEncoding)); if (bytes.length < length) { bytes = Arrays.copyOf(bytes, length); } return new PrimitiveValue(bytes, characterEncoding, length); } }
public class class_name { public static PrimitiveValue parse( final String value, final int length, final String characterEncoding) { if (value.length() > length) { throw new IllegalStateException("value.length=" + value.length() + " greater than length=" + length); } byte[] bytes = value.getBytes(forName(characterEncoding)); if (bytes.length < length) { bytes = Arrays.copyOf(bytes, length); // depends on control dependency: [if], data = [length)] } return new PrimitiveValue(bytes, characterEncoding, length); } }
public class class_name { public static String readAndClose(Reader reader) { try { return read(reader).toString(); } catch (IOException e) { throw Lang.wrapThrow(e); } finally { safeClose(reader); } } }
public class class_name { public static String readAndClose(Reader reader) { try { return read(reader).toString(); // depends on control dependency: [try], data = [none] } catch (IOException e) { throw Lang.wrapThrow(e); } // depends on control dependency: [catch], data = [none] finally { safeClose(reader); } } }
public class class_name { @Deprecated public static BasicDBObject parseFieldsString(final String str, final Class clazz, final Mapper mapper, final boolean validate) { BasicDBObject ret = new BasicDBObject(); final String[] parts = str.split(","); for (String s : parts) { s = s.trim(); int dir = 1; if (s.startsWith("-")) { dir = -1; s = s.substring(1).trim(); } if (validate) { s = new PathTarget(mapper, clazz, s).translatedPath(); } ret.put(s, dir); } return ret; } }
public class class_name { @Deprecated public static BasicDBObject parseFieldsString(final String str, final Class clazz, final Mapper mapper, final boolean validate) { BasicDBObject ret = new BasicDBObject(); final String[] parts = str.split(","); for (String s : parts) { s = s.trim(); // depends on control dependency: [for], data = [s] int dir = 1; if (s.startsWith("-")) { dir = -1; // depends on control dependency: [if], data = [none] s = s.substring(1).trim(); // depends on control dependency: [if], data = [none] } if (validate) { s = new PathTarget(mapper, clazz, s).translatedPath(); // depends on control dependency: [if], data = [none] } ret.put(s, dir); // depends on control dependency: [for], data = [s] } return ret; } }
public class class_name { protected void validateFunctionConfigurations(final Map<String, FunctionConfiguration> configMap) { info(""); info(VALIDATE_CONFIG); if (configMap.size() == 0) { info(VALIDATE_SKIP); } else { configMap.values().forEach(config -> config.validate()); info(VALIDATE_DONE); } } }
public class class_name { protected void validateFunctionConfigurations(final Map<String, FunctionConfiguration> configMap) { info(""); info(VALIDATE_CONFIG); if (configMap.size() == 0) { info(VALIDATE_SKIP); // depends on control dependency: [if], data = [none] } else { configMap.values().forEach(config -> config.validate()); // depends on control dependency: [if], data = [none] info(VALIDATE_DONE); // depends on control dependency: [if], data = [none] } } }
public class class_name { private void consumeNonExecutePrefix() { // fast forward through the leading whitespace nextNonWhitespace(true); pos--; if (pos + NON_EXECUTE_PREFIX.length > limit && !fillBuffer(NON_EXECUTE_PREFIX.length)) { return; } for (int i = 0; i < NON_EXECUTE_PREFIX.length; i++) { if (buffer[pos + i] != NON_EXECUTE_PREFIX[i]) { return; // not a security token! } } // we consumed a security token! pos += NON_EXECUTE_PREFIX.length; } }
public class class_name { private void consumeNonExecutePrefix() { // fast forward through the leading whitespace nextNonWhitespace(true); pos--; if (pos + NON_EXECUTE_PREFIX.length > limit && !fillBuffer(NON_EXECUTE_PREFIX.length)) { return; // depends on control dependency: [if], data = [none] } for (int i = 0; i < NON_EXECUTE_PREFIX.length; i++) { if (buffer[pos + i] != NON_EXECUTE_PREFIX[i]) { return; // not a security token! // depends on control dependency: [if], data = [none] } } // we consumed a security token! pos += NON_EXECUTE_PREFIX.length; } }
public class class_name { @Override public void setData(final Object data) { UIContext uic = UIContextHolder.getCurrent(); if (uic == null) { getComponentModel().setData(data); } else { Object sharedValue = ((BeanAndProviderBoundComponentModel) getDefaultModel()).getData(); if (getBeanProperty() != null) { sharedValue = getBeanValue(); } getOrCreateComponentModel().setData(data); setFlag(ComponentModel.USER_DATA_SET, !Util.equals(data, sharedValue)); } } }
public class class_name { @Override public void setData(final Object data) { UIContext uic = UIContextHolder.getCurrent(); if (uic == null) { getComponentModel().setData(data); // depends on control dependency: [if], data = [none] } else { Object sharedValue = ((BeanAndProviderBoundComponentModel) getDefaultModel()).getData(); if (getBeanProperty() != null) { sharedValue = getBeanValue(); // depends on control dependency: [if], data = [none] } getOrCreateComponentModel().setData(data); // depends on control dependency: [if], data = [none] setFlag(ComponentModel.USER_DATA_SET, !Util.equals(data, sharedValue)); // depends on control dependency: [if], data = [none] } } }
public class class_name { private void setRunLevel(int level) { if (m_instance != null) { if (m_instance.m_runLevel >= OpenCms.RUNLEVEL_1_CORE_OBJECT) { // otherwise the log is not available if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info( Messages.get().getBundle().key( Messages.INIT_RUNLEVEL_CHANGE_2, new Integer(m_instance.m_runLevel), new Integer(level))); } } m_instance.m_runLevel = level; } } }
public class class_name { private void setRunLevel(int level) { if (m_instance != null) { if (m_instance.m_runLevel >= OpenCms.RUNLEVEL_1_CORE_OBJECT) { // otherwise the log is not available if (CmsLog.INIT.isInfoEnabled()) { CmsLog.INIT.info( Messages.get().getBundle().key( Messages.INIT_RUNLEVEL_CHANGE_2, new Integer(m_instance.m_runLevel), new Integer(level))); // depends on control dependency: [if], data = [none] } } m_instance.m_runLevel = level; // depends on control dependency: [if], data = [none] } } }
public class class_name { public OClass getLinkedClass() { acquireSchemaReadLock(); try { if (linkedClass == null && linkedClassName != null) linkedClass = owner.owner.getClass(linkedClassName); return linkedClass; } finally { releaseSchemaReadLock(); } } }
public class class_name { public OClass getLinkedClass() { acquireSchemaReadLock(); try { if (linkedClass == null && linkedClassName != null) linkedClass = owner.owner.getClass(linkedClassName); return linkedClass; // depends on control dependency: [try], data = [none] } finally { releaseSchemaReadLock(); } } }
public class class_name { public static ExecutableElement getMethod(TypeElement typeElement, String name, TypeMirror... parameters) { List<ExecutableElement> allMethods = getAllMethods(typeElement, name, parameters); if (allMethods.isEmpty()) { return null; } else { Collections.sort(allMethods, new SpecificMethodComparator()); return allMethods.get(0); } } }
public class class_name { public static ExecutableElement getMethod(TypeElement typeElement, String name, TypeMirror... parameters) { List<ExecutableElement> allMethods = getAllMethods(typeElement, name, parameters); if (allMethods.isEmpty()) { return null; // depends on control dependency: [if], data = [none] } else { Collections.sort(allMethods, new SpecificMethodComparator()); // depends on control dependency: [if], data = [none] return allMethods.get(0); // depends on control dependency: [if], data = [none] } } }
public class class_name { Symbol findImmediateMemberType(Env<AttrContext> env, Type site, Name name, TypeSymbol c) { Scope.Entry e = c.members().lookup(name); while (e.scope != null) { if (e.sym.kind == TYP) { return isAccessible(env, site, e.sym) ? e.sym : new AccessError(env, site, e.sym); } e = e.next(); } return typeNotFound; } }
public class class_name { Symbol findImmediateMemberType(Env<AttrContext> env, Type site, Name name, TypeSymbol c) { Scope.Entry e = c.members().lookup(name); while (e.scope != null) { if (e.sym.kind == TYP) { return isAccessible(env, site, e.sym) ? e.sym : new AccessError(env, site, e.sym); // depends on control dependency: [if], data = [none] } e = e.next(); // depends on control dependency: [while], data = [none] } return typeNotFound; } }
public class class_name { public boolean containsKey(Object key) { EntryImpl<K, V> entry = _entries[keyHash(key) & _mask]; while (entry != null) { if (key.equals(entry._key)) { return true; } entry = entry._next; } return false; } }
public class class_name { public boolean containsKey(Object key) { EntryImpl<K, V> entry = _entries[keyHash(key) & _mask]; while (entry != null) { if (key.equals(entry._key)) { return true; } // depends on control dependency: [if], data = [none] entry = entry._next; // depends on control dependency: [while], data = [none] } return false; } }
public class class_name { @Override public void visitLabel(Label label) { super.visitLabel(label); if (waitingForSuper) { // Get what should be the shape of the stack in the handler. // Not all labels are branch targets so only deal with targets if (branchTargets.containsKey(label)) { currentStack = branchTargets.get(label); } } else { pendingExceptionHandlerTypeName = handlers.get(label); } } }
public class class_name { @Override public void visitLabel(Label label) { super.visitLabel(label); if (waitingForSuper) { // Get what should be the shape of the stack in the handler. // Not all labels are branch targets so only deal with targets if (branchTargets.containsKey(label)) { currentStack = branchTargets.get(label); // depends on control dependency: [if], data = [none] } } else { pendingExceptionHandlerTypeName = handlers.get(label); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void marshall(RetrieveTapeRecoveryPointRequest retrieveTapeRecoveryPointRequest, ProtocolMarshaller protocolMarshaller) { if (retrieveTapeRecoveryPointRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(retrieveTapeRecoveryPointRequest.getTapeARN(), TAPEARN_BINDING); protocolMarshaller.marshall(retrieveTapeRecoveryPointRequest.getGatewayARN(), GATEWAYARN_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(RetrieveTapeRecoveryPointRequest retrieveTapeRecoveryPointRequest, ProtocolMarshaller protocolMarshaller) { if (retrieveTapeRecoveryPointRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(retrieveTapeRecoveryPointRequest.getTapeARN(), TAPEARN_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(retrieveTapeRecoveryPointRequest.getGatewayARN(), GATEWAYARN_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 void reload() { m_table.init(); if (!CmsStringUtil.isEmptyOrWhitespaceOnly(m_resourcetypeTableFilter.getValue())) { m_table.filterTable(m_resourcetypeTableFilter.getValue()); } } }
public class class_name { public void reload() { m_table.init(); if (!CmsStringUtil.isEmptyOrWhitespaceOnly(m_resourcetypeTableFilter.getValue())) { m_table.filterTable(m_resourcetypeTableFilter.getValue()); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void addGlobalVarMaskRegex(VarMaskRegex varMaskRegex) { // blank values are forbidden if(StringUtils.isBlank(varMaskRegex.getRegex())) { LOGGER.fine("addGlobalVarMaskRegex NOT adding null regex"); return; } getGlobalVarMaskRegexesList().add(varMaskRegex); } }
public class class_name { public void addGlobalVarMaskRegex(VarMaskRegex varMaskRegex) { // blank values are forbidden if(StringUtils.isBlank(varMaskRegex.getRegex())) { LOGGER.fine("addGlobalVarMaskRegex NOT adding null regex"); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } getGlobalVarMaskRegexesList().add(varMaskRegex); } }
public class class_name { @Override public UpdateSketch rebuild() { final int lgNomLongs = getLgNomLongs(); final int preambleLongs = mem_.getByte(PREAMBLE_LONGS_BYTE) & 0X3F; if (getRetainedEntries(true) > (1 << lgNomLongs)) { quickSelectAndRebuild(mem_, preambleLongs, lgNomLongs); } return this; } }
public class class_name { @Override public UpdateSketch rebuild() { final int lgNomLongs = getLgNomLongs(); final int preambleLongs = mem_.getByte(PREAMBLE_LONGS_BYTE) & 0X3F; if (getRetainedEntries(true) > (1 << lgNomLongs)) { quickSelectAndRebuild(mem_, preambleLongs, lgNomLongs); // depends on control dependency: [if], data = [none] } return this; } }
public class class_name { private int bestSurroundingSet(int index, int length, int... valid) { int option1 = set[index - 1]; if (index + 1 < length) { // we have two options to check int option2 = set[index + 1]; if (contains(valid, option1) && contains(valid, option2)) { return Math.min(option1, option2); } else if (contains(valid, option1)) { return option1; } else if (contains(valid, option2)) { return option2; } else { return valid[0]; } } else { // we only have one option to check if (contains(valid, option1)) { return option1; } else { return valid[0]; } } } }
public class class_name { private int bestSurroundingSet(int index, int length, int... valid) { int option1 = set[index - 1]; if (index + 1 < length) { // we have two options to check int option2 = set[index + 1]; if (contains(valid, option1) && contains(valid, option2)) { return Math.min(option1, option2); // depends on control dependency: [if], data = [none] } else if (contains(valid, option1)) { return option1; // depends on control dependency: [if], data = [none] } else if (contains(valid, option2)) { return option2; // depends on control dependency: [if], data = [none] } else { return valid[0]; // depends on control dependency: [if], data = [none] } } else { // we only have one option to check if (contains(valid, option1)) { return option1; // depends on control dependency: [if], data = [none] } else { return valid[0]; // depends on control dependency: [if], data = [none] } } } }
public class class_name { public Set<TZID> resolve(Locale country) { Set<TZID> ids = WinZoneProviderSPI.NAME_BASED_MAP.get(this.name).get(FormatUtils.getRegion(country)); if (ids == null) { return Collections.emptySet(); } else { return Collections.unmodifiableSet(ids); } } }
public class class_name { public Set<TZID> resolve(Locale country) { Set<TZID> ids = WinZoneProviderSPI.NAME_BASED_MAP.get(this.name).get(FormatUtils.getRegion(country)); if (ids == null) { return Collections.emptySet(); // depends on control dependency: [if], data = [none] } else { return Collections.unmodifiableSet(ids); // depends on control dependency: [if], data = [(ids] } } }
public class class_name { public EClass getIfcEnergyProperties() { if (ifcEnergyPropertiesEClass == null) { ifcEnergyPropertiesEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(207); } return ifcEnergyPropertiesEClass; } }
public class class_name { public EClass getIfcEnergyProperties() { if (ifcEnergyPropertiesEClass == null) { ifcEnergyPropertiesEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(207); // depends on control dependency: [if], data = [none] } return ifcEnergyPropertiesEClass; } }
public class class_name { @Override public final void stop() { // Trying to stop() from FAILED is valid, but may not work boolean failed; synchronized (this) { try { while (state == ComponentStatus.STOPPING) { wait(); } if (!state.stopAllowed()) { getLog().debugf("Ignoring call to stop() as current state is %s", state); return; } failed = state == ComponentStatus.FAILED; state = ComponentStatus.STOPPING; } catch (InterruptedException e) { throw new CacheException("Interrupted waiting for the component registry to stop"); } } preStop(); try { internalStop(); postStop(); } catch (Throwable t) { if (failed) { getLog().failedToCallStopAfterFailure(t); } else { handleLifecycleTransitionFailure(t); } } finally { synchronized (this) { state = ComponentStatus.TERMINATED; } } } }
public class class_name { @Override public final void stop() { // Trying to stop() from FAILED is valid, but may not work boolean failed; synchronized (this) { try { while (state == ComponentStatus.STOPPING) { wait(); // depends on control dependency: [while], data = [none] } if (!state.stopAllowed()) { getLog().debugf("Ignoring call to stop() as current state is %s", state); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } failed = state == ComponentStatus.FAILED; // depends on control dependency: [try], data = [none] state = ComponentStatus.STOPPING; // depends on control dependency: [try], data = [none] } catch (InterruptedException e) { throw new CacheException("Interrupted waiting for the component registry to stop"); } // depends on control dependency: [catch], data = [none] } preStop(); try { internalStop(); // depends on control dependency: [try], data = [none] postStop(); // depends on control dependency: [try], data = [none] } catch (Throwable t) { if (failed) { getLog().failedToCallStopAfterFailure(t); // depends on control dependency: [if], data = [none] } else { handleLifecycleTransitionFailure(t); // depends on control dependency: [if], data = [none] } } finally { // depends on control dependency: [catch], data = [none] synchronized (this) { state = ComponentStatus.TERMINATED; } } } }
public class class_name { public void save(String modelFile, Set<Map.Entry<String, Integer>> featureIdSet, final double ratio, boolean text) throws IOException { float[] parameter = this.parameter; this.compress(ratio, 1e-3f); DataOutputStream out = new DataOutputStream(new BufferedOutputStream(IOUtil.newOutputStream(modelFile))); save(out); out.close(); if (text) { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(IOUtil.newOutputStream(modelFile + ".txt"), "UTF-8")); TagSet tagSet = featureMap.tagSet; for (Map.Entry<String, Integer> entry : featureIdSet) { bw.write(entry.getKey()); if (featureIdSet.size() == parameter.length) { bw.write("\t"); bw.write(String.valueOf(parameter[entry.getValue()])); } else { for (int i = 0; i < tagSet.size(); ++i) { bw.write("\t"); bw.write(String.valueOf(parameter[entry.getValue() * tagSet.size() + i])); } } bw.newLine(); } bw.close(); } } }
public class class_name { public void save(String modelFile, Set<Map.Entry<String, Integer>> featureIdSet, final double ratio, boolean text) throws IOException { float[] parameter = this.parameter; this.compress(ratio, 1e-3f); DataOutputStream out = new DataOutputStream(new BufferedOutputStream(IOUtil.newOutputStream(modelFile))); save(out); out.close(); if (text) { BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(IOUtil.newOutputStream(modelFile + ".txt"), "UTF-8")); TagSet tagSet = featureMap.tagSet; for (Map.Entry<String, Integer> entry : featureIdSet) { bw.write(entry.getKey()); // depends on control dependency: [for], data = [entry] if (featureIdSet.size() == parameter.length) { bw.write("\t"); // depends on control dependency: [if], data = [none] bw.write(String.valueOf(parameter[entry.getValue()])); // depends on control dependency: [if], data = [none] } else { for (int i = 0; i < tagSet.size(); ++i) { bw.write("\t"); // depends on control dependency: [for], data = [none] bw.write(String.valueOf(parameter[entry.getValue() * tagSet.size() + i])); // depends on control dependency: [for], data = [i] } } bw.newLine(); // depends on control dependency: [for], data = [none] } bw.close(); } } }
public class class_name { private X509Certificate[] getPeerCertificates() { X509Certificate[] rc = null; SSLContext ssl = this.connection.getSSLContext(); if (null != ssl && (ssl.getNeedClientAuth() || ssl.getWantClientAuth())) { try { Object[] objs = ssl.getSession().getPeerCertificates(); if (null != objs) { rc = (X509Certificate[]) objs; } } catch (Throwable t) { FFDCFilter.processException(t, getClass().getName(), "peercerts", new Object[] { this, ssl }); if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) { Tr.event(tc, "Error getting peer certs; " + t); } } } if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { if (null == rc) { Tr.debug(tc, "getPeerCertificates: none"); } else { Tr.debug(tc, "getPeerCertificates: " + rc.length); } } return rc; } }
public class class_name { private X509Certificate[] getPeerCertificates() { X509Certificate[] rc = null; SSLContext ssl = this.connection.getSSLContext(); if (null != ssl && (ssl.getNeedClientAuth() || ssl.getWantClientAuth())) { try { Object[] objs = ssl.getSession().getPeerCertificates(); if (null != objs) { rc = (X509Certificate[]) objs; // depends on control dependency: [if], data = [none] } } catch (Throwable t) { FFDCFilter.processException(t, getClass().getName(), "peercerts", new Object[] { this, ssl }); if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) { Tr.event(tc, "Error getting peer certs; " + t); // depends on control dependency: [if], data = [none] } } // depends on control dependency: [catch], data = [none] } if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { if (null == rc) { Tr.debug(tc, "getPeerCertificates: none"); // depends on control dependency: [if], data = [none] } else { Tr.debug(tc, "getPeerCertificates: " + rc.length); // depends on control dependency: [if], data = [none] } } return rc; } }
public class class_name { protected static Set<Class<? extends Model>> getModelsForDb(String dbName) throws ClassNotFoundException { Set<String> modelClassNames = getModelMap().get(dbName); Set<Class<? extends Model>> classSet = new HashSet<>(); if (modelClassNames != null) { for (String className : modelClassNames) { Class modelClass = Class.forName(className); if (!modelClass.equals(Model.class) && Model.class.isAssignableFrom(modelClass)) { String realDbName = MetaModel.getDbName(modelClass); if (realDbName.equals(dbName)) { classSet.add(modelClass); } else { throw new InitException("invalid database association for the " + className + ". Real database name: " + realDbName); } } else { throw new InitException("invalid class in the models list: " + className); } } } if (classSet.isEmpty()){ throw new InitException("you are trying to work with models, but no models are found. Maybe you have " + "no models in project, or you did not instrument the models. It is expected that you have " + "a file activejdbc_models.properties on classpath"); } return classSet; } }
public class class_name { protected static Set<Class<? extends Model>> getModelsForDb(String dbName) throws ClassNotFoundException { Set<String> modelClassNames = getModelMap().get(dbName); Set<Class<? extends Model>> classSet = new HashSet<>(); if (modelClassNames != null) { for (String className : modelClassNames) { Class modelClass = Class.forName(className); if (!modelClass.equals(Model.class) && Model.class.isAssignableFrom(modelClass)) { String realDbName = MetaModel.getDbName(modelClass); if (realDbName.equals(dbName)) { classSet.add(modelClass); // depends on control dependency: [if], data = [none] } else { throw new InitException("invalid database association for the " + className + ". Real database name: " + realDbName); } } else { throw new InitException("invalid class in the models list: " + className); } } } if (classSet.isEmpty()){ throw new InitException("you are trying to work with models, but no models are found. Maybe you have " + "no models in project, or you did not instrument the models. It is expected that you have " + "a file activejdbc_models.properties on classpath"); } return classSet; } }
public class class_name { public final void mRULE_SL_COMMENT() throws RecognitionException { try { int _type = RULE_SL_COMMENT; int _channel = DEFAULT_TOKEN_CHANNEL; // InternalPureXbase.g:6891:17: ( '//' (~ ( ( '\\n' | '\\r' ) ) )* ( ( '\\r' )? '\\n' )? ) // InternalPureXbase.g:6891:19: '//' (~ ( ( '\\n' | '\\r' ) ) )* ( ( '\\r' )? '\\n' )? { match("//"); // InternalPureXbase.g:6891:24: (~ ( ( '\\n' | '\\r' ) ) )* loop17: do { int alt17=2; int LA17_0 = input.LA(1); if ( ((LA17_0>='\u0000' && LA17_0<='\t')||(LA17_0>='\u000B' && LA17_0<='\f')||(LA17_0>='\u000E' && LA17_0<='\uFFFF')) ) { alt17=1; } switch (alt17) { case 1 : // InternalPureXbase.g:6891:24: ~ ( ( '\\n' | '\\r' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='\t')||(input.LA(1)>='\u000B' && input.LA(1)<='\f')||(input.LA(1)>='\u000E' && input.LA(1)<='\uFFFF') ) { input.consume(); } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); throw mse;} } break; default : break loop17; } } while (true); // InternalPureXbase.g:6891:40: ( ( '\\r' )? '\\n' )? int alt19=2; int LA19_0 = input.LA(1); if ( (LA19_0=='\n'||LA19_0=='\r') ) { alt19=1; } switch (alt19) { case 1 : // InternalPureXbase.g:6891:41: ( '\\r' )? '\\n' { // InternalPureXbase.g:6891:41: ( '\\r' )? int alt18=2; int LA18_0 = input.LA(1); if ( (LA18_0=='\r') ) { alt18=1; } switch (alt18) { case 1 : // InternalPureXbase.g:6891:41: '\\r' { match('\r'); } break; } match('\n'); } break; } } state.type = _type; state.channel = _channel; } finally { } } }
public class class_name { public final void mRULE_SL_COMMENT() throws RecognitionException { try { int _type = RULE_SL_COMMENT; int _channel = DEFAULT_TOKEN_CHANNEL; // InternalPureXbase.g:6891:17: ( '//' (~ ( ( '\\n' | '\\r' ) ) )* ( ( '\\r' )? '\\n' )? ) // InternalPureXbase.g:6891:19: '//' (~ ( ( '\\n' | '\\r' ) ) )* ( ( '\\r' )? '\\n' )? { match("//"); // InternalPureXbase.g:6891:24: (~ ( ( '\\n' | '\\r' ) ) )* loop17: do { int alt17=2; int LA17_0 = input.LA(1); if ( ((LA17_0>='\u0000' && LA17_0<='\t')||(LA17_0>='\u000B' && LA17_0<='\f')||(LA17_0>='\u000E' && LA17_0<='\uFFFF')) ) { alt17=1; // depends on control dependency: [if], data = [none] } switch (alt17) { case 1 : // InternalPureXbase.g:6891:24: ~ ( ( '\\n' | '\\r' ) ) { if ( (input.LA(1)>='\u0000' && input.LA(1)<='\t')||(input.LA(1)>='\u000B' && input.LA(1)<='\f')||(input.LA(1)>='\u000E' && input.LA(1)<='\uFFFF') ) { input.consume(); // depends on control dependency: [if], data = [none] } else { MismatchedSetException mse = new MismatchedSetException(null,input); recover(mse); // depends on control dependency: [if], data = [none] throw mse;} } break; default : break loop17; } } while (true); // InternalPureXbase.g:6891:40: ( ( '\\r' )? '\\n' )? int alt19=2; int LA19_0 = input.LA(1); if ( (LA19_0=='\n'||LA19_0=='\r') ) { alt19=1; // depends on control dependency: [if], data = [none] } switch (alt19) { case 1 : // InternalPureXbase.g:6891:41: ( '\\r' )? '\\n' { // InternalPureXbase.g:6891:41: ( '\\r' )? int alt18=2; int LA18_0 = input.LA(1); if ( (LA18_0=='\r') ) { alt18=1; // depends on control dependency: [if], data = [none] } switch (alt18) { case 1 : // InternalPureXbase.g:6891:41: '\\r' { match('\r'); } break; } match('\n'); } break; } } state.type = _type; state.channel = _channel; } finally { } } }
public class class_name { private Object convertToJadeModelValue(Object eval) { if(eval instanceof Double){ String s = String.valueOf(eval); if(s.endsWith(".0")){ return Integer.valueOf(s.substring(0,s.length()-2)); } } // eval = convert(eval); // if(eval instanceof NativeArray){ // NativeArray n = (NativeArray) eval; // for(int i=0;i<n.getLength();i++){ // n.get(0); // } // } return eval; } }
public class class_name { private Object convertToJadeModelValue(Object eval) { if(eval instanceof Double){ String s = String.valueOf(eval); if(s.endsWith(".0")){ return Integer.valueOf(s.substring(0,s.length()-2)); // depends on control dependency: [if], data = [none] } } // eval = convert(eval); // if(eval instanceof NativeArray){ // NativeArray n = (NativeArray) eval; // for(int i=0;i<n.getLength();i++){ // n.get(0); // } // } return eval; } }
public class class_name { public Service withEdges(Edge... edges) { if (this.edges == null) { setEdges(new java.util.ArrayList<Edge>(edges.length)); } for (Edge ele : edges) { this.edges.add(ele); } return this; } }
public class class_name { public Service withEdges(Edge... edges) { if (this.edges == null) { setEdges(new java.util.ArrayList<Edge>(edges.length)); // depends on control dependency: [if], data = [none] } for (Edge ele : edges) { this.edges.add(ele); // depends on control dependency: [for], data = [ele] } return this; } }
public class class_name { public void setPicker(GVRPicker picker) { if (mPicker != null) { mPicker.setEnable(false); } mPicker = picker; } }
public class class_name { public void setPicker(GVRPicker picker) { if (mPicker != null) { mPicker.setEnable(false); // depends on control dependency: [if], data = [none] } mPicker = picker; } }
public class class_name { public void downloadByteData(ResponseDownloadResource resource, HttpServletResponse response) { final byte[] byteData = resource.getByteData(); if (byteData == null) { String msg = "Either byte data or input stream is required: " + resource; throw new IllegalArgumentException(msg); } try { final OutputStream out = response.getOutputStream(); try { out.write(byteData); } finally { closeDownloadStream(out); } } catch (RuntimeException e) { throw new ResponseDownloadFailureException("Failed to download the byte data: " + resource, e); } catch (IOException e) { handleDownloadIOException(resource, e); } } }
public class class_name { public void downloadByteData(ResponseDownloadResource resource, HttpServletResponse response) { final byte[] byteData = resource.getByteData(); if (byteData == null) { String msg = "Either byte data or input stream is required: " + resource; throw new IllegalArgumentException(msg); } try { final OutputStream out = response.getOutputStream(); try { out.write(byteData); // depends on control dependency: [try], data = [none] } finally { closeDownloadStream(out); } } catch (RuntimeException e) { throw new ResponseDownloadFailureException("Failed to download the byte data: " + resource, e); } catch (IOException e) { // depends on control dependency: [catch], data = [none] handleDownloadIOException(resource, e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static String padRight(String string, int size, char padding) { if(string == null || size <= string.length()) { return string; } StringBuilder sb = new StringBuilder(); sb.append(string); while (sb.length() < size) { sb.append(padding); } return sb.toString(); } }
public class class_name { public static String padRight(String string, int size, char padding) { if(string == null || size <= string.length()) { return string; // depends on control dependency: [if], data = [none] } StringBuilder sb = new StringBuilder(); sb.append(string); while (sb.length() < size) { sb.append(padding); // depends on control dependency: [while], data = [none] } return sb.toString(); } }
public class class_name { public static synchronized void initializeEnvironment() { if (_isStaticInit) return; _isStaticInit = true; ClassLoader systemLoader = ClassLoader.getSystemClassLoader(); Thread thread = Thread.currentThread(); ClassLoader oldLoader = thread.getContextClassLoader(); try { thread.setContextClassLoader(systemLoader); if ("1.8.".compareTo(System.getProperty("java.runtime.version")) > 0) throw new ConfigException("Baratine requires JDK 1.8 or later"); // #2281 // PolicyImpl.init(); //EnvironmentStream.setStdout(System.out); //EnvironmentStream.setStderr(System.err); /* try { Vfs.initJNI(); } catch (Throwable e) { } */ Properties props = System.getProperties(); ClassLoader envClassLoader = EnvironmentClassLoader.class.getClassLoader(); /* boolean isGlobalLoadableJndi = false; try { Class<?> cl = Class.forName("com.caucho.v5.naming.InitialContextFactoryImpl", false, systemLoader); isGlobalLoadableJndi = (cl != null); } catch (Exception e) { log().log(Level.FINER, e.toString(), e); } // #3486 String namingPkgs = (String) props.get("java.naming.factory.url.pkgs"); if (namingPkgs == null) namingPkgs = "com.caucho.v5.naming"; else namingPkgs = namingPkgs + ":" + "com.caucho.v5.naming"; props.put("java.naming.factory.url.pkgs", namingPkgs); if (isGlobalLoadableJndi) { // These properties require the server to be at the system loader if (props.get("java.naming.factory.initial") == null) { props.put("java.naming.factory.initial", "com.caucho.v5.naming.InitialContextFactoryImpl"); } } */ /* boolean isGlobalLoadableJmx = false; try { Class<?> cl = Class.forName("com.caucho.v5.jmx.MBeanServerBuilderImpl", false, systemLoader); isGlobalLoadableJmx = (cl != null); } catch (Exception e) { log().log(Level.FINER, e.toString(), e); } if (isGlobalLoadableJmx) { // props.put("java.naming.factory.url.pkgs", "com.caucho.naming"); EnvironmentProperties.enableEnvironmentSystemProperties(true); String oldBuilder = props.getProperty("javax.management.builder.initial"); if (oldBuilder == null) { oldBuilder = "com.caucho.v5.jmx.MBeanServerBuilderImpl"; props.put("javax.management.builder.initial", oldBuilder); } Object value = ManagementFactory.getPlatformMBeanServer(); } */ } catch (Throwable e) { log().log(Level.FINE, e.toString(), e); } finally { thread.setContextClassLoader(oldLoader); _isInitComplete = true; } } }
public class class_name { public static synchronized void initializeEnvironment() { if (_isStaticInit) return; _isStaticInit = true; ClassLoader systemLoader = ClassLoader.getSystemClassLoader(); Thread thread = Thread.currentThread(); ClassLoader oldLoader = thread.getContextClassLoader(); try { thread.setContextClassLoader(systemLoader); // depends on control dependency: [try], data = [none] if ("1.8.".compareTo(System.getProperty("java.runtime.version")) > 0) throw new ConfigException("Baratine requires JDK 1.8 or later"); // #2281 // PolicyImpl.init(); //EnvironmentStream.setStdout(System.out); //EnvironmentStream.setStderr(System.err); /* try { Vfs.initJNI(); } catch (Throwable e) { } */ Properties props = System.getProperties(); ClassLoader envClassLoader = EnvironmentClassLoader.class.getClassLoader(); /* boolean isGlobalLoadableJndi = false; try { Class<?> cl = Class.forName("com.caucho.v5.naming.InitialContextFactoryImpl", false, systemLoader); isGlobalLoadableJndi = (cl != null); } catch (Exception e) { log().log(Level.FINER, e.toString(), e); } // #3486 String namingPkgs = (String) props.get("java.naming.factory.url.pkgs"); if (namingPkgs == null) namingPkgs = "com.caucho.v5.naming"; else namingPkgs = namingPkgs + ":" + "com.caucho.v5.naming"; props.put("java.naming.factory.url.pkgs", namingPkgs); if (isGlobalLoadableJndi) { // These properties require the server to be at the system loader if (props.get("java.naming.factory.initial") == null) { props.put("java.naming.factory.initial", "com.caucho.v5.naming.InitialContextFactoryImpl"); } } */ /* boolean isGlobalLoadableJmx = false; try { Class<?> cl = Class.forName("com.caucho.v5.jmx.MBeanServerBuilderImpl", false, systemLoader); isGlobalLoadableJmx = (cl != null); } catch (Exception e) { log().log(Level.FINER, e.toString(), e); } if (isGlobalLoadableJmx) { // props.put("java.naming.factory.url.pkgs", "com.caucho.naming"); EnvironmentProperties.enableEnvironmentSystemProperties(true); String oldBuilder = props.getProperty("javax.management.builder.initial"); if (oldBuilder == null) { oldBuilder = "com.caucho.v5.jmx.MBeanServerBuilderImpl"; props.put("javax.management.builder.initial", oldBuilder); } Object value = ManagementFactory.getPlatformMBeanServer(); } */ } catch (Throwable e) { log().log(Level.FINE, e.toString(), e); } finally { // depends on control dependency: [catch], data = [none] thread.setContextClassLoader(oldLoader); _isInitComplete = true; } } }
public class class_name { @Override public boolean isUserInRole(String role) { boolean inRole = false; Authentication authentication = getAuthentication(); if (authentication != null) { Collection<? extends GrantedAuthority> authorities = authentication .getAuthorities(); for (GrantedAuthority authority : authorities) { if (role.equals(authority.getAuthority())) { inRole = true; break; } } } return inRole; } }
public class class_name { @Override public boolean isUserInRole(String role) { boolean inRole = false; Authentication authentication = getAuthentication(); if (authentication != null) { Collection<? extends GrantedAuthority> authorities = authentication .getAuthorities(); // depends on control dependency: [if], data = [none] for (GrantedAuthority authority : authorities) { if (role.equals(authority.getAuthority())) { inRole = true; // depends on control dependency: [if], data = [none] break; } } } return inRole; } }
public class class_name { public void doNewRecord(boolean bDisplayOption) { super.doNewRecord(bDisplayOption); try { if (this.getOwner().isOpen()) // Don't do first time! { boolean bOldEnableState = this.isEnabledListener(); this.setEnabledListener(false); // Just in case AddNew decides to call this this.getOwner().close(); if (this.getOwner().hasNext()) // records yet? this.getOwner().next(); else this.getOwner().addNew(); // Make a new one this.setEnabledListener(bOldEnableState); } } catch (DBException ex) { if (ex.getErrorCode() == DBConstants.FILE_NOT_FOUND) if ((this.getOwner().getOpenMode() & DBConstants.OPEN_DONT_CREATE) == DBConstants.OPEN_DONT_CREATE) return; // Special case - they didn't want the table created if not found ex.printStackTrace(); // Never } } }
public class class_name { public void doNewRecord(boolean bDisplayOption) { super.doNewRecord(bDisplayOption); try { if (this.getOwner().isOpen()) // Don't do first time! { boolean bOldEnableState = this.isEnabledListener(); this.setEnabledListener(false); // Just in case AddNew decides to call this // depends on control dependency: [if], data = [none] this.getOwner().close(); // depends on control dependency: [if], data = [none] if (this.getOwner().hasNext()) // records yet? this.getOwner().next(); else this.getOwner().addNew(); // Make a new one this.setEnabledListener(bOldEnableState); // depends on control dependency: [if], data = [none] } } catch (DBException ex) { if (ex.getErrorCode() == DBConstants.FILE_NOT_FOUND) if ((this.getOwner().getOpenMode() & DBConstants.OPEN_DONT_CREATE) == DBConstants.OPEN_DONT_CREATE) return; // Special case - they didn't want the table created if not found ex.printStackTrace(); // Never } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static void open(File file) { final Desktop dsktop = getDsktop(); try { dsktop.open(file); } catch (IOException e) { throw new IORuntimeException(e); } } }
public class class_name { public static void open(File file) { final Desktop dsktop = getDsktop(); try { dsktop.open(file); // depends on control dependency: [try], data = [none] } catch (IOException e) { throw new IORuntimeException(e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void setCurrentCounter(int currElement) { currElement -= offset; for (int ii = 0; ii < rank; ii++) { // general rank if (shape[ii] < 0) { current[ii] = -1; break; } current[ii] = currElement / stride[ii]; currElement -= current[ii] * stride[ii]; } set(current); // transfer to subclass fields } }
public class class_name { public void setCurrentCounter(int currElement) { currElement -= offset; for (int ii = 0; ii < rank; ii++) { // general rank if (shape[ii] < 0) { current[ii] = -1; // depends on control dependency: [if], data = [none] break; } current[ii] = currElement / stride[ii]; // depends on control dependency: [for], data = [ii] currElement -= current[ii] * stride[ii]; // depends on control dependency: [for], data = [ii] } set(current); // transfer to subclass fields } }
public class class_name { @SuppressWarnings({"unused"}) @UsedByGeneratedCode public static List<String> internListOf(Object... objects) { if (objects == null || objects.length == 0) { return Collections.emptyList(); } Integer hash = Arrays.hashCode(objects); return INTERN_LIST_POOL.computeIfAbsent(hash, integer -> StringUtils.internListOf(objects)); } }
public class class_name { @SuppressWarnings({"unused"}) @UsedByGeneratedCode public static List<String> internListOf(Object... objects) { if (objects == null || objects.length == 0) { return Collections.emptyList(); // depends on control dependency: [if], data = [none] } Integer hash = Arrays.hashCode(objects); return INTERN_LIST_POOL.computeIfAbsent(hash, integer -> StringUtils.internListOf(objects)); } }
public class class_name { public void close() { super.clear(); if (indexMap != null){ indexMap.clear(); indexMap = null; } if (this.indexStore != null){ getIndexStore().close(); this.indexStore = null ; } if (this.cacheStore != null){ getCacheStore().close(); this.cacheStore = null ; } } }
public class class_name { public void close() { super.clear(); if (indexMap != null){ indexMap.clear(); // depends on control dependency: [if], data = [none] indexMap = null; // depends on control dependency: [if], data = [none] } if (this.indexStore != null){ getIndexStore().close(); // depends on control dependency: [if], data = [none] this.indexStore = null ; // depends on control dependency: [if], data = [none] } if (this.cacheStore != null){ getCacheStore().close(); // depends on control dependency: [if], data = [none] this.cacheStore = null ; // depends on control dependency: [if], data = [none] } } }
public class class_name { public void start( final Callback<? super TcpSocketServer> onStart, final Callback<? super Exception> onError ) throws IllegalStateException { if(isClosed()) throw new IllegalStateException("TcpSocketServer is closed"); synchronized(lock) { if(serverSocket != null) throw new IllegalStateException(); executors.getUnbounded().submit( new Runnable() { @Override public void run() { try { if(isClosed()) throw new SocketException("TcpSocketServer is closed"); final ServerSocket newServerSocket = new ServerSocket(port, backlog, bindAddr); synchronized(lock) { TcpSocketServer.this.serverSocket = newServerSocket; } // Handle incoming messages in a Thread, can try nio later executors.getUnbounded().submit( new Runnable() { @Override public void run() { try { while(true) { synchronized(lock) { // Check if closed if(newServerSocket!=TcpSocketServer.this.serverSocket) break; } Socket socket = newServerSocket.accept(); long connectTime = System.currentTimeMillis(); socket.setKeepAlive(KEEPALIVE); socket.setSoLinger(SOCKET_SO_LINGER_ENABLED, SOCKET_SO_LINGER_SECONDS); socket.setTcpNoDelay(TCP_NO_DELAY); CompressedDataInputStream in = new CompressedDataInputStream(socket.getInputStream()); CompressedDataOutputStream out = new CompressedDataOutputStream(socket.getOutputStream()); Identifier id = newIdentifier(); out.writeLong(id.getHi()); out.writeLong(id.getLo()); out.flush(); TcpSocket tcpSocket = new TcpSocket( TcpSocketServer.this, id, connectTime, socket, in, out ); addSocket(tcpSocket); } } catch(Exception exc) { if(!isClosed()) callOnError(exc); } finally { close(); } } } ); if(onStart!=null) onStart.call(TcpSocketServer.this); } catch(Exception exc) { if(onError!=null) onError.call(exc); } } } ); } } }
public class class_name { public void start( final Callback<? super TcpSocketServer> onStart, final Callback<? super Exception> onError ) throws IllegalStateException { if(isClosed()) throw new IllegalStateException("TcpSocketServer is closed"); synchronized(lock) { if(serverSocket != null) throw new IllegalStateException(); executors.getUnbounded().submit( new Runnable() { @Override public void run() { try { if(isClosed()) throw new SocketException("TcpSocketServer is closed"); final ServerSocket newServerSocket = new ServerSocket(port, backlog, bindAddr); synchronized(lock) { // depends on control dependency: [try], data = [none] TcpSocketServer.this.serverSocket = newServerSocket; } // Handle incoming messages in a Thread, can try nio later executors.getUnbounded().submit( new Runnable() { @Override public void run() { try { while(true) { synchronized(lock) { // depends on control dependency: [while], data = [none] // Check if closed if(newServerSocket!=TcpSocketServer.this.serverSocket) break; } Socket socket = newServerSocket.accept(); long connectTime = System.currentTimeMillis(); socket.setKeepAlive(KEEPALIVE); // depends on control dependency: [while], data = [none] socket.setSoLinger(SOCKET_SO_LINGER_ENABLED, SOCKET_SO_LINGER_SECONDS); // depends on control dependency: [while], data = [none] socket.setTcpNoDelay(TCP_NO_DELAY); // depends on control dependency: [while], data = [none] CompressedDataInputStream in = new CompressedDataInputStream(socket.getInputStream()); CompressedDataOutputStream out = new CompressedDataOutputStream(socket.getOutputStream()); Identifier id = newIdentifier(); out.writeLong(id.getHi()); // depends on control dependency: [while], data = [none] out.writeLong(id.getLo()); // depends on control dependency: [while], data = [none] out.flush(); // depends on control dependency: [while], data = [none] TcpSocket tcpSocket = new TcpSocket( TcpSocketServer.this, id, connectTime, socket, in, out ); addSocket(tcpSocket); // depends on control dependency: [while], data = [none] } } catch(Exception exc) { if(!isClosed()) callOnError(exc); } finally { // depends on control dependency: [catch], data = [none] close(); } } } ); // depends on control dependency: [try], data = [none] if(onStart!=null) onStart.call(TcpSocketServer.this); } catch(Exception exc) { if(onError!=null) onError.call(exc); } // depends on control dependency: [catch], data = [none] } } ); } } }
public class class_name { protected static Object[] mkAxioms(HashMap<IAtomicConceptOfLabel, String> hashConceptNumber, Map<INode, ArrayList<IAtomicConceptOfLabel>> nmtAcols, Map<String, IAtomicConceptOfLabel> sourceACoLs, Map<String, IAtomicConceptOfLabel> targetACoLs, IContextMapping<IAtomicConceptOfLabel> acolMapping, INode sourceNode, INode targetNode) { StringBuilder axioms = new StringBuilder(); Integer numberOfClauses = 0; // create DIMACS variables for all acols in the matching task createVariables(hashConceptNumber, nmtAcols, sourceACoLs, sourceNode); createVariables(hashConceptNumber, nmtAcols, targetACoLs, targetNode); ArrayList<IAtomicConceptOfLabel> sourceACols = nmtAcols.get(sourceNode); ArrayList<IAtomicConceptOfLabel> targetACols = nmtAcols.get(targetNode); if (null != sourceACols && null != targetACols) { for (IAtomicConceptOfLabel sourceACoL : sourceACols) { for (IAtomicConceptOfLabel targetACoL : targetACols) { char relation = acolMapping.getRelation(sourceACoL, targetACoL); if (IMappingElement.IDK != relation) { //get the numbers of DIMACS variables corresponding to ACoLs String sourceVarNumber = hashConceptNumber.get(sourceACoL); String targetVarNumber = hashConceptNumber.get(targetACoL); if (IMappingElement.LESS_GENERAL == relation) { String tmp = "-" + sourceVarNumber + " " + targetVarNumber + " 0\n"; //if not already present add to axioms if (-1 == axioms.indexOf(tmp)) { axioms.append(tmp); numberOfClauses++; } } else if (IMappingElement.MORE_GENERAL == relation) { String tmp = sourceVarNumber + " -" + targetVarNumber + " 0\n"; if (-1 == axioms.indexOf(tmp)) { axioms.append(tmp); numberOfClauses++; } } else if (IMappingElement.EQUIVALENCE == relation) { if (!sourceVarNumber.equals(targetVarNumber)) { //add clauses for less and more generality String tmp = "-" + sourceVarNumber + " " + targetVarNumber + " 0\n"; if (-1 == axioms.indexOf(tmp)) { axioms.append(tmp); numberOfClauses++; } tmp = sourceVarNumber + " -" + targetVarNumber + " 0\n"; if (-1 == axioms.indexOf(tmp)) { axioms.append(tmp); numberOfClauses++; } } } else if (IMappingElement.DISJOINT == relation) { String tmp = "-" + sourceVarNumber + " -" + targetVarNumber + " 0\n"; if (-1 == axioms.indexOf(tmp)) { axioms.append(tmp); numberOfClauses++; } } } } } } return new Object[]{axioms.toString(), numberOfClauses}; } }
public class class_name { protected static Object[] mkAxioms(HashMap<IAtomicConceptOfLabel, String> hashConceptNumber, Map<INode, ArrayList<IAtomicConceptOfLabel>> nmtAcols, Map<String, IAtomicConceptOfLabel> sourceACoLs, Map<String, IAtomicConceptOfLabel> targetACoLs, IContextMapping<IAtomicConceptOfLabel> acolMapping, INode sourceNode, INode targetNode) { StringBuilder axioms = new StringBuilder(); Integer numberOfClauses = 0; // create DIMACS variables for all acols in the matching task createVariables(hashConceptNumber, nmtAcols, sourceACoLs, sourceNode); createVariables(hashConceptNumber, nmtAcols, targetACoLs, targetNode); ArrayList<IAtomicConceptOfLabel> sourceACols = nmtAcols.get(sourceNode); ArrayList<IAtomicConceptOfLabel> targetACols = nmtAcols.get(targetNode); if (null != sourceACols && null != targetACols) { for (IAtomicConceptOfLabel sourceACoL : sourceACols) { for (IAtomicConceptOfLabel targetACoL : targetACols) { char relation = acolMapping.getRelation(sourceACoL, targetACoL); if (IMappingElement.IDK != relation) { //get the numbers of DIMACS variables corresponding to ACoLs String sourceVarNumber = hashConceptNumber.get(sourceACoL); String targetVarNumber = hashConceptNumber.get(targetACoL); if (IMappingElement.LESS_GENERAL == relation) { String tmp = "-" + sourceVarNumber + " " + targetVarNumber + " 0\n"; //if not already present add to axioms if (-1 == axioms.indexOf(tmp)) { axioms.append(tmp); // depends on control dependency: [if], data = [none] numberOfClauses++; // depends on control dependency: [if], data = [none] } } else if (IMappingElement.MORE_GENERAL == relation) { String tmp = sourceVarNumber + " -" + targetVarNumber + " 0\n"; if (-1 == axioms.indexOf(tmp)) { axioms.append(tmp); // depends on control dependency: [if], data = [none] numberOfClauses++; // depends on control dependency: [if], data = [none] } } else if (IMappingElement.EQUIVALENCE == relation) { if (!sourceVarNumber.equals(targetVarNumber)) { //add clauses for less and more generality String tmp = "-" + sourceVarNumber + " " + targetVarNumber + " 0\n"; if (-1 == axioms.indexOf(tmp)) { axioms.append(tmp); // depends on control dependency: [if], data = [none] numberOfClauses++; // depends on control dependency: [if], data = [none] } tmp = sourceVarNumber + " -" + targetVarNumber + " 0\n"; // depends on control dependency: [if], data = [none] if (-1 == axioms.indexOf(tmp)) { axioms.append(tmp); // depends on control dependency: [if], data = [none] numberOfClauses++; // depends on control dependency: [if], data = [none] } } } else if (IMappingElement.DISJOINT == relation) { String tmp = "-" + sourceVarNumber + " -" + targetVarNumber + " 0\n"; if (-1 == axioms.indexOf(tmp)) { axioms.append(tmp); // depends on control dependency: [if], data = [none] numberOfClauses++; // depends on control dependency: [if], data = [none] } } } } } } return new Object[]{axioms.toString(), numberOfClauses}; } }
public class class_name { public synchronized void notifyTaskCompletion(long jobId, int taskId, Object result) { Pair<Long, Integer> id = new Pair<>(jobId, taskId); TaskInfo.Builder taskInfo = mUnfinishedTasks.get(id); taskInfo.setStatus(Status.COMPLETED); try { taskInfo.setResult(ByteString.copyFrom(SerializationUtils.serialize(result))); } catch (IOException e) { // TODO(yupeng) better error handling LOG.warn("Failed to serialize {} : {}", result, e.getMessage()); LOG.debug("Exception: ", e); } finally { finishTask(id); LOG.info("Task {} for job {} completed.", taskId, jobId); } } }
public class class_name { public synchronized void notifyTaskCompletion(long jobId, int taskId, Object result) { Pair<Long, Integer> id = new Pair<>(jobId, taskId); TaskInfo.Builder taskInfo = mUnfinishedTasks.get(id); taskInfo.setStatus(Status.COMPLETED); try { taskInfo.setResult(ByteString.copyFrom(SerializationUtils.serialize(result))); // depends on control dependency: [try], data = [none] } catch (IOException e) { // TODO(yupeng) better error handling LOG.warn("Failed to serialize {} : {}", result, e.getMessage()); LOG.debug("Exception: ", e); } finally { // depends on control dependency: [catch], data = [none] finishTask(id); LOG.info("Task {} for job {} completed.", taskId, jobId); } } }
public class class_name { public WComponent getExpandedTreeNodeRenderer(final Class<? extends WComponent> rendererClass) { if (rendererClass == null) { return null; } // If we already have an additional renderer for this class, return it. // This is synchronized, as it updates the shared model using locking/unlocking, which is a bit dodgy. synchronized (expandedRenderers) { WComponent renderer = expandedRenderers.get(rendererClass); if (renderer != null) { return renderer; } // Not found, create a new instance of the given class renderer = new RendererWrapper(this, rendererClass, -1); expandedRenderers.put(rendererClass, renderer); setLocked(false); add(renderer); setLocked(true); return renderer; } } }
public class class_name { public WComponent getExpandedTreeNodeRenderer(final Class<? extends WComponent> rendererClass) { if (rendererClass == null) { return null; // depends on control dependency: [if], data = [none] } // If we already have an additional renderer for this class, return it. // This is synchronized, as it updates the shared model using locking/unlocking, which is a bit dodgy. synchronized (expandedRenderers) { WComponent renderer = expandedRenderers.get(rendererClass); if (renderer != null) { return renderer; // depends on control dependency: [if], data = [none] } // Not found, create a new instance of the given class renderer = new RendererWrapper(this, rendererClass, -1); expandedRenderers.put(rendererClass, renderer); setLocked(false); add(renderer); setLocked(true); return renderer; } } }
public class class_name { @RequestMapping(method = RequestMethod.POST, params = "action=moveTab") public ModelAndView moveTab( HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "sourceID") String sourceId, @RequestParam String method, @RequestParam(value = "elementID") String destinationId) throws IOException { IUserInstance ui = userInstanceManager.getUserInstance(request); UserPreferencesManager upm = (UserPreferencesManager) ui.getPreferencesManager(); IUserLayoutManager ulm = upm.getUserLayoutManager(); final Locale locale = RequestContextUtils.getLocale(request); // If we're moving this element before another one, we need // to know what the target is. If there's no target, just // assume we're moving it to the very end of the list. String siblingId = null; if ("insertBefore".equals(method)) siblingId = destinationId; try { // move the node as requested and save the layout if (!ulm.moveNode(sourceId, ulm.getParentId(destinationId), siblingId)) { logger.warn("Failed to move tab in user layout. moveNode returned false"); response.setStatus(HttpServletResponse.SC_FORBIDDEN); return new ModelAndView( "jsonView", Collections.singletonMap( "response", getMessage( "error.move.tab", "There was an issue moving the tab, please refresh the page and try again.", locale))); } ulm.saveUserLayout(); } catch (PortalException e) { return handlePersistError(request, response, e); } return new ModelAndView( "jsonView", Collections.singletonMap( "response", getMessage("success.move.tab", "Tab moved successfully", locale))); } }
public class class_name { @RequestMapping(method = RequestMethod.POST, params = "action=moveTab") public ModelAndView moveTab( HttpServletRequest request, HttpServletResponse response, @RequestParam(value = "sourceID") String sourceId, @RequestParam String method, @RequestParam(value = "elementID") String destinationId) throws IOException { IUserInstance ui = userInstanceManager.getUserInstance(request); UserPreferencesManager upm = (UserPreferencesManager) ui.getPreferencesManager(); IUserLayoutManager ulm = upm.getUserLayoutManager(); final Locale locale = RequestContextUtils.getLocale(request); // If we're moving this element before another one, we need // to know what the target is. If there's no target, just // assume we're moving it to the very end of the list. String siblingId = null; if ("insertBefore".equals(method)) siblingId = destinationId; try { // move the node as requested and save the layout if (!ulm.moveNode(sourceId, ulm.getParentId(destinationId), siblingId)) { logger.warn("Failed to move tab in user layout. moveNode returned false"); // depends on control dependency: [if], data = [none] response.setStatus(HttpServletResponse.SC_FORBIDDEN); // depends on control dependency: [if], data = [none] return new ModelAndView( "jsonView", Collections.singletonMap( "response", getMessage( "error.move.tab", "There was an issue moving the tab, please refresh the page and try again.", locale))); // depends on control dependency: [if], data = [none] } ulm.saveUserLayout(); } catch (PortalException e) { return handlePersistError(request, response, e); } return new ModelAndView( "jsonView", Collections.singletonMap( "response", getMessage("success.move.tab", "Tab moved successfully", locale))); } }
public class class_name { public List<LifecycleCallbackType<WebFragmentDescriptor>> getAllPreDestroy() { List<LifecycleCallbackType<WebFragmentDescriptor>> list = new ArrayList<LifecycleCallbackType<WebFragmentDescriptor>>(); List<Node> nodeList = model.get("pre-destroy"); for(Node node: nodeList) { LifecycleCallbackType<WebFragmentDescriptor> type = new LifecycleCallbackTypeImpl<WebFragmentDescriptor>(this, "pre-destroy", model, node); list.add(type); } return list; } }
public class class_name { public List<LifecycleCallbackType<WebFragmentDescriptor>> getAllPreDestroy() { List<LifecycleCallbackType<WebFragmentDescriptor>> list = new ArrayList<LifecycleCallbackType<WebFragmentDescriptor>>(); List<Node> nodeList = model.get("pre-destroy"); for(Node node: nodeList) { LifecycleCallbackType<WebFragmentDescriptor> type = new LifecycleCallbackTypeImpl<WebFragmentDescriptor>(this, "pre-destroy", model, node); list.add(type); // depends on control dependency: [for], data = [none] } return list; } }
public class class_name { @Override public void publish(String channel, Tree message) { if (client != null) { try { if (debug && (debugHeartbeats || !channel.endsWith(heartbeatChannel))) { logger.info("Submitting message to channel \"" + channel + "\":\r\n" + message.toString()); } TopicPublisher publisher = createOrGetPublisher(channel); BytesMessage msg = session.createBytesMessage(); msg.writeBytes(serializer.write(message)); if (transacted) { synchronized (this) { try { publisher.send(msg, deliveryMode, priority, ttl); session.commit(); } catch (Exception cause) { try { session.rollback(); } catch (Exception ignored) { } throw cause; } } } else { publisher.send(msg, deliveryMode, priority, ttl); } } catch (Exception cause) { logger.warn("Unable to send message to JMS server!", cause); } } } }
public class class_name { @Override public void publish(String channel, Tree message) { if (client != null) { try { if (debug && (debugHeartbeats || !channel.endsWith(heartbeatChannel))) { logger.info("Submitting message to channel \"" + channel + "\":\r\n" + message.toString()); // depends on control dependency: [if], data = [none] } TopicPublisher publisher = createOrGetPublisher(channel); BytesMessage msg = session.createBytesMessage(); msg.writeBytes(serializer.write(message)); // depends on control dependency: [try], data = [none] if (transacted) { synchronized (this) { // depends on control dependency: [if], data = [none] try { publisher.send(msg, deliveryMode, priority, ttl); // depends on control dependency: [try], data = [none] session.commit(); // depends on control dependency: [try], data = [none] } catch (Exception cause) { try { session.rollback(); // depends on control dependency: [try], data = [none] } catch (Exception ignored) { } // depends on control dependency: [catch], data = [none] throw cause; } // depends on control dependency: [catch], data = [none] } } else { publisher.send(msg, deliveryMode, priority, ttl); // depends on control dependency: [if], data = [none] } } catch (Exception cause) { logger.warn("Unable to send message to JMS server!", cause); } // depends on control dependency: [catch], data = [none] } } }
public class class_name { public Object convert( String value, TypeLiteral<?> toType ) { try { return Time.valueOf( value ); } catch ( Throwable t ) { throw new ProvisionException( "String must be in JDBC format [HH:mm:ss] to create a java.sql.Time" ); } } }
public class class_name { public Object convert( String value, TypeLiteral<?> toType ) { try { return Time.valueOf( value ); // depends on control dependency: [try], data = [none] } catch ( Throwable t ) { throw new ProvisionException( "String must be in JDBC format [HH:mm:ss] to create a java.sql.Time" ); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private TransportPool getOrCreateTransportPool(String hostInfo, Settings settings, SecureSettings secureSettings) { TransportPool pool; pool = hostPools.get(hostInfo); // Check again in case it was added while waiting for the lock if (pool == null) { pool = new TransportPool(jobKey, hostInfo, settings, secureSettings); hostPools.put(hostInfo, pool); if (log.isDebugEnabled()) { log.debug("Creating new TransportPool for job ["+jobKey+"] for host ["+hostInfo+"]"); } } return pool; } }
public class class_name { private TransportPool getOrCreateTransportPool(String hostInfo, Settings settings, SecureSettings secureSettings) { TransportPool pool; pool = hostPools.get(hostInfo); // Check again in case it was added while waiting for the lock if (pool == null) { pool = new TransportPool(jobKey, hostInfo, settings, secureSettings); // depends on control dependency: [if], data = [none] hostPools.put(hostInfo, pool); // depends on control dependency: [if], data = [none] if (log.isDebugEnabled()) { log.debug("Creating new TransportPool for job ["+jobKey+"] for host ["+hostInfo+"]"); // depends on control dependency: [if], data = [none] } } return pool; } }
public class class_name { protected AbstractBeanDeployer<E> deploySpecialized() { // ensure that all decorators are initialized before initializing // the rest of the beans for (DecoratorImpl<?> bean : getEnvironment().getDecorators()) { bean.initialize(getEnvironment()); containerLifecycleEvents.fireProcessBean(getManager(), bean); manager.addDecorator(bean); BootstrapLogger.LOG.foundDecorator(bean); } for (InterceptorImpl<?> bean : getEnvironment().getInterceptors()) { bean.initialize(getEnvironment()); containerLifecycleEvents.fireProcessBean(getManager(), bean); manager.addInterceptor(bean); BootstrapLogger.LOG.foundInterceptor(bean); } return this; } }
public class class_name { protected AbstractBeanDeployer<E> deploySpecialized() { // ensure that all decorators are initialized before initializing // the rest of the beans for (DecoratorImpl<?> bean : getEnvironment().getDecorators()) { bean.initialize(getEnvironment()); // depends on control dependency: [for], data = [bean] containerLifecycleEvents.fireProcessBean(getManager(), bean); // depends on control dependency: [for], data = [bean] manager.addDecorator(bean); // depends on control dependency: [for], data = [bean] BootstrapLogger.LOG.foundDecorator(bean); // depends on control dependency: [for], data = [bean] } for (InterceptorImpl<?> bean : getEnvironment().getInterceptors()) { bean.initialize(getEnvironment()); // depends on control dependency: [for], data = [bean] containerLifecycleEvents.fireProcessBean(getManager(), bean); // depends on control dependency: [for], data = [bean] manager.addInterceptor(bean); // depends on control dependency: [for], data = [bean] BootstrapLogger.LOG.foundInterceptor(bean); // depends on control dependency: [for], data = [bean] } return this; } }
public class class_name { @Override @SuppressWarnings("unchecked") public NutMap addv(String key, Object value) { Object obj = get(key); if (null == obj) { put(key, value); } else if (obj instanceof List<?>) ((List<Object>) obj).add(value); else { List<Object> list = new LinkedList<Object>(); list.add(obj); list.add(value); put(key, list); } return this; } }
public class class_name { @Override @SuppressWarnings("unchecked") public NutMap addv(String key, Object value) { Object obj = get(key); if (null == obj) { put(key, value); // depends on control dependency: [if], data = [none] } else if (obj instanceof List<?>) ((List<Object>) obj).add(value); else { List<Object> list = new LinkedList<Object>(); list.add(obj); // depends on control dependency: [if], data = [)] list.add(value); // depends on control dependency: [if], data = [)] put(key, list); // depends on control dependency: [if], data = [)] } return this; } }
public class class_name { public void write(byte[] b, int offset, int length) throws IOException { int o=offset; int l=length; while (l>0) { int c=capacity(); if (_bypassBuffer && isCommitted() && size()==0 && l>c) { // Bypass buffer bypassWrite(b,o,l); break; } if (l<c || !isFixed()) { // Write all super.write(b,o,l); break; } else { // Write a block super.write(b,o,c); flush(); l-=c; o+=c; } } } }
public class class_name { public void write(byte[] b, int offset, int length) throws IOException { int o=offset; int l=length; while (l>0) { int c=capacity(); if (_bypassBuffer && isCommitted() && size()==0 && l>c) { // Bypass buffer bypassWrite(b,o,l); // depends on control dependency: [if], data = [none] break; } if (l<c || !isFixed()) { // Write all super.write(b,o,l); // depends on control dependency: [if], data = [none] break; } else { // Write a block super.write(b,o,c); // depends on control dependency: [if], data = [none] flush(); // depends on control dependency: [if], data = [none] l-=c; // depends on control dependency: [if], data = [none] o+=c; // depends on control dependency: [if], data = [none] } } } }
public class class_name { private void generateGenerator() { cfw.startMethod(codegen.getBodyMethodName(scriptOrFn), codegen.getBodyMethodSignature(scriptOrFn), (short)(ACC_STATIC | ACC_PRIVATE)); initBodyGeneration(); argsLocal = firstFreeLocal++; localsMax = firstFreeLocal; // get top level scope if (fnCurrent != null) { // Unless we're in a direct call use the enclosing scope // of the function as our variable object. cfw.addALoad(funObjLocal); cfw.addInvoke(ByteCode.INVOKEINTERFACE, "org/mozilla/javascript/Scriptable", "getParentScope", "()Lorg/mozilla/javascript/Scriptable;"); cfw.addAStore(variableObjectLocal); } // generators are forced to have an activation record cfw.addALoad(funObjLocal); cfw.addALoad(variableObjectLocal); cfw.addALoad(argsLocal); cfw.addPush(scriptOrFn.isInStrictMode()); addScriptRuntimeInvoke("createFunctionActivation", "(Lorg/mozilla/javascript/NativeFunction;" +"Lorg/mozilla/javascript/Scriptable;" +"[Ljava/lang/Object;" +"Z" +")Lorg/mozilla/javascript/Scriptable;"); cfw.addAStore(variableObjectLocal); // create a function object cfw.add(ByteCode.NEW, codegen.mainClassName); // Call function constructor cfw.add(ByteCode.DUP); cfw.addALoad(variableObjectLocal); cfw.addALoad(contextLocal); // load 'cx' cfw.addPush(scriptOrFnIndex); cfw.addInvoke(ByteCode.INVOKESPECIAL, codegen.mainClassName, "<init>", Codegen.FUNCTION_CONSTRUCTOR_SIGNATURE); generateNestedFunctionInits(); // create the NativeGenerator object that we return cfw.addALoad(variableObjectLocal); cfw.addALoad(thisObjLocal); cfw.addLoadConstant(maxLocals); cfw.addLoadConstant(maxStack); addOptRuntimeInvoke("createNativeGenerator", "(Lorg/mozilla/javascript/NativeFunction;" +"Lorg/mozilla/javascript/Scriptable;" +"Lorg/mozilla/javascript/Scriptable;II" +")Lorg/mozilla/javascript/Scriptable;"); cfw.add(ByteCode.ARETURN); cfw.stopMethod((short)(localsMax + 1)); } }
public class class_name { private void generateGenerator() { cfw.startMethod(codegen.getBodyMethodName(scriptOrFn), codegen.getBodyMethodSignature(scriptOrFn), (short)(ACC_STATIC | ACC_PRIVATE)); initBodyGeneration(); argsLocal = firstFreeLocal++; localsMax = firstFreeLocal; // get top level scope if (fnCurrent != null) { // Unless we're in a direct call use the enclosing scope // of the function as our variable object. cfw.addALoad(funObjLocal); // depends on control dependency: [if], data = [none] cfw.addInvoke(ByteCode.INVOKEINTERFACE, "org/mozilla/javascript/Scriptable", "getParentScope", "()Lorg/mozilla/javascript/Scriptable;"); cfw.addAStore(variableObjectLocal); // depends on control dependency: [if], data = [none] } // generators are forced to have an activation record cfw.addALoad(funObjLocal); cfw.addALoad(variableObjectLocal); cfw.addALoad(argsLocal); cfw.addPush(scriptOrFn.isInStrictMode()); addScriptRuntimeInvoke("createFunctionActivation", "(Lorg/mozilla/javascript/NativeFunction;" +"Lorg/mozilla/javascript/Scriptable;" +"[Ljava/lang/Object;" +"Z" +")Lorg/mozilla/javascript/Scriptable;"); cfw.addAStore(variableObjectLocal); // create a function object cfw.add(ByteCode.NEW, codegen.mainClassName); // Call function constructor cfw.add(ByteCode.DUP); cfw.addALoad(variableObjectLocal); cfw.addALoad(contextLocal); // load 'cx' cfw.addPush(scriptOrFnIndex); cfw.addInvoke(ByteCode.INVOKESPECIAL, codegen.mainClassName, "<init>", Codegen.FUNCTION_CONSTRUCTOR_SIGNATURE); generateNestedFunctionInits(); // create the NativeGenerator object that we return cfw.addALoad(variableObjectLocal); cfw.addALoad(thisObjLocal); cfw.addLoadConstant(maxLocals); cfw.addLoadConstant(maxStack); addOptRuntimeInvoke("createNativeGenerator", "(Lorg/mozilla/javascript/NativeFunction;" +"Lorg/mozilla/javascript/Scriptable;" +"Lorg/mozilla/javascript/Scriptable;II" +")Lorg/mozilla/javascript/Scriptable;"); cfw.add(ByteCode.ARETURN); cfw.stopMethod((short)(localsMax + 1)); } }
public class class_name { private void updateWorker(final Worker worker) { final ZkWorker zkWorker = zkWorkers.get(worker.getHost()); if (zkWorker != null) { log.info("Worker[%s] updated its announcement from[%s] to[%s].", worker.getHost(), zkWorker.getWorker(), worker); zkWorker.setWorker(worker); } else { log.warn( "WTF, worker[%s] updated its announcement but we didn't have a ZkWorker for it. Ignoring.", worker.getHost() ); } } }
public class class_name { private void updateWorker(final Worker worker) { final ZkWorker zkWorker = zkWorkers.get(worker.getHost()); if (zkWorker != null) { log.info("Worker[%s] updated its announcement from[%s] to[%s].", worker.getHost(), zkWorker.getWorker(), worker); // depends on control dependency: [if], data = [none] zkWorker.setWorker(worker); // depends on control dependency: [if], data = [none] } else { log.warn( "WTF, worker[%s] updated its announcement but we didn't have a ZkWorker for it. Ignoring.", worker.getHost() ); // depends on control dependency: [if], data = [none] } } }
public class class_name { public boolean next() { boolean ret = false; if (this.iterator == null) { this.iterator = this.objects.iterator(); } if (this.iterator.hasNext()) { this.current = this.iterator.next(); ret = true; } return ret; } }
public class class_name { public boolean next() { boolean ret = false; if (this.iterator == null) { this.iterator = this.objects.iterator(); // depends on control dependency: [if], data = [none] } if (this.iterator.hasNext()) { this.current = this.iterator.next(); // depends on control dependency: [if], data = [none] ret = true; // depends on control dependency: [if], data = [none] } return ret; } }
public class class_name { public static String trim(String s, int maxWidth) { if (s.length() <= maxWidth) { return (s); } return (s.substring(0, maxWidth)); } }
public class class_name { public static String trim(String s, int maxWidth) { if (s.length() <= maxWidth) { return (s); // depends on control dependency: [if], data = [none] } return (s.substring(0, maxWidth)); } }
public class class_name { @Override protected void appendOptionHtml(final AppendingStringBuffer buffer, final T choice, final int index, final String selected) { final T currentOptGroup = choice; if (isNewGroup(currentOptGroup)) { if (!isFirst(index)) { buffer.append(CLOSE_OPTGROUP_TAG); } appendOptGroupLabel(buffer, currentOptGroup); } super.appendOptionHtml(buffer, choice, index, selected); if (isLast(index)) { buffer.append(CLOSE_OPTGROUP_TAG); } last = currentOptGroup; } }
public class class_name { @Override protected void appendOptionHtml(final AppendingStringBuffer buffer, final T choice, final int index, final String selected) { final T currentOptGroup = choice; if (isNewGroup(currentOptGroup)) { if (!isFirst(index)) { buffer.append(CLOSE_OPTGROUP_TAG); // depends on control dependency: [if], data = [none] } appendOptGroupLabel(buffer, currentOptGroup); // depends on control dependency: [if], data = [none] } super.appendOptionHtml(buffer, choice, index, selected); if (isLast(index)) { buffer.append(CLOSE_OPTGROUP_TAG); // depends on control dependency: [if], data = [none] } last = currentOptGroup; } }
public class class_name { public void marshall(VoiceConnectorSettings voiceConnectorSettings, ProtocolMarshaller protocolMarshaller) { if (voiceConnectorSettings == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(voiceConnectorSettings.getCdrBucket(), CDRBUCKET_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(VoiceConnectorSettings voiceConnectorSettings, ProtocolMarshaller protocolMarshaller) { if (voiceConnectorSettings == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(voiceConnectorSettings.getCdrBucket(), CDRBUCKET_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 void setStreamProcessors(java.util.Collection<StreamProcessor> streamProcessors) { if (streamProcessors == null) { this.streamProcessors = null; return; } this.streamProcessors = new java.util.ArrayList<StreamProcessor>(streamProcessors); } }
public class class_name { public void setStreamProcessors(java.util.Collection<StreamProcessor> streamProcessors) { if (streamProcessors == null) { this.streamProcessors = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.streamProcessors = new java.util.ArrayList<StreamProcessor>(streamProcessors); } }
public class class_name { public VoltTable[] runAdHoc(SystemProcedureExecutionContext ctx, byte[] serializedBatchData) { Pair<Object[], AdHocPlannedStatement[]> data = decodeSerializedBatchData(serializedBatchData); Object[] userparams = data.getFirst(); AdHocPlannedStatement[] statements = data.getSecond(); if (statements.length == 0) { return new VoltTable[]{}; } for (AdHocPlannedStatement statement : statements) { if (!statement.core.wasPlannedAgainstHash(ctx.getCatalogHash())) { @SuppressWarnings("deprecation") String msg = String.format("AdHoc transaction %d wasn't planned " + "against the current catalog version. Statement: %s", DeprecatedProcedureAPIAccess.getVoltPrivateRealTransactionId(this), new String(statement.sql, Constants.UTF8ENCODING)); throw new VoltAbortException(msg); } // Don't cache the statement text, since ad hoc statements // that differ only by constants reuse the same plan, statement text may change. long aggFragId = ActivePlanRepository.loadOrAddRefPlanFragment( statement.core.aggregatorHash, statement.core.aggregatorFragment, null); long collectorFragId = 0; if (statement.core.collectorFragment != null) { collectorFragId = ActivePlanRepository.loadOrAddRefPlanFragment( statement.core.collectorHash, statement.core.collectorFragment, null); } SQLStmt stmt = SQLStmtAdHocHelper.createWithPlan( statement.sql, aggFragId, statement.core.aggregatorHash, true, collectorFragId, statement.core.collectorHash, true, statement.core.isReplicatedTableDML, statement.core.readOnly, statement.core.parameterTypes, m_site); Object[] params = paramsForStatement(statement, userparams); voltQueueSQL(stmt, params); } return voltExecuteSQL(true); } }
public class class_name { public VoltTable[] runAdHoc(SystemProcedureExecutionContext ctx, byte[] serializedBatchData) { Pair<Object[], AdHocPlannedStatement[]> data = decodeSerializedBatchData(serializedBatchData); Object[] userparams = data.getFirst(); AdHocPlannedStatement[] statements = data.getSecond(); if (statements.length == 0) { return new VoltTable[]{}; // depends on control dependency: [if], data = [none] } for (AdHocPlannedStatement statement : statements) { if (!statement.core.wasPlannedAgainstHash(ctx.getCatalogHash())) { @SuppressWarnings("deprecation") String msg = String.format("AdHoc transaction %d wasn't planned " + "against the current catalog version. Statement: %s", DeprecatedProcedureAPIAccess.getVoltPrivateRealTransactionId(this), new String(statement.sql, Constants.UTF8ENCODING)); throw new VoltAbortException(msg); } // Don't cache the statement text, since ad hoc statements // that differ only by constants reuse the same plan, statement text may change. long aggFragId = ActivePlanRepository.loadOrAddRefPlanFragment( statement.core.aggregatorHash, statement.core.aggregatorFragment, null); long collectorFragId = 0; if (statement.core.collectorFragment != null) { collectorFragId = ActivePlanRepository.loadOrAddRefPlanFragment( statement.core.collectorHash, statement.core.collectorFragment, null); // depends on control dependency: [if], data = [none] } SQLStmt stmt = SQLStmtAdHocHelper.createWithPlan( statement.sql, aggFragId, statement.core.aggregatorHash, true, collectorFragId, statement.core.collectorHash, true, statement.core.isReplicatedTableDML, statement.core.readOnly, statement.core.parameterTypes, m_site); Object[] params = paramsForStatement(statement, userparams); voltQueueSQL(stmt, params); // depends on control dependency: [for], data = [none] } return voltExecuteSQL(true); } }
public class class_name { protected void generateEntityValues(Object entity, DAOMode mode, DAOValidatorEvaluationTime validationTime) { // Obtention de la classe de l'entite Class<?> entityClass = entity.getClass(); // Obtention de la liste des champs de l'entite List<Field> fields = DAOValidatorHelper.getAllFields(entityClass, true); // Si la liste des champs est vide if(fields == null || fields.isEmpty()) return; // Parcours de la liste des champs for (Field field : fields) { // Chargement des annotaions de generation List<Annotation> daoAnnotations = DAOValidatorHelper.loadDAOGeneratorAnnotations(field); // Si la liste est vide if(daoAnnotations == null || daoAnnotations.size() == 0) continue; // Parcours de la liste des annotations for (Annotation daoAnnotation : daoAnnotations) { // Obtention de la classe de gestion du generateur Class<?> generatorClass = DAOValidatorHelper.getGenerationLogicClass(daoAnnotation); // Le generateur IDAOGeneratorManager<Annotation> generator = null; try { // On instancie le generateur generator = (IDAOGeneratorManager<Annotation>) generatorClass.newInstance(); // Initialisation du generateur generator.initialize(daoAnnotation, getGeneratorEntityManager(), getEntityManager(), mode, validationTime); } catch (Throwable e) { // On relance l'exception throw new JPersistenceToolsException("GeneratorInstanciationException.message", e); } // Validation des contraintes d'integrites generator.processGeneration(entity, field); } } } }
public class class_name { protected void generateEntityValues(Object entity, DAOMode mode, DAOValidatorEvaluationTime validationTime) { // Obtention de la classe de l'entite Class<?> entityClass = entity.getClass(); // Obtention de la liste des champs de l'entite List<Field> fields = DAOValidatorHelper.getAllFields(entityClass, true); // Si la liste des champs est vide if(fields == null || fields.isEmpty()) return; // Parcours de la liste des champs for (Field field : fields) { // Chargement des annotaions de generation List<Annotation> daoAnnotations = DAOValidatorHelper.loadDAOGeneratorAnnotations(field); // Si la liste est vide if(daoAnnotations == null || daoAnnotations.size() == 0) continue; // Parcours de la liste des annotations for (Annotation daoAnnotation : daoAnnotations) { // Obtention de la classe de gestion du generateur Class<?> generatorClass = DAOValidatorHelper.getGenerationLogicClass(daoAnnotation); // Le generateur IDAOGeneratorManager<Annotation> generator = null; try { // On instancie le generateur generator = (IDAOGeneratorManager<Annotation>) generatorClass.newInstance(); // Initialisation du generateur generator.initialize(daoAnnotation, getGeneratorEntityManager(), getEntityManager(), mode, validationTime); } catch (Throwable e) { // depends on control dependency: [for], data = [none] // On relance l'exception throw new JPersistenceToolsException("GeneratorInstanciationException.message", e); } // Validation des contraintes d'integrites generator.processGeneration(entity, field); // depends on control dependency: [for], data = [none] } } } }
public class class_name { public void remove(Identity oid) { if (oid == null) return; ObjectCache cache = getCache(oid, null, METHOD_REMOVE); if (cache != null) { cache.remove(oid); } } }
public class class_name { public void remove(Identity oid) { if (oid == null) return; ObjectCache cache = getCache(oid, null, METHOD_REMOVE); if (cache != null) { cache.remove(oid); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void put(String name,List list) { if (list==null || list.size()==0) { remove(name); return; } Object v=list.get(0); if (v!=null) put(name,v.toString()); else remove(name); if (list.size()>1) { java.util.Iterator iter = list.iterator(); iter.next(); while(iter.hasNext()) { v=iter.next(); if (v!=null) add(name,v.toString()); } } } }
public class class_name { public void put(String name,List list) { if (list==null || list.size()==0) { remove(name); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } Object v=list.get(0); if (v!=null) put(name,v.toString()); else remove(name); if (list.size()>1) { java.util.Iterator iter = list.iterator(); iter.next(); // depends on control dependency: [if], data = [none] while(iter.hasNext()) { v=iter.next(); // depends on control dependency: [while], data = [none] if (v!=null) add(name,v.toString()); } } } }
public class class_name { public List<Point2D_F64> convert( @Nullable List<Point2D_F64> storage , boolean copy ) { if( storage == null ) storage = new ArrayList<>(); else storage.clear(); if( copy ) { for (int i = 0; i < vertexes.size; i++) { storage.add( vertexes.get(i).copy() ); } } else { storage.addAll(vertexes.toList()); } return storage; } }
public class class_name { public List<Point2D_F64> convert( @Nullable List<Point2D_F64> storage , boolean copy ) { if( storage == null ) storage = new ArrayList<>(); else storage.clear(); if( copy ) { for (int i = 0; i < vertexes.size; i++) { storage.add( vertexes.get(i).copy() ); // depends on control dependency: [for], data = [i] } } else { storage.addAll(vertexes.toList()); // depends on control dependency: [if], data = [none] } return storage; } }
public class class_name { @Override public final void sessionIdle(NextFilter nextFilter, IoSession session, IdleStatus status) { if (eventTypes.contains(IoEventType.SESSION_IDLE)) { IoFilterEvent event = new IoFilterEvent(nextFilter, IoEventType.SESSION_IDLE, session, status); fireEvent(event); } else { nextFilter.sessionIdle(session, status); } } }
public class class_name { @Override public final void sessionIdle(NextFilter nextFilter, IoSession session, IdleStatus status) { if (eventTypes.contains(IoEventType.SESSION_IDLE)) { IoFilterEvent event = new IoFilterEvent(nextFilter, IoEventType.SESSION_IDLE, session, status); fireEvent(event); // depends on control dependency: [if], data = [none] } else { nextFilter.sessionIdle(session, status); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static int getScreenWidth(final GraphicsDevice graphicsDevice) { final GraphicsConfiguration[] graphicsConfigurations = graphicsDevice.getConfigurations(); final GraphicsConfiguration graphicsConfiguration = ArrayExtensions .getFirst(graphicsConfigurations); if (graphicsConfiguration != null) { final Rectangle bounds = graphicsConfiguration.getBounds(); final double width = bounds.getWidth(); return (int)width; } return getScreenWidth(); } }
public class class_name { public static int getScreenWidth(final GraphicsDevice graphicsDevice) { final GraphicsConfiguration[] graphicsConfigurations = graphicsDevice.getConfigurations(); final GraphicsConfiguration graphicsConfiguration = ArrayExtensions .getFirst(graphicsConfigurations); if (graphicsConfiguration != null) { final Rectangle bounds = graphicsConfiguration.getBounds(); final double width = bounds.getWidth(); return (int)width; // depends on control dependency: [if], data = [none] } return getScreenWidth(); } }
public class class_name { protected String getOptionalAttributeValue(StartElement start, QName attributeName) { Attribute mapNameAttribute = start.getAttributeByName(attributeName); if (mapNameAttribute == null) { return null; } else { return mapNameAttribute.getValue(); } } }
public class class_name { protected String getOptionalAttributeValue(StartElement start, QName attributeName) { Attribute mapNameAttribute = start.getAttributeByName(attributeName); if (mapNameAttribute == null) { return null; // depends on control dependency: [if], data = [none] } else { return mapNameAttribute.getValue(); // depends on control dependency: [if], data = [none] } } }
public class class_name { private static BeanInfo getBeanInfoOptional(Class<?> beanClass) { try { return Introspector.getBeanInfo(beanClass); } catch (IntrospectionException e) { return null; } } }
public class class_name { private static BeanInfo getBeanInfoOptional(Class<?> beanClass) { try { return Introspector.getBeanInfo(beanClass); // depends on control dependency: [try], data = [none] } catch (IntrospectionException e) { return null; } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static boolean equalsToIgnoreEndline(String expected, String actual) { if (expected == null && actual == null) { return true; } if (expected != null ^ actual != null) { return false; } Scanner scanner1 = new Scanner(expected); Scanner scanner2 = new Scanner(actual); String line1, line2; while (scanner1.hasNextLine()) { line1 = scanner1.nextLine(); line2 = scanner2.nextLine(); if (! line1.equals(line2)) { scanner1.close(); scanner2.close(); return false; } } if (scanner2.hasNextLine()) { scanner1.close(); scanner2.close(); return false; } scanner1.close(); scanner2.close(); return true; } }
public class class_name { public static boolean equalsToIgnoreEndline(String expected, String actual) { if (expected == null && actual == null) { return true; // depends on control dependency: [if], data = [none] } if (expected != null ^ actual != null) { return false; // depends on control dependency: [if], data = [none] } Scanner scanner1 = new Scanner(expected); Scanner scanner2 = new Scanner(actual); String line1, line2; while (scanner1.hasNextLine()) { line1 = scanner1.nextLine(); // depends on control dependency: [while], data = [none] line2 = scanner2.nextLine(); // depends on control dependency: [while], data = [none] if (! line1.equals(line2)) { scanner1.close(); // depends on control dependency: [if], data = [none] scanner2.close(); // depends on control dependency: [if], data = [none] return false; // depends on control dependency: [if], data = [none] } } if (scanner2.hasNextLine()) { scanner1.close(); // depends on control dependency: [if], data = [none] scanner2.close(); // depends on control dependency: [if], data = [none] return false; // depends on control dependency: [if], data = [none] } scanner1.close(); scanner2.close(); return true; } }
public class class_name { public static int crypto_sign_open( Sha512 sha512provider, byte[] m, long mlen, byte[] sm, long smlen, byte[] pk ) { byte[] pkcopy = new byte[32]; byte[] rcopy = new byte[32]; byte[] scopy = new byte[32]; byte[] h = new byte[64]; byte[] rcheck = new byte[32]; ge_p3 A = new ge_p3(); ge_p2 R = new ge_p2(); if (smlen < 64) return -1; if ((sm[63] & 224) != 0) return -1; if (ge_frombytes.ge_frombytes_negate_vartime(A,pk) != 0) return -1; byte[] pubkeyhash = new byte[64]; sha512provider.calculateDigest(pubkeyhash,pk,32); System.arraycopy(pk, 0, pkcopy, 0, 32); System.arraycopy(sm, 0, rcopy, 0, 32); System.arraycopy(sm, 32, scopy, 0, 32); System.arraycopy(sm, 0, m, 0, (int)smlen); System.arraycopy(pkcopy, 0, m, 32, 32); sha512provider.calculateDigest(h,m,smlen); sc_reduce.sc_reduce(h); ge_double_scalarmult.ge_double_scalarmult_vartime(R,h,A,scopy); ge_tobytes.ge_tobytes(rcheck,R); if (crypto_verify_32.crypto_verify_32(rcheck,rcopy) == 0) { System.arraycopy(m, 64, m, 0, (int)(smlen - 64)); //memset(m + smlen - 64,0,64); return 0; } //badsig: //memset(m,0,smlen); return -1; } }
public class class_name { public static int crypto_sign_open( Sha512 sha512provider, byte[] m, long mlen, byte[] sm, long smlen, byte[] pk ) { byte[] pkcopy = new byte[32]; byte[] rcopy = new byte[32]; byte[] scopy = new byte[32]; byte[] h = new byte[64]; byte[] rcheck = new byte[32]; ge_p3 A = new ge_p3(); ge_p2 R = new ge_p2(); if (smlen < 64) return -1; if ((sm[63] & 224) != 0) return -1; if (ge_frombytes.ge_frombytes_negate_vartime(A,pk) != 0) return -1; byte[] pubkeyhash = new byte[64]; sha512provider.calculateDigest(pubkeyhash,pk,32); System.arraycopy(pk, 0, pkcopy, 0, 32); System.arraycopy(sm, 0, rcopy, 0, 32); System.arraycopy(sm, 32, scopy, 0, 32); System.arraycopy(sm, 0, m, 0, (int)smlen); System.arraycopy(pkcopy, 0, m, 32, 32); sha512provider.calculateDigest(h,m,smlen); sc_reduce.sc_reduce(h); ge_double_scalarmult.ge_double_scalarmult_vartime(R,h,A,scopy); ge_tobytes.ge_tobytes(rcheck,R); if (crypto_verify_32.crypto_verify_32(rcheck,rcopy) == 0) { System.arraycopy(m, 64, m, 0, (int)(smlen - 64)); // depends on control dependency: [if], data = [none] //memset(m + smlen - 64,0,64); return 0; // depends on control dependency: [if], data = [none] } //badsig: //memset(m,0,smlen); return -1; } }
public class class_name { public static double daleChallGrade(String strText) { //http://rfptemplates.technologyevaluation.com/dale-chall-list-of-3000-simple-words.html double score=daleChallScore(strText); if(score<5.0) { return 2.5; } else if(score<6.0) { return 5.5; } else if(score<7.0) { return 7.5; } else if(score<8.0) { return 9.5; } else if(score<9.0) { return 11.5; } else if(score<10.0) { return 14.0; } else { return 16.0; } } }
public class class_name { public static double daleChallGrade(String strText) { //http://rfptemplates.technologyevaluation.com/dale-chall-list-of-3000-simple-words.html double score=daleChallScore(strText); if(score<5.0) { return 2.5; // depends on control dependency: [if], data = [none] } else if(score<6.0) { return 5.5; // depends on control dependency: [if], data = [none] } else if(score<7.0) { return 7.5; // depends on control dependency: [if], data = [none] } else if(score<8.0) { return 9.5; // depends on control dependency: [if], data = [none] } else if(score<9.0) { return 11.5; // depends on control dependency: [if], data = [none] } else if(score<10.0) { return 14.0; // depends on control dependency: [if], data = [none] } else { return 16.0; // depends on control dependency: [if], data = [none] } } }
public class class_name { private void instantiateIngest() throws IOException { InjectionHandler.processEvent(InjectionEvent.STANDBY_INSTANTIATE_INGEST); try { synchronized (ingestStateLock) { if (checkIngestState()) { LOG.info("Standby: Ingest for txid: " + currentSegmentTxId + " is already running"); return; } assertState(StandbyIngestState.NOT_INGESTING); ingest = new Ingest(this, fsnamesys, confg, currentSegmentTxId); ingestThread = new Thread(ingest); ingestThread.setName("Ingest_for_" + currentSegmentTxId); ingestThread.start(); currentIngestState = StandbyIngestState.INGESTING_EDITS; } LOG.info("Standby: Instatiated ingest for txid: " + currentSegmentTxId); } catch (IOException e) { setIngestFailures(ingestFailures + 1); currentIngestState = StandbyIngestState.NOT_INGESTING; throw e; } } }
public class class_name { private void instantiateIngest() throws IOException { InjectionHandler.processEvent(InjectionEvent.STANDBY_INSTANTIATE_INGEST); try { synchronized (ingestStateLock) { if (checkIngestState()) { LOG.info("Standby: Ingest for txid: " + currentSegmentTxId + " is already running"); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } assertState(StandbyIngestState.NOT_INGESTING); ingest = new Ingest(this, fsnamesys, confg, currentSegmentTxId); ingestThread = new Thread(ingest); ingestThread.setName("Ingest_for_" + currentSegmentTxId); ingestThread.start(); currentIngestState = StandbyIngestState.INGESTING_EDITS; } LOG.info("Standby: Instatiated ingest for txid: " + currentSegmentTxId); } catch (IOException e) { setIngestFailures(ingestFailures + 1); currentIngestState = StandbyIngestState.NOT_INGESTING; throw e; } } }
public class class_name { public void maybePutThrottle(int nodeId) { if(!putThrottlers.containsKey(nodeId)) { putThrottlers.putIfAbsent(nodeId, new EventThrottler(perServerQPSLimit)); } putThrottlers.get(nodeId).maybeThrottle(1); } }
public class class_name { public void maybePutThrottle(int nodeId) { if(!putThrottlers.containsKey(nodeId)) { putThrottlers.putIfAbsent(nodeId, new EventThrottler(perServerQPSLimit)); // depends on control dependency: [if], data = [none] } putThrottlers.get(nodeId).maybeThrottle(1); } }
public class class_name { public double sim(List<String> sentence, int index) { double score = 0; for (String word : sentence) { if (!f[index].containsKey(word)) continue; int d = docs.get(index).size(); Integer tf = f[index].get(word); score += (idf.get(word) * tf * (k1 + 1) / (tf + k1 * (1 - b + b * d / avgdl))); } return score; } }
public class class_name { public double sim(List<String> sentence, int index) { double score = 0; for (String word : sentence) { if (!f[index].containsKey(word)) continue; int d = docs.get(index).size(); Integer tf = f[index].get(word); score += (idf.get(word) * tf * (k1 + 1) / (tf + k1 * (1 - b + b * d / avgdl))); // depends on control dependency: [for], data = [word] } return score; } }
public class class_name { public void setServerName(String serverName) { if (serverName == null || serverName.equals("")) { this.serverName = "localhost"; } else { this.serverName = serverName; } } }
public class class_name { public void setServerName(String serverName) { if (serverName == null || serverName.equals("")) { this.serverName = "localhost"; // depends on control dependency: [if], data = [none] } else { this.serverName = serverName; // depends on control dependency: [if], data = [none] } } }
public class class_name { private void filterMappingsOfChildren(INode sourceParent, INode targetParent, char semanticRelation) { List<INode> source = new ArrayList<INode>(sourceParent.getChildrenList()); List<INode> target = new ArrayList<INode>(targetParent.getChildrenList()); sourceIndex.add(sourceParent.getLevel(), 0); targetIndex.add(targetParent.getLevel(), 0); if (source.size() >= 1 && target.size() >= 1) { //sorts the siblings first with the strongest relation, and then with the others filterMappingsOfSiblingsByRelation(source, target, semanticRelation); } sourceIndex.remove(sourceParent.getLevel()); targetIndex.remove(targetParent.getLevel()); } }
public class class_name { private void filterMappingsOfChildren(INode sourceParent, INode targetParent, char semanticRelation) { List<INode> source = new ArrayList<INode>(sourceParent.getChildrenList()); List<INode> target = new ArrayList<INode>(targetParent.getChildrenList()); sourceIndex.add(sourceParent.getLevel(), 0); targetIndex.add(targetParent.getLevel(), 0); if (source.size() >= 1 && target.size() >= 1) { //sorts the siblings first with the strongest relation, and then with the others filterMappingsOfSiblingsByRelation(source, target, semanticRelation); // depends on control dependency: [if], data = [none] } sourceIndex.remove(sourceParent.getLevel()); targetIndex.remove(targetParent.getLevel()); } }
public class class_name { private ParseTree parseShiftExpression() { SourcePosition start = getTreeStartLocation(); ParseTree left = parseAdditiveExpression(); while (peekShiftOperator()) { Token operator = nextToken(); ParseTree right = parseAdditiveExpression(); left = new BinaryOperatorTree(getTreeLocation(start), left, operator, right); } return left; } }
public class class_name { private ParseTree parseShiftExpression() { SourcePosition start = getTreeStartLocation(); ParseTree left = parseAdditiveExpression(); while (peekShiftOperator()) { Token operator = nextToken(); ParseTree right = parseAdditiveExpression(); left = new BinaryOperatorTree(getTreeLocation(start), left, operator, right); // depends on control dependency: [while], data = [none] } return left; } }
public class class_name { private static void doBox(CodeBuilder adapter, SoyRuntimeType type) { if (type.isKnownSanitizedContent()) { FieldRef.enumReference( ContentKind.valueOf(((SanitizedType) type.soyType()).getContentKind().name())) .accessStaticUnchecked(adapter); MethodRef.ORDAIN_AS_SAFE.invokeUnchecked(adapter); } else if (type.isKnownString()) { MethodRef.STRING_DATA_FOR_VALUE.invokeUnchecked(adapter); } else if (type.isKnownListOrUnionOfLists()) { MethodRef.LIST_IMPL_FOR_PROVIDER_LIST.invokeUnchecked(adapter); } else if (type.isKnownLegacyObjectMapOrUnionOfMaps()) { FieldRef.enumReference(RuntimeMapTypeTracker.Type.LEGACY_OBJECT_MAP_OR_RECORD) .putUnchecked(adapter); MethodRef.DICT_IMPL_FOR_PROVIDER_MAP.invokeUnchecked(adapter); } else if (type.isKnownMapOrUnionOfMaps()) { MethodRef.MAP_IMPL_FOR_PROVIDER_MAP.invokeUnchecked(adapter); } else if (type.isKnownProtoOrUnionOfProtos()) { MethodRef.SOY_PROTO_VALUE_CREATE.invokeUnchecked(adapter); } else { throw new IllegalStateException("Can't box soy expression of type " + type); } } }
public class class_name { private static void doBox(CodeBuilder adapter, SoyRuntimeType type) { if (type.isKnownSanitizedContent()) { FieldRef.enumReference( ContentKind.valueOf(((SanitizedType) type.soyType()).getContentKind().name())) .accessStaticUnchecked(adapter); // depends on control dependency: [if], data = [none] MethodRef.ORDAIN_AS_SAFE.invokeUnchecked(adapter); // depends on control dependency: [if], data = [none] } else if (type.isKnownString()) { MethodRef.STRING_DATA_FOR_VALUE.invokeUnchecked(adapter); // depends on control dependency: [if], data = [none] } else if (type.isKnownListOrUnionOfLists()) { MethodRef.LIST_IMPL_FOR_PROVIDER_LIST.invokeUnchecked(adapter); // depends on control dependency: [if], data = [none] } else if (type.isKnownLegacyObjectMapOrUnionOfMaps()) { FieldRef.enumReference(RuntimeMapTypeTracker.Type.LEGACY_OBJECT_MAP_OR_RECORD) .putUnchecked(adapter); // depends on control dependency: [if], data = [none] MethodRef.DICT_IMPL_FOR_PROVIDER_MAP.invokeUnchecked(adapter); // depends on control dependency: [if], data = [none] } else if (type.isKnownMapOrUnionOfMaps()) { MethodRef.MAP_IMPL_FOR_PROVIDER_MAP.invokeUnchecked(adapter); // depends on control dependency: [if], data = [none] } else if (type.isKnownProtoOrUnionOfProtos()) { MethodRef.SOY_PROTO_VALUE_CREATE.invokeUnchecked(adapter); // depends on control dependency: [if], data = [none] } else { throw new IllegalStateException("Can't box soy expression of type " + type); } } }
public class class_name { public static void setPreferredRoadConnectionDistance(double distance) { final Preferences prefs = Preferences.userNodeForPackage(RoadNetworkConstants.class); if (prefs != null) { if (distance <= 0.) { prefs.remove("ROAD_CONNECTION_DISTANCE"); //$NON-NLS-1$ } else { prefs.putDouble("ROAD_CONNECTION_DISTANCE", distance); //$NON-NLS-1$ } } } }
public class class_name { public static void setPreferredRoadConnectionDistance(double distance) { final Preferences prefs = Preferences.userNodeForPackage(RoadNetworkConstants.class); if (prefs != null) { if (distance <= 0.) { prefs.remove("ROAD_CONNECTION_DISTANCE"); //$NON-NLS-1$ // depends on control dependency: [if], data = [none] } else { prefs.putDouble("ROAD_CONNECTION_DISTANCE", distance); //$NON-NLS-1$ // depends on control dependency: [if], data = [none] } } } }
public class class_name { private ReCaptcha newReCaptcha(final String publicKey, final String privateKey, final boolean includeNoscript) { if (WicketComponentExtensions.isSecure(ComponentFinder.getCurrentPage())) { final ReCaptcha reCaptcha = ReCaptchaFactory.newSecureReCaptcha(getPublicKey(), getPrivateKey(), includeNoscript); ((ReCaptchaImpl)reCaptcha).setRecaptchaServer(RECAPTCHA_SERVER_URL); return reCaptcha; } return ReCaptchaFactory.newReCaptcha(getPublicKey(), getPrivateKey(), includeNoscript); } }
public class class_name { private ReCaptcha newReCaptcha(final String publicKey, final String privateKey, final boolean includeNoscript) { if (WicketComponentExtensions.isSecure(ComponentFinder.getCurrentPage())) { final ReCaptcha reCaptcha = ReCaptchaFactory.newSecureReCaptcha(getPublicKey(), getPrivateKey(), includeNoscript); ((ReCaptchaImpl)reCaptcha).setRecaptchaServer(RECAPTCHA_SERVER_URL); // depends on control dependency: [if], data = [none] return reCaptcha; // depends on control dependency: [if], data = [none] } return ReCaptchaFactory.newReCaptcha(getPublicKey(), getPrivateKey(), includeNoscript); } }
public class class_name { public void setAccounts(java.util.Collection<Account> accounts) { if (accounts == null) { this.accounts = null; return; } this.accounts = new java.util.ArrayList<Account>(accounts); } }
public class class_name { public void setAccounts(java.util.Collection<Account> accounts) { if (accounts == null) { this.accounts = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.accounts = new java.util.ArrayList<Account>(accounts); } }
public class class_name { @DELETE @Path("/{variantId}") public Response deleteVariant(@PathParam("variantId") String variantId) { Variant variant = variantService.findByVariantID(variantId); if (variant == null) { return Response.status(Response.Status.NOT_FOUND).entity("Could not find requested Variant").build(); } if (!type.isInstance(variant)) { return Response.status(Response.Status.BAD_REQUEST).entity("Requested Variant is of another type/platform").build(); } logger.trace("Deleting: {}", variant.getClass().getSimpleName()); variantService.removeVariant(variant); return Response.noContent().build(); } }
public class class_name { @DELETE @Path("/{variantId}") public Response deleteVariant(@PathParam("variantId") String variantId) { Variant variant = variantService.findByVariantID(variantId); if (variant == null) { return Response.status(Response.Status.NOT_FOUND).entity("Could not find requested Variant").build(); // depends on control dependency: [if], data = [none] } if (!type.isInstance(variant)) { return Response.status(Response.Status.BAD_REQUEST).entity("Requested Variant is of another type/platform").build(); // depends on control dependency: [if], data = [none] } logger.trace("Deleting: {}", variant.getClass().getSimpleName()); variantService.removeVariant(variant); return Response.noContent().build(); } }
public class class_name { public static Map<String, String> getNamespaces(final Session session) { final NamespaceRegistry registry = getNamespaceRegistry(session); final Map<String, String> namespaces = new HashMap<>(); try { stream(registry.getPrefixes()).filter(internalPrefix.negate()).forEach(x -> { try { namespaces.put(x, registry.getURI(x)); } catch (final RepositoryException e) { throw new RepositoryRuntimeException(e); } }); } catch (final RepositoryException e) { throw new RepositoryRuntimeException(e); } return namespaces; } }
public class class_name { public static Map<String, String> getNamespaces(final Session session) { final NamespaceRegistry registry = getNamespaceRegistry(session); final Map<String, String> namespaces = new HashMap<>(); try { stream(registry.getPrefixes()).filter(internalPrefix.negate()).forEach(x -> { try { namespaces.put(x, registry.getURI(x)); // depends on control dependency: [try], data = [none] } catch (final RepositoryException e) { throw new RepositoryRuntimeException(e); } // depends on control dependency: [catch], data = [none] }); } catch (final RepositoryException e) { throw new RepositoryRuntimeException(e); } return namespaces; } }
public class class_name { public static Bitmap applyColor(Bitmap bitmap, int accentColor) { int r = Color.red(accentColor); int g = Color.green(accentColor); int b = Color.blue(accentColor); int width = bitmap.getWidth(); int height = bitmap.getHeight(); int[] pixels = new int[width * height]; bitmap.getPixels(pixels, 0, width, 0, 0, width, height); for (int i=0; i<pixels.length; i++) { int color = pixels[i]; int alpha = Color.alpha(color); pixels[i] = Color.argb(alpha, r, g, b); } return Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888); } }
public class class_name { public static Bitmap applyColor(Bitmap bitmap, int accentColor) { int r = Color.red(accentColor); int g = Color.green(accentColor); int b = Color.blue(accentColor); int width = bitmap.getWidth(); int height = bitmap.getHeight(); int[] pixels = new int[width * height]; bitmap.getPixels(pixels, 0, width, 0, 0, width, height); for (int i=0; i<pixels.length; i++) { int color = pixels[i]; int alpha = Color.alpha(color); pixels[i] = Color.argb(alpha, r, g, b); // depends on control dependency: [for], data = [i] } return Bitmap.createBitmap(pixels, width, height, Bitmap.Config.ARGB_8888); } }
public class class_name { public BufferedReader getReader() throws FileNotFoundException { LineNumberReader reader = new LineNumberReader(new InputStreamReader(new FileInputStream(file), getCharset())); if (hasUTF8Bom() || hasUTF16LEBom() || hasUTF16BEBom()) { try { reader.read(); } catch (IOException e) { // should never happen, as a file with no content // but with a BOM has at least one char } } return reader; } }
public class class_name { public BufferedReader getReader() throws FileNotFoundException { LineNumberReader reader = new LineNumberReader(new InputStreamReader(new FileInputStream(file), getCharset())); if (hasUTF8Bom() || hasUTF16LEBom() || hasUTF16BEBom()) { try { reader.read(); // depends on control dependency: [try], data = [none] } catch (IOException e) { // should never happen, as a file with no content // but with a BOM has at least one char } // depends on control dependency: [catch], data = [none] } return reader; } }
public class class_name { @Override public void clear() { removeAllUserData(); if (this.children != null) { N child; for (int i = 0; i < this.children.length; ++i) { child = this.children[i]; if (child != null) { setChildAt(i, null); child.clear(); } } } } }
public class class_name { @Override public void clear() { removeAllUserData(); if (this.children != null) { N child; for (int i = 0; i < this.children.length; ++i) { child = this.children[i]; // depends on control dependency: [for], data = [i] if (child != null) { setChildAt(i, null); // depends on control dependency: [if], data = [null)] child.clear(); // depends on control dependency: [if], data = [none] } } } } }
public class class_name { public boolean addClasspathEntry(final String pathElement, final ClassLoader classLoader, final ScanSpec scanSpec, final LogNode log) { if (pathElement == null || pathElement.isEmpty()) { return false; } // Check for wildcard path element (allowable for local classpaths as of JDK 6) if (pathElement.endsWith("*")) { if (pathElement.length() == 1 || // (pathElement.length() > 2 && pathElement.charAt(pathElement.length() - 1) == '*' && (pathElement.charAt(pathElement.length() - 2) == File.separatorChar || (File.separatorChar != '/' && pathElement.charAt(pathElement.length() - 2) == '/')))) { // Apply classpath element filters, if any final String baseDirPath = pathElement.length() == 1 ? "" : pathElement.substring(0, pathElement.length() - 2); final String baseDirPathResolved = FastPathResolver.resolve(FileUtils.CURR_DIR_PATH, baseDirPath); if (!filter(baseDirPath) || (!baseDirPathResolved.equals(baseDirPath) && !filter(baseDirPathResolved))) { if (log != null) { log.log("Classpath element did not match filter criterion, skipping: " + pathElement); } return false; } // Check the path before the "/*" suffix is a directory final File baseDir = new File(baseDirPathResolved); if (!baseDir.exists()) { if (log != null) { log.log("Directory does not exist for wildcard classpath element: " + pathElement); } return false; } if (!FileUtils.canRead(baseDir)) { if (log != null) { log.log("Cannot read directory for wildcard classpath element: " + pathElement); } return false; } if (!baseDir.isDirectory()) { if (log != null) { log.log("Wildcard is appended to something other than a directory: " + pathElement); } return false; } // Add all elements in the requested directory to the classpath final LogNode dirLog = log == null ? null : log.log("Adding classpath elements from wildcarded directory: " + pathElement); final File[] baseDirFiles = baseDir.listFiles(); if (baseDirFiles != null) { for (final File fileInDir : baseDirFiles) { final String name = fileInDir.getName(); if (!name.equals(".") && !name.equals("..")) { // Add each directory entry as a classpath element final String fileInDirPath = fileInDir.getPath(); final String fileInDirPathResolved = FastPathResolver.resolve(FileUtils.CURR_DIR_PATH, fileInDirPath); if (addClasspathEntry(fileInDirPathResolved, classLoader, scanSpec)) { if (dirLog != null) { dirLog.log("Found classpath element: " + fileInDirPath + (fileInDirPath.equals(fileInDirPathResolved) ? "" : " -> " + fileInDirPathResolved)); } } else { if (dirLog != null) { dirLog.log("Ignoring duplicate classpath element: " + fileInDirPath + (fileInDirPath.equals(fileInDirPathResolved) ? "" : " -> " + fileInDirPathResolved)); } } } } return true; } else { return false; } } else { if (log != null) { log.log("Wildcard classpath elements can only end with a leaf of \"*\", " + "can't have a partial name and then a wildcard: " + pathElement); } return false; } } else { // Non-wildcarded (standard) classpath element final String pathElementResolved = FastPathResolver.resolve(FileUtils.CURR_DIR_PATH, pathElement); if (!filter(pathElement) || (!pathElementResolved.equals(pathElement) && !filter(pathElementResolved))) { if (log != null) { log.log("Classpath element did not match filter criterion, skipping: " + pathElement + (pathElement.equals(pathElementResolved) ? "" : " -> " + pathElementResolved)); } return false; } if (addClasspathEntry(pathElementResolved, classLoader, scanSpec)) { if (log != null) { log.log("Found classpath element: " + pathElement + (pathElement.equals(pathElementResolved) ? "" : " -> " + pathElementResolved)); } return true; } else { if (log != null) { log.log("Ignoring duplicate classpath element: " + pathElement + (pathElement.equals(pathElementResolved) ? "" : " -> " + pathElementResolved)); } return false; } } } }
public class class_name { public boolean addClasspathEntry(final String pathElement, final ClassLoader classLoader, final ScanSpec scanSpec, final LogNode log) { if (pathElement == null || pathElement.isEmpty()) { return false; // depends on control dependency: [if], data = [none] } // Check for wildcard path element (allowable for local classpaths as of JDK 6) if (pathElement.endsWith("*")) { if (pathElement.length() == 1 || // (pathElement.length() > 2 && pathElement.charAt(pathElement.length() - 1) == '*' && (pathElement.charAt(pathElement.length() - 2) == File.separatorChar || (File.separatorChar != '/' && pathElement.charAt(pathElement.length() - 2) == '/')))) { // Apply classpath element filters, if any final String baseDirPath = pathElement.length() == 1 ? "" : pathElement.substring(0, pathElement.length() - 2); final String baseDirPathResolved = FastPathResolver.resolve(FileUtils.CURR_DIR_PATH, baseDirPath); if (!filter(baseDirPath) || (!baseDirPathResolved.equals(baseDirPath) && !filter(baseDirPathResolved))) { if (log != null) { log.log("Classpath element did not match filter criterion, skipping: " + pathElement); // depends on control dependency: [if], data = [none] } return false; // depends on control dependency: [if], data = [none] } // Check the path before the "/*" suffix is a directory final File baseDir = new File(baseDirPathResolved); if (!baseDir.exists()) { if (log != null) { log.log("Directory does not exist for wildcard classpath element: " + pathElement); // depends on control dependency: [if], data = [none] } return false; // depends on control dependency: [if], data = [none] } if (!FileUtils.canRead(baseDir)) { if (log != null) { log.log("Cannot read directory for wildcard classpath element: " + pathElement); // depends on control dependency: [if], data = [none] } return false; // depends on control dependency: [if], data = [none] } if (!baseDir.isDirectory()) { if (log != null) { log.log("Wildcard is appended to something other than a directory: " + pathElement); // depends on control dependency: [if], data = [none] } return false; // depends on control dependency: [if], data = [none] } // Add all elements in the requested directory to the classpath final LogNode dirLog = log == null ? null : log.log("Adding classpath elements from wildcarded directory: " + pathElement); final File[] baseDirFiles = baseDir.listFiles(); if (baseDirFiles != null) { for (final File fileInDir : baseDirFiles) { final String name = fileInDir.getName(); if (!name.equals(".") && !name.equals("..")) { // Add each directory entry as a classpath element final String fileInDirPath = fileInDir.getPath(); final String fileInDirPathResolved = FastPathResolver.resolve(FileUtils.CURR_DIR_PATH, fileInDirPath); if (addClasspathEntry(fileInDirPathResolved, classLoader, scanSpec)) { if (dirLog != null) { dirLog.log("Found classpath element: " + fileInDirPath + (fileInDirPath.equals(fileInDirPathResolved) ? "" : " -> " + fileInDirPathResolved)); // depends on control dependency: [if], data = [none] } } else { if (dirLog != null) { dirLog.log("Ignoring duplicate classpath element: " + fileInDirPath + (fileInDirPath.equals(fileInDirPathResolved) ? "" : " -> " + fileInDirPathResolved)); // depends on control dependency: [if], data = [none] } } } } return true; // depends on control dependency: [if], data = [none] } else { return false; // depends on control dependency: [if], data = [none] } } else { if (log != null) { log.log("Wildcard classpath elements can only end with a leaf of \"*\", " + "can't have a partial name and then a wildcard: " + pathElement); // depends on control dependency: [if], data = [none] } return false; // depends on control dependency: [if], data = [none] } } else { // Non-wildcarded (standard) classpath element final String pathElementResolved = FastPathResolver.resolve(FileUtils.CURR_DIR_PATH, pathElement); if (!filter(pathElement) || (!pathElementResolved.equals(pathElement) && !filter(pathElementResolved))) { if (log != null) { log.log("Classpath element did not match filter criterion, skipping: " + pathElement + (pathElement.equals(pathElementResolved) ? "" : " -> " + pathElementResolved)); // depends on control dependency: [if], data = [none] } return false; // depends on control dependency: [if], data = [none] } if (addClasspathEntry(pathElementResolved, classLoader, scanSpec)) { if (log != null) { log.log("Found classpath element: " + pathElement + (pathElement.equals(pathElementResolved) ? "" : " -> " + pathElementResolved)); // depends on control dependency: [if], data = [none] } return true; // depends on control dependency: [if], data = [none] } else { if (log != null) { log.log("Ignoring duplicate classpath element: " + pathElement + (pathElement.equals(pathElementResolved) ? "" : " -> " + pathElementResolved)); // depends on control dependency: [if], data = [none] } return false; // depends on control dependency: [if], data = [none] } } } }
public class class_name { public FacesConfigConverterType<FacesConfigType<T>> getOrCreateConverter() { List<Node> nodeList = childNode.get("converter"); if (nodeList != null && nodeList.size() > 0) { return new FacesConfigConverterTypeImpl<FacesConfigType<T>>(this, "converter", childNode, nodeList.get(0)); } return createConverter(); } }
public class class_name { public FacesConfigConverterType<FacesConfigType<T>> getOrCreateConverter() { List<Node> nodeList = childNode.get("converter"); if (nodeList != null && nodeList.size() > 0) { return new FacesConfigConverterTypeImpl<FacesConfigType<T>>(this, "converter", childNode, nodeList.get(0)); // depends on control dependency: [if], data = [none] } return createConverter(); } }
public class class_name { public boolean readBoundary () throws MultipartMalformedStreamException { final byte [] marker = new byte [2]; boolean bNextChunk = false; m_nHead += m_nBoundaryLength; try { marker[0] = readByte (); if (marker[0] == LF) { // Work around IE5 Mac bug with input type=image. // Because the boundary delimiter, not including the trailing // CRLF, must not appear within any file (RFC 2046, section // 5.1.1), we know the missing CR is due to a buggy browser // rather than a file containing something similar to a // boundary. return true; } marker[1] = readByte (); if (ArrayHelper.startsWith (marker, STREAM_TERMINATOR)) bNextChunk = false; else if (ArrayHelper.startsWith (marker, FIELD_SEPARATOR)) bNextChunk = true; else throw new MultipartMalformedStreamException ("Unexpected characters follow a boundary"); } catch (final IOException ex) { throw new MultipartMalformedStreamException ("Stream ended unexpectedly", ex); } return bNextChunk; } }
public class class_name { public boolean readBoundary () throws MultipartMalformedStreamException { final byte [] marker = new byte [2]; boolean bNextChunk = false; m_nHead += m_nBoundaryLength; try { marker[0] = readByte (); if (marker[0] == LF) { // Work around IE5 Mac bug with input type=image. // Because the boundary delimiter, not including the trailing // CRLF, must not appear within any file (RFC 2046, section // 5.1.1), we know the missing CR is due to a buggy browser // rather than a file containing something similar to a // boundary. return true; // depends on control dependency: [if], data = [none] } marker[1] = readByte (); if (ArrayHelper.startsWith (marker, STREAM_TERMINATOR)) bNextChunk = false; else if (ArrayHelper.startsWith (marker, FIELD_SEPARATOR)) bNextChunk = true; else throw new MultipartMalformedStreamException ("Unexpected characters follow a boundary"); } catch (final IOException ex) { throw new MultipartMalformedStreamException ("Stream ended unexpectedly", ex); } return bNextChunk; } }
public class class_name { public void processOpCall(Op op) { // total number of invocations invocationsCount.incrementAndGet(); // number of invocations for this specific op opCounter.incrementCount(op.opName()); // number of invocations for specific class String opClass = getOpClass(op); classCounter.incrementCount(opClass); if(op.x() == null || (op.x() != null && op.x().data().address() == lastZ && op.z() == op.x() && op.y() == null)) { // we have possible shift here matchingCounter.incrementCount(prevOpMatching + " -> " + opClass); matchingCounterDetailed.incrementCount(prevOpMatchingDetailed + " -> " + opClass + " " + op.opName()); } else { matchingCounter.totalsIncrement(); matchingCounterDetailed.totalsIncrement(); if (op.y() != null && op.y().data().address() == lastZ) { matchingCounterInverted.incrementCount(prevOpMatchingInverted + " -> " + opClass + " " + op.opName()); } else { matchingCounterInverted.totalsIncrement(); } } lastZ = op.z() != null ? op.z().data().address() : 0L; prevOpMatching = opClass; prevOpMatchingDetailed = opClass + " " + op.opName(); prevOpMatchingInverted = opClass + " " + op.opName(); updatePairs(op.opName(), opClass); if (config.isNotOptimalArguments()) { PenaltyCause[] causes = processOperands(op.x(), op.y(), op.z()); for (PenaltyCause cause : causes) { switch (cause) { case NON_EWS_ACCESS: nonEwsAggregator.incrementCount(); break; case STRIDED_ACCESS: stridedAggregator.incrementCount(); break; case MIXED_ORDER: mixedOrderAggregator.incrementCount(); break; case NONE: default: break; } } } for (OpProfilerListener listener : listeners) { listener.invoke(op); } } }
public class class_name { public void processOpCall(Op op) { // total number of invocations invocationsCount.incrementAndGet(); // number of invocations for this specific op opCounter.incrementCount(op.opName()); // number of invocations for specific class String opClass = getOpClass(op); classCounter.incrementCount(opClass); if(op.x() == null || (op.x() != null && op.x().data().address() == lastZ && op.z() == op.x() && op.y() == null)) { // we have possible shift here matchingCounter.incrementCount(prevOpMatching + " -> " + opClass); // depends on control dependency: [if], data = [none] matchingCounterDetailed.incrementCount(prevOpMatchingDetailed + " -> " + opClass + " " + op.opName()); // depends on control dependency: [if], data = [none] } else { matchingCounter.totalsIncrement(); // depends on control dependency: [if], data = [none] matchingCounterDetailed.totalsIncrement(); // depends on control dependency: [if], data = [none] if (op.y() != null && op.y().data().address() == lastZ) { matchingCounterInverted.incrementCount(prevOpMatchingInverted + " -> " + opClass + " " + op.opName()); // depends on control dependency: [if], data = [none] } else { matchingCounterInverted.totalsIncrement(); // depends on control dependency: [if], data = [none] } } lastZ = op.z() != null ? op.z().data().address() : 0L; prevOpMatching = opClass; prevOpMatchingDetailed = opClass + " " + op.opName(); prevOpMatchingInverted = opClass + " " + op.opName(); updatePairs(op.opName(), opClass); if (config.isNotOptimalArguments()) { PenaltyCause[] causes = processOperands(op.x(), op.y(), op.z()); for (PenaltyCause cause : causes) { switch (cause) { case NON_EWS_ACCESS: nonEwsAggregator.incrementCount(); break; case STRIDED_ACCESS: stridedAggregator.incrementCount(); break; case MIXED_ORDER: mixedOrderAggregator.incrementCount(); break; case NONE: default: break; } } } for (OpProfilerListener listener : listeners) { listener.invoke(op); // depends on control dependency: [for], data = [listener] } } }
public class class_name { protected void writeBundle(PrintWriter writer, String name, ResourceBundle bundle) { writer.print("var "); writer.print(escapeBundleName(name)); writer.println(" = {"); Enumeration<String> keyEnum = bundle.getKeys(); while (keyEnum.hasMoreElements()) { String key = keyEnum.nextElement(); Object object = bundle.getObject(key); if (object instanceof String) { writer.print(escapeBundleKey(key)); writer.print(":\""); writer.print(object.toString()); writer.print("\","); } } writer.println("};"); } }
public class class_name { protected void writeBundle(PrintWriter writer, String name, ResourceBundle bundle) { writer.print("var "); writer.print(escapeBundleName(name)); writer.println(" = {"); Enumeration<String> keyEnum = bundle.getKeys(); while (keyEnum.hasMoreElements()) { String key = keyEnum.nextElement(); Object object = bundle.getObject(key); if (object instanceof String) { writer.print(escapeBundleKey(key)); // depends on control dependency: [if], data = [none] writer.print(":\""); // depends on control dependency: [if], data = [none] writer.print(object.toString()); // depends on control dependency: [if], data = [none] writer.print("\","); // depends on control dependency: [if], data = [none] } } writer.println("};"); } }
public class class_name { public boolean parse(Context context, ProcPatternElement terminator) { Source source = context.getSource(); int offset = source.getOffset(); int end; if (terminator != null && !ghost) { end = terminator.findIn(source); if (end < 0) { if (regex == null) { return false; } else { end = source.length(); } } } else { end = source.length(); } CharSequence value = source.sub(end); // If define regex, then find this regex in value if (regex != null) { Matcher matcher = regex.matcher(value); if (matcher.lookingAt()) { int lend = matcher.end(); end = offset + lend; value = matcher.group(); } else { return false; } } // Old context value CharSequence old = (CharSequence) context.getAttribute(getName()); // Test this variable already defined and equals with this in this code scope CharSequence attr = (CharSequence) context.getLocalAttribute(getName()); if (attr == null || attr.equals(value)) { if (attr == null) { if (action == Action.rewrite) { setAttribute(context, value); } else { /* action == append */ if (old != null) { setAttribute(context, new StringBuilder().append(old).append(value)); } else { setAttribute(context, value); } } } if (!ghost) { source.incOffset(end - offset); } return true; } else { return false; } } }
public class class_name { public boolean parse(Context context, ProcPatternElement terminator) { Source source = context.getSource(); int offset = source.getOffset(); int end; if (terminator != null && !ghost) { end = terminator.findIn(source); // depends on control dependency: [if], data = [none] if (end < 0) { if (regex == null) { return false; // depends on control dependency: [if], data = [none] } else { end = source.length(); // depends on control dependency: [if], data = [none] } } } else { end = source.length(); // depends on control dependency: [if], data = [none] } CharSequence value = source.sub(end); // If define regex, then find this regex in value if (regex != null) { Matcher matcher = regex.matcher(value); if (matcher.lookingAt()) { int lend = matcher.end(); end = offset + lend; // depends on control dependency: [if], data = [none] value = matcher.group(); // depends on control dependency: [if], data = [none] } else { return false; // depends on control dependency: [if], data = [none] } } // Old context value CharSequence old = (CharSequence) context.getAttribute(getName()); // Test this variable already defined and equals with this in this code scope CharSequence attr = (CharSequence) context.getLocalAttribute(getName()); if (attr == null || attr.equals(value)) { if (attr == null) { if (action == Action.rewrite) { setAttribute(context, value); // depends on control dependency: [if], data = [none] } else { /* action == append */ if (old != null) { setAttribute(context, new StringBuilder().append(old).append(value)); // depends on control dependency: [if], data = [(old] } else { setAttribute(context, value); // depends on control dependency: [if], data = [none] } } } if (!ghost) { source.incOffset(end - offset); // depends on control dependency: [if], data = [none] } return true; // depends on control dependency: [if], data = [none] } else { return false; // depends on control dependency: [if], data = [none] } } }
public class class_name { public static JSONObject beanToJson(Object object) throws IllegalAccessException, InvocationTargetException { Method[] methods = object.getClass().getMethods(); JSONObject jsonObject = new JSONObject(); for (Method method : methods) { String name = method.getName(); if (name.startsWith("get") && !"getClass".equals(name)) { name = name.substring(3); jsonObject.put(name.substring(0, 1).toLowerCase() + name.substring(1), method.invoke(object)); } else if (name.startsWith("is")) { jsonObject.put(name, method.invoke(object)); } } return jsonObject; } }
public class class_name { public static JSONObject beanToJson(Object object) throws IllegalAccessException, InvocationTargetException { Method[] methods = object.getClass().getMethods(); JSONObject jsonObject = new JSONObject(); for (Method method : methods) { String name = method.getName(); if (name.startsWith("get") && !"getClass".equals(name)) { name = name.substring(3); // depends on control dependency: [if], data = [none] jsonObject.put(name.substring(0, 1).toLowerCase() + name.substring(1), method.invoke(object)); // depends on control dependency: [if], data = [none] } else if (name.startsWith("is")) { jsonObject.put(name, method.invoke(object)); // depends on control dependency: [if], data = [none] } } return jsonObject; } }
public class class_name { public void setPeriodTriggers(java.util.Collection<String> periodTriggers) { if (periodTriggers == null) { this.periodTriggers = null; return; } this.periodTriggers = new java.util.ArrayList<String>(periodTriggers); } }
public class class_name { public void setPeriodTriggers(java.util.Collection<String> periodTriggers) { if (periodTriggers == null) { this.periodTriggers = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.periodTriggers = new java.util.ArrayList<String>(periodTriggers); } }
public class class_name { public BigInteger nextBigInteger(int radix) { // Check cached result if ((typeCache != null) && (typeCache instanceof BigInteger) && this.radix == radix) { BigInteger val = (BigInteger)typeCache; useTypeCache(); return val; } setRadix(radix); clearCaches(); // Search for next int try { String s = next(integerPattern()); if (matcher.group(SIMPLE_GROUP_INDEX) == null) s = processIntegerToken(s); return new BigInteger(s, radix); } catch (NumberFormatException nfe) { position = matcher.start(); // don't skip bad token throw new InputMismatchException(nfe.getMessage()); } } }
public class class_name { public BigInteger nextBigInteger(int radix) { // Check cached result if ((typeCache != null) && (typeCache instanceof BigInteger) && this.radix == radix) { BigInteger val = (BigInteger)typeCache; useTypeCache(); // depends on control dependency: [if], data = [none] return val; // depends on control dependency: [if], data = [none] } setRadix(radix); clearCaches(); // Search for next int try { String s = next(integerPattern()); if (matcher.group(SIMPLE_GROUP_INDEX) == null) s = processIntegerToken(s); return new BigInteger(s, radix); // depends on control dependency: [try], data = [none] } catch (NumberFormatException nfe) { position = matcher.start(); // don't skip bad token throw new InputMismatchException(nfe.getMessage()); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void clearCache() { if (accountCache != null) { accountCache.invalidateAll(); } for (Realm realm : allRealms) { if (realm instanceof CachingRealm) { CachingRealm cachingRealm = (CachingRealm) realm; cachingRealm.clearCache(); } } } }
public class class_name { public void clearCache() { if (accountCache != null) { accountCache.invalidateAll(); // depends on control dependency: [if], data = [none] } for (Realm realm : allRealms) { if (realm instanceof CachingRealm) { CachingRealm cachingRealm = (CachingRealm) realm; cachingRealm.clearCache(); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public void marshall(CancelClusterRequest cancelClusterRequest, ProtocolMarshaller protocolMarshaller) { if (cancelClusterRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(cancelClusterRequest.getClusterId(), CLUSTERID_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(CancelClusterRequest cancelClusterRequest, ProtocolMarshaller protocolMarshaller) { if (cancelClusterRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(cancelClusterRequest.getClusterId(), CLUSTERID_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 { private Node performArithmeticOp(Token opType, Node left, Node right) { // Unlike other operations, ADD operands are not always converted // to Number. if (opType == Token.ADD && (NodeUtil.mayBeString(left, shouldUseTypes) || NodeUtil.mayBeString(right, shouldUseTypes))) { return null; } double result; // TODO(johnlenz): Handle NaN with unknown value. BIT ops convert NaN // to zero so this is a little awkward here. Double lValObj = NodeUtil.getNumberValue(left); Double rValObj = NodeUtil.getNumberValue(right); // at least one of the two operands must have a value and both must be numeric if ((lValObj == null && rValObj == null) || !isNumeric(left) || !isNumeric(right)) { return null; } // handle the operations that have algebraic identities, since we can simplify the tree without // actually knowing the value statically. switch (opType) { case ADD: if (lValObj != null && rValObj != null) { return maybeReplaceBinaryOpWithNumericResult(lValObj + rValObj, lValObj, rValObj); } if (lValObj != null && lValObj == 0) { return right.cloneTree(true); } else if (rValObj != null && rValObj == 0) { return left.cloneTree(true); } return null; case SUB: if (lValObj != null && rValObj != null) { return maybeReplaceBinaryOpWithNumericResult(lValObj - rValObj, lValObj, rValObj); } if (lValObj != null && lValObj == 0) { // 0 - x -> -x return IR.neg(right.cloneTree(true)); } else if (rValObj != null && rValObj == 0) { // x - 0 -> x return left.cloneTree(true); } return null; case MUL: if (lValObj != null && rValObj != null) { return maybeReplaceBinaryOpWithNumericResult(lValObj * rValObj, lValObj, rValObj); } // NOTE: 0*x != 0 for all x, if x==0, then it is NaN. So we can't take advantage of that // without some kind of non-NaN proof. So the special cases here only deal with 1*x if (lValObj != null) { if (lValObj == 1) { return right.cloneTree(true); } } else { if (rValObj == 1) { return left.cloneTree(true); } } return null; case DIV: if (lValObj != null && rValObj != null) { if (rValObj == 0) { return null; } return maybeReplaceBinaryOpWithNumericResult(lValObj / rValObj, lValObj, rValObj); } // NOTE: 0/x != 0 for all x, if x==0, then it is NaN if (rValObj != null) { if (rValObj == 1) { // x/1->x return left.cloneTree(true); } } return null; case EXPONENT: if (lValObj != null && rValObj != null) { return maybeReplaceBinaryOpWithNumericResult( Math.pow(lValObj, rValObj), lValObj, rValObj); } return null; default: // fall-through } if (lValObj == null || rValObj == null) { return null; } double lval = lValObj; double rval = rValObj; switch (opType) { case BITAND: result = NodeUtil.toInt32(lval) & NodeUtil.toInt32(rval); break; case BITOR: result = NodeUtil.toInt32(lval) | NodeUtil.toInt32(rval); break; case BITXOR: result = NodeUtil.toInt32(lval) ^ NodeUtil.toInt32(rval); break; case MOD: if (rval == 0) { return null; } result = lval % rval; break; default: throw new Error("Unexpected arithmetic operator: " + opType); } return maybeReplaceBinaryOpWithNumericResult(result, lval, rval); } }
public class class_name { private Node performArithmeticOp(Token opType, Node left, Node right) { // Unlike other operations, ADD operands are not always converted // to Number. if (opType == Token.ADD && (NodeUtil.mayBeString(left, shouldUseTypes) || NodeUtil.mayBeString(right, shouldUseTypes))) { return null; // depends on control dependency: [if], data = [none] } double result; // TODO(johnlenz): Handle NaN with unknown value. BIT ops convert NaN // to zero so this is a little awkward here. Double lValObj = NodeUtil.getNumberValue(left); Double rValObj = NodeUtil.getNumberValue(right); // at least one of the two operands must have a value and both must be numeric if ((lValObj == null && rValObj == null) || !isNumeric(left) || !isNumeric(right)) { return null; // depends on control dependency: [if], data = [none] } // handle the operations that have algebraic identities, since we can simplify the tree without // actually knowing the value statically. switch (opType) { case ADD: if (lValObj != null && rValObj != null) { return maybeReplaceBinaryOpWithNumericResult(lValObj + rValObj, lValObj, rValObj); // depends on control dependency: [if], data = [(lValObj] } if (lValObj != null && lValObj == 0) { return right.cloneTree(true); // depends on control dependency: [if], data = [none] } else if (rValObj != null && rValObj == 0) { return left.cloneTree(true); // depends on control dependency: [if], data = [none] } return null; case SUB: if (lValObj != null && rValObj != null) { return maybeReplaceBinaryOpWithNumericResult(lValObj - rValObj, lValObj, rValObj); // depends on control dependency: [if], data = [(lValObj] } if (lValObj != null && lValObj == 0) { // 0 - x -> -x return IR.neg(right.cloneTree(true)); // depends on control dependency: [if], data = [none] } else if (rValObj != null && rValObj == 0) { // x - 0 -> x return left.cloneTree(true); // depends on control dependency: [if], data = [none] } return null; case MUL: if (lValObj != null && rValObj != null) { return maybeReplaceBinaryOpWithNumericResult(lValObj * rValObj, lValObj, rValObj); // depends on control dependency: [if], data = [(lValObj] } // NOTE: 0*x != 0 for all x, if x==0, then it is NaN. So we can't take advantage of that // without some kind of non-NaN proof. So the special cases here only deal with 1*x if (lValObj != null) { if (lValObj == 1) { return right.cloneTree(true); // depends on control dependency: [if], data = [none] } } else { if (rValObj == 1) { return left.cloneTree(true); // depends on control dependency: [if], data = [none] } } return null; case DIV: if (lValObj != null && rValObj != null) { if (rValObj == 0) { return null; // depends on control dependency: [if], data = [none] } return maybeReplaceBinaryOpWithNumericResult(lValObj / rValObj, lValObj, rValObj); // depends on control dependency: [if], data = [(lValObj] } // NOTE: 0/x != 0 for all x, if x==0, then it is NaN if (rValObj != null) { if (rValObj == 1) { // x/1->x return left.cloneTree(true); // depends on control dependency: [if], data = [none] } } return null; case EXPONENT: if (lValObj != null && rValObj != null) { return maybeReplaceBinaryOpWithNumericResult( Math.pow(lValObj, rValObj), lValObj, rValObj); // depends on control dependency: [if], data = [none] } return null; default: // fall-through } if (lValObj == null || rValObj == null) { return null; // depends on control dependency: [if], data = [none] } double lval = lValObj; double rval = rValObj; switch (opType) { case BITAND: result = NodeUtil.toInt32(lval) & NodeUtil.toInt32(rval); break; case BITOR: result = NodeUtil.toInt32(lval) | NodeUtil.toInt32(rval); break; case BITXOR: result = NodeUtil.toInt32(lval) ^ NodeUtil.toInt32(rval); break; case MOD: if (rval == 0) { return null; // depends on control dependency: [if], data = [none] } result = lval % rval; break; default: throw new Error("Unexpected arithmetic operator: " + opType); } return maybeReplaceBinaryOpWithNumericResult(result, lval, rval); } }
public class class_name { public static String toJsonStr(Object obj) { if (null == obj) { return null; } if (obj instanceof String) { return (String) obj; } return toJsonStr(parse(obj)); } }
public class class_name { public static String toJsonStr(Object obj) { if (null == obj) { return null; // depends on control dependency: [if], data = [none] } if (obj instanceof String) { return (String) obj; // depends on control dependency: [if], data = [none] } return toJsonStr(parse(obj)); } }
public class class_name { public static Deferred<Boolean> processAllTrees(final TSDB tsdb, final TSMeta meta) { /** * Simple final callback that waits on all of the processing calls before * returning */ final class FinalCB implements Callback<Boolean, ArrayList<ArrayList<Boolean>>> { @Override public Boolean call(final ArrayList<ArrayList<Boolean>> groups) throws Exception { return true; } } /** * Callback that loops through the local list of trees, processing the * TSMeta through each */ final class ProcessTreesCB implements Callback<Deferred<Boolean>, List<Tree>> { // stores the tree deferred calls for later joining. Lazily initialized ArrayList<Deferred<ArrayList<Boolean>>> processed_trees; @Override public Deferred<Boolean> call(List<Tree> trees) throws Exception { if (trees == null || trees.isEmpty()) { LOG.debug("No trees found to process meta through"); return Deferred.fromResult(false); } else { LOG.debug("Loaded [" + trees.size() + "] trees"); } processed_trees = new ArrayList<Deferred<ArrayList<Boolean>>>(trees.size()); for (Tree tree : trees) { if (!tree.getEnabled()) { continue; } final TreeBuilder builder = new TreeBuilder(tsdb, new Tree(tree)); processed_trees.add(builder.processTimeseriesMeta(meta, false)); } return Deferred.group(processed_trees).addCallback(new FinalCB()); } } /** * Callback used when loading or re-loading the cached list of trees */ final class FetchedTreesCB implements Callback<List<Tree>, List<Tree>> { @Override public List<Tree> call(final List<Tree> loaded_trees) throws Exception { final List<Tree> local_trees; synchronized(trees) { trees.clear(); for (final Tree tree : loaded_trees) { if (tree.getEnabled()) { trees.add(tree); } } local_trees = new ArrayList<Tree>(trees.size()); local_trees.addAll(trees); } trees_lock.unlock(); return local_trees; } } /** * Since we can't use a try/catch/finally to release the lock we need to * setup an ErrBack to catch any exception thrown by the loader and * release the lock before returning */ final class ErrorCB implements Callback<Object, Exception> { @Override public Object call(final Exception e) throws Exception { trees_lock.unlock(); throw e; } } // lock to load or trees_lock.lock(); // if we haven't loaded our trees in a while or we've just started, load if (((System.currentTimeMillis() / 1000) - last_tree_load) > 300) { final Deferred<List<Tree>> load_deferred = Tree.fetchAllTrees(tsdb) .addCallback(new FetchedTreesCB()).addErrback(new ErrorCB()); last_tree_load = (System.currentTimeMillis() / 1000); return load_deferred.addCallbackDeferring(new ProcessTreesCB()); } // copy the tree list so we don't hold up the other threads while we're // processing final List<Tree> local_trees; if (trees.isEmpty()) { LOG.debug("No trees were found to process the meta through"); trees_lock.unlock(); return Deferred.fromResult(true); } local_trees = new ArrayList<Tree>(trees.size()); local_trees.addAll(trees); // unlock so the next thread can get a copy of the trees and start // processing trees_lock.unlock(); try { return new ProcessTreesCB().call(local_trees); } catch (Exception e) { throw new RuntimeException("Failed to process trees", e); } } }
public class class_name { public static Deferred<Boolean> processAllTrees(final TSDB tsdb, final TSMeta meta) { /** * Simple final callback that waits on all of the processing calls before * returning */ final class FinalCB implements Callback<Boolean, ArrayList<ArrayList<Boolean>>> { @Override public Boolean call(final ArrayList<ArrayList<Boolean>> groups) throws Exception { return true; } } /** * Callback that loops through the local list of trees, processing the * TSMeta through each */ final class ProcessTreesCB implements Callback<Deferred<Boolean>, List<Tree>> { // stores the tree deferred calls for later joining. Lazily initialized ArrayList<Deferred<ArrayList<Boolean>>> processed_trees; @Override public Deferred<Boolean> call(List<Tree> trees) throws Exception { if (trees == null || trees.isEmpty()) { LOG.debug("No trees found to process meta through"); return Deferred.fromResult(false); } else { LOG.debug("Loaded [" + trees.size() + "] trees"); } processed_trees = new ArrayList<Deferred<ArrayList<Boolean>>>(trees.size()); for (Tree tree : trees) { if (!tree.getEnabled()) { continue; } final TreeBuilder builder = new TreeBuilder(tsdb, new Tree(tree)); processed_trees.add(builder.processTimeseriesMeta(meta, false)); } return Deferred.group(processed_trees).addCallback(new FinalCB()); } } /** * Callback used when loading or re-loading the cached list of trees */ final class FetchedTreesCB implements Callback<List<Tree>, List<Tree>> { @Override public List<Tree> call(final List<Tree> loaded_trees) throws Exception { final List<Tree> local_trees; synchronized(trees) { trees.clear(); for (final Tree tree : loaded_trees) { if (tree.getEnabled()) { trees.add(tree); // depends on control dependency: [if], data = [none] } } local_trees = new ArrayList<Tree>(trees.size()); local_trees.addAll(trees); } trees_lock.unlock(); return local_trees; } } /** * Since we can't use a try/catch/finally to release the lock we need to * setup an ErrBack to catch any exception thrown by the loader and * release the lock before returning */ final class ErrorCB implements Callback<Object, Exception> { @Override public Object call(final Exception e) throws Exception { trees_lock.unlock(); throw e; } } // lock to load or trees_lock.lock(); // if we haven't loaded our trees in a while or we've just started, load if (((System.currentTimeMillis() / 1000) - last_tree_load) > 300) { final Deferred<List<Tree>> load_deferred = Tree.fetchAllTrees(tsdb) .addCallback(new FetchedTreesCB()).addErrback(new ErrorCB()); last_tree_load = (System.currentTimeMillis() / 1000); return load_deferred.addCallbackDeferring(new ProcessTreesCB()); } // copy the tree list so we don't hold up the other threads while we're // processing final List<Tree> local_trees; if (trees.isEmpty()) { LOG.debug("No trees were found to process the meta through"); trees_lock.unlock(); return Deferred.fromResult(true); } local_trees = new ArrayList<Tree>(trees.size()); local_trees.addAll(trees); // unlock so the next thread can get a copy of the trees and start // processing trees_lock.unlock(); try { return new ProcessTreesCB().call(local_trees); } catch (Exception e) { throw new RuntimeException("Failed to process trees", e); } } }
public class class_name { public boolean isIndexed() { boolean indexed = false; for (FeatureIndexType type : indexLocationQueryOrder) { indexed = isIndexed(type); if (indexed) { break; } } return indexed; } }
public class class_name { public boolean isIndexed() { boolean indexed = false; for (FeatureIndexType type : indexLocationQueryOrder) { indexed = isIndexed(type); // depends on control dependency: [for], data = [type] if (indexed) { break; } } return indexed; } }