code
stringlengths
130
281k
code_dependency
stringlengths
182
306k
public class class_name { public void marshall(EbsBlockDeviceConfig ebsBlockDeviceConfig, ProtocolMarshaller protocolMarshaller) { if (ebsBlockDeviceConfig == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(ebsBlockDeviceConfig.getVolumeSpecification(), VOLUMESPECIFICATION_BINDING); protocolMarshaller.marshall(ebsBlockDeviceConfig.getVolumesPerInstance(), VOLUMESPERINSTANCE_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(EbsBlockDeviceConfig ebsBlockDeviceConfig, ProtocolMarshaller protocolMarshaller) { if (ebsBlockDeviceConfig == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(ebsBlockDeviceConfig.getVolumeSpecification(), VOLUMESPECIFICATION_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(ebsBlockDeviceConfig.getVolumesPerInstance(), VOLUMESPERINSTANCE_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 Histogram getRefinedHistogram(SalesforceConnector connector, String entity, String watermarkColumn, SourceState state, Partition partition, Histogram histogram) { final int maxPartitions = state.getPropAsInt(ConfigurationKeys.SOURCE_MAX_NUMBER_OF_PARTITIONS, ConfigurationKeys.DEFAULT_MAX_NUMBER_OF_PARTITIONS); final int probeLimit = state.getPropAsInt(DYNAMIC_PROBING_LIMIT, DEFAULT_DYNAMIC_PROBING_LIMIT); final int minTargetPartitionSize = state.getPropAsInt(MIN_TARGET_PARTITION_SIZE, DEFAULT_MIN_TARGET_PARTITION_SIZE); final Histogram outputHistogram = new Histogram(); final double probeTargetRatio = state.getPropAsDouble(PROBE_TARGET_RATIO, DEFAULT_PROBE_TARGET_RATIO); final int bucketSizeLimit = (int) (probeTargetRatio * computeTargetPartitionSize(histogram, minTargetPartitionSize, maxPartitions)); log.info("Refining histogram with bucket size limit {}.", bucketSizeLimit); HistogramGroup currentGroup; HistogramGroup nextGroup; final TableCountProbingContext probingContext = new TableCountProbingContext(connector, entity, watermarkColumn, bucketSizeLimit, probeLimit); if (histogram.getGroups().isEmpty()) { return outputHistogram; } // make a copy of the histogram list and add a dummy entry at the end to avoid special processing of the last group List<HistogramGroup> list = new ArrayList(histogram.getGroups()); Date hwmDate = Utils.toDate(partition.getHighWatermark(), Partitioner.WATERMARKTIMEFORMAT); list.add(new HistogramGroup(Utils.epochToDate(hwmDate.getTime(), SECONDS_FORMAT), 0)); for (int i = 0; i < list.size() - 1; i++) { currentGroup = list.get(i); nextGroup = list.get(i + 1); // split the group if it is larger than the bucket size limit if (currentGroup.count > bucketSizeLimit) { long startEpoch = Utils.toDate(currentGroup.getKey(), SECONDS_FORMAT).getTime(); long endEpoch = Utils.toDate(nextGroup.getKey(), SECONDS_FORMAT).getTime(); outputHistogram.add(getHistogramByProbing(probingContext, currentGroup.count, startEpoch, endEpoch)); } else { outputHistogram.add(currentGroup); } } log.info("Executed {} probes for refining the histogram.", probingContext.probeCount); // if the probe limit has been reached then print a warning if (probingContext.probeCount >= probingContext.probeLimit) { log.warn("Reached the probe limit"); } return outputHistogram; } }
public class class_name { private Histogram getRefinedHistogram(SalesforceConnector connector, String entity, String watermarkColumn, SourceState state, Partition partition, Histogram histogram) { final int maxPartitions = state.getPropAsInt(ConfigurationKeys.SOURCE_MAX_NUMBER_OF_PARTITIONS, ConfigurationKeys.DEFAULT_MAX_NUMBER_OF_PARTITIONS); final int probeLimit = state.getPropAsInt(DYNAMIC_PROBING_LIMIT, DEFAULT_DYNAMIC_PROBING_LIMIT); final int minTargetPartitionSize = state.getPropAsInt(MIN_TARGET_PARTITION_SIZE, DEFAULT_MIN_TARGET_PARTITION_SIZE); final Histogram outputHistogram = new Histogram(); final double probeTargetRatio = state.getPropAsDouble(PROBE_TARGET_RATIO, DEFAULT_PROBE_TARGET_RATIO); final int bucketSizeLimit = (int) (probeTargetRatio * computeTargetPartitionSize(histogram, minTargetPartitionSize, maxPartitions)); log.info("Refining histogram with bucket size limit {}.", bucketSizeLimit); HistogramGroup currentGroup; HistogramGroup nextGroup; final TableCountProbingContext probingContext = new TableCountProbingContext(connector, entity, watermarkColumn, bucketSizeLimit, probeLimit); if (histogram.getGroups().isEmpty()) { return outputHistogram; // depends on control dependency: [if], data = [none] } // make a copy of the histogram list and add a dummy entry at the end to avoid special processing of the last group List<HistogramGroup> list = new ArrayList(histogram.getGroups()); Date hwmDate = Utils.toDate(partition.getHighWatermark(), Partitioner.WATERMARKTIMEFORMAT); list.add(new HistogramGroup(Utils.epochToDate(hwmDate.getTime(), SECONDS_FORMAT), 0)); for (int i = 0; i < list.size() - 1; i++) { currentGroup = list.get(i); // depends on control dependency: [for], data = [i] nextGroup = list.get(i + 1); // depends on control dependency: [for], data = [i] // split the group if it is larger than the bucket size limit if (currentGroup.count > bucketSizeLimit) { long startEpoch = Utils.toDate(currentGroup.getKey(), SECONDS_FORMAT).getTime(); long endEpoch = Utils.toDate(nextGroup.getKey(), SECONDS_FORMAT).getTime(); outputHistogram.add(getHistogramByProbing(probingContext, currentGroup.count, startEpoch, endEpoch)); // depends on control dependency: [if], data = [none] } else { outputHistogram.add(currentGroup); // depends on control dependency: [if], data = [none] } } log.info("Executed {} probes for refining the histogram.", probingContext.probeCount); // if the probe limit has been reached then print a warning if (probingContext.probeCount >= probingContext.probeLimit) { log.warn("Reached the probe limit"); // depends on control dependency: [if], data = [none] } return outputHistogram; } }
public class class_name { private boolean isTileNotAvailable(Pathfindable mover, int ctx, int cty, Integer ignoreObjectId) { final Collection<Integer> ids = getObjectsId(ctx, cty); final Tile tile = map.getTile(ctx, cty); if (tile != null) { final TilePath tilePath = tile.getFeature(TilePath.class); if (mover.isBlocking(tilePath.getCategory()) || ignoreObjectId != null && !ids.isEmpty() && !ids.contains(ignoreObjectId)) { return true; } } return false; } }
public class class_name { private boolean isTileNotAvailable(Pathfindable mover, int ctx, int cty, Integer ignoreObjectId) { final Collection<Integer> ids = getObjectsId(ctx, cty); final Tile tile = map.getTile(ctx, cty); if (tile != null) { final TilePath tilePath = tile.getFeature(TilePath.class); if (mover.isBlocking(tilePath.getCategory()) || ignoreObjectId != null && !ids.isEmpty() && !ids.contains(ignoreObjectId)) { return true; // depends on control dependency: [if], data = [none] } } return false; } }
public class class_name { public static RiakClient newClient(InetSocketAddress... addresses) throws UnknownHostException { final List<String> remoteAddresses = new ArrayList<>(addresses.length); for (InetSocketAddress addy : addresses) { remoteAddresses.add( String.format("%s:%s", addy.getHostName(), addy.getPort()) ); } return newClient(createDefaultNodeBuilder(), remoteAddresses); } }
public class class_name { public static RiakClient newClient(InetSocketAddress... addresses) throws UnknownHostException { final List<String> remoteAddresses = new ArrayList<>(addresses.length); for (InetSocketAddress addy : addresses) { remoteAddresses.add( String.format("%s:%s", addy.getHostName(), addy.getPort()) ); // depends on control dependency: [for], data = [none] } return newClient(createDefaultNodeBuilder(), remoteAddresses); } }
public class class_name { static Query createWithNextPageQuery(String nextPageQuery) { Query query = new Query(); query.nextPageQuery = nextPageQuery; if(nextPageQuery != null) { String nextPageParameters=nextPageQuery.substring(1, nextPageQuery.length()); Map<String,String> params=new LinkedHashMap<String,String>(); for(HttpParameter param : HttpParameter.decodeParameters(nextPageParameters)) { // Yes, we'll overwrite duplicate parameters, but we should not // get duplicate parameters from this endpoint. params.put(param.getName(), param.getValue()); } if(params.containsKey("q")) query.setQuery(params.get("q")); if(params.containsKey("lang")) query.setLang(params.get("lang")); if(params.containsKey("locale")) query.setLocale(params.get("locale")); if(params.containsKey("max_id")) query.setMaxId(Long.parseLong(params.get("max_id"))); if(params.containsKey("count")) query.setCount(Integer.parseInt(params.get("count"))); if(params.containsKey("geocode")) { String[] parts=params.get("geocode").split(","); double latitude=Double.parseDouble(parts[0]); double longitude=Double.parseDouble(parts[1]); double radius=0.0; Query.Unit unit=null; String radiusstr=parts[2]; for(Query.Unit value : Query.Unit.values()) if(radiusstr.endsWith(value.name())) { radius = Double.parseDouble(radiusstr.substring(0, radiusstr.length()-2)); unit = value; break; } if(unit == null) throw new IllegalArgumentException("unrecognized geocode radius: "+radiusstr); query.setGeoCode(new GeoLocation(latitude, longitude), radius, unit); } if(params.containsKey("result_type")) query.setResultType(Query.ResultType.valueOf(params.get("result_type"))); // We don't pull out since, until -- they get pushed into the query } return query; } }
public class class_name { static Query createWithNextPageQuery(String nextPageQuery) { Query query = new Query(); query.nextPageQuery = nextPageQuery; if(nextPageQuery != null) { String nextPageParameters=nextPageQuery.substring(1, nextPageQuery.length()); Map<String,String> params=new LinkedHashMap<String,String>(); for(HttpParameter param : HttpParameter.decodeParameters(nextPageParameters)) { // Yes, we'll overwrite duplicate parameters, but we should not // get duplicate parameters from this endpoint. params.put(param.getName(), param.getValue()); // depends on control dependency: [for], data = [param] } if(params.containsKey("q")) query.setQuery(params.get("q")); if(params.containsKey("lang")) query.setLang(params.get("lang")); if(params.containsKey("locale")) query.setLocale(params.get("locale")); if(params.containsKey("max_id")) query.setMaxId(Long.parseLong(params.get("max_id"))); if(params.containsKey("count")) query.setCount(Integer.parseInt(params.get("count"))); if(params.containsKey("geocode")) { String[] parts=params.get("geocode").split(","); double latitude=Double.parseDouble(parts[0]); double longitude=Double.parseDouble(parts[1]); double radius=0.0; Query.Unit unit=null; String radiusstr=parts[2]; for(Query.Unit value : Query.Unit.values()) if(radiusstr.endsWith(value.name())) { radius = Double.parseDouble(radiusstr.substring(0, radiusstr.length()-2)); // depends on control dependency: [if], data = [none] unit = value; // depends on control dependency: [if], data = [none] break; } if(unit == null) throw new IllegalArgumentException("unrecognized geocode radius: "+radiusstr); query.setGeoCode(new GeoLocation(latitude, longitude), radius, unit); // depends on control dependency: [if], data = [none] } if(params.containsKey("result_type")) query.setResultType(Query.ResultType.valueOf(params.get("result_type"))); // We don't pull out since, until -- they get pushed into the query } return query; } }
public class class_name { public static boolean renameTo(final Path self, URI newPathName) { try { Files.move(self, Paths.get(newPathName)); return true; } catch (IOException e) { return false; } } }
public class class_name { public static boolean renameTo(final Path self, URI newPathName) { try { Files.move(self, Paths.get(newPathName)); // depends on control dependency: [try], data = [none] return true; // depends on control dependency: [try], data = [none] } catch (IOException e) { return false; } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void loadTableLocal(byte []tableKey, Result<TableKraken> result) { if (tableKey == null) { result.ok(null); return; } TableKraken table = getTableByKeyImpl(tableKey); if (table != null) { result.ok(table); return; } RowCursor cursor = _metaTable.getTableKelp().cursor(); cursor.setBytes(1, tableKey, 0); _metaTable.getTableKelp().get(cursor, result.then((v,r)->loadTableLocalImpl(tableKey, cursor, v, r))); } }
public class class_name { public void loadTableLocal(byte []tableKey, Result<TableKraken> result) { if (tableKey == null) { result.ok(null); // depends on control dependency: [if], data = [null)] return; // depends on control dependency: [if], data = [none] } TableKraken table = getTableByKeyImpl(tableKey); if (table != null) { result.ok(table); // depends on control dependency: [if], data = [(table] return; // depends on control dependency: [if], data = [none] } RowCursor cursor = _metaTable.getTableKelp().cursor(); cursor.setBytes(1, tableKey, 0); _metaTable.getTableKelp().get(cursor, result.then((v,r)->loadTableLocalImpl(tableKey, cursor, v, r))); } }
public class class_name { private static Object initializeEmbedded(EmbeddedMetadata embeddedMetadata, Object target) { try { // If instantiation of Entity instantiated the embeddable, we will // use the pre-initialized embedded object. Object embeddedObject = embeddedMetadata.getReadMethod().invoke(target); if (embeddedObject == null) { // Otherwise, we will instantiate the embedded object, which // could be a Builder embeddedObject = IntrospectionUtils.instantiate(embeddedMetadata); ConstructorMetadata constructorMetadata = embeddedMetadata.getConstructorMetadata(); if (constructorMetadata.isBuilderConstructionStrategy()) { // Build the Builder embeddedObject = constructorMetadata.getBuildMethodHandle().invoke(embeddedObject); } else { // TODO we should not be doing this?? There is no equivalent // of this for builder pattern embeddedMetadata.getWriteMethod().invoke(target, embeddedObject); } } return embeddedObject; } catch (Throwable t) { throw new EntityManagerException(t); } } }
public class class_name { private static Object initializeEmbedded(EmbeddedMetadata embeddedMetadata, Object target) { try { // If instantiation of Entity instantiated the embeddable, we will // use the pre-initialized embedded object. Object embeddedObject = embeddedMetadata.getReadMethod().invoke(target); if (embeddedObject == null) { // Otherwise, we will instantiate the embedded object, which // could be a Builder embeddedObject = IntrospectionUtils.instantiate(embeddedMetadata); // depends on control dependency: [if], data = [none] ConstructorMetadata constructorMetadata = embeddedMetadata.getConstructorMetadata(); if (constructorMetadata.isBuilderConstructionStrategy()) { // Build the Builder embeddedObject = constructorMetadata.getBuildMethodHandle().invoke(embeddedObject); // depends on control dependency: [if], data = [none] } else { // TODO we should not be doing this?? There is no equivalent // of this for builder pattern embeddedMetadata.getWriteMethod().invoke(target, embeddedObject); // depends on control dependency: [if], data = [none] } } return embeddedObject; // depends on control dependency: [try], data = [none] } catch (Throwable t) { throw new EntityManagerException(t); } // depends on control dependency: [catch], data = [none] } }
public class class_name { @SuppressWarnings("PrimitiveArrayArgumentToVariableArgMethod") private void visualizeItem(@NonNull final Item item, @NonNull final ItemViewHolder viewHolder) { viewHolder.iconImageView.setVisibility(iconCount > 0 ? View.VISIBLE : View.GONE); viewHolder.iconImageView.setEnabled(item.isEnabled()); if (item.getIcon() != null && item.getIcon() instanceof StateListDrawable) { StateListDrawable stateListDrawable = (StateListDrawable) item.getIcon(); try { int[] currentState = viewHolder.iconImageView.getDrawableState(); Method getStateDrawableIndex = StateListDrawable.class.getMethod("getStateDrawableIndex", int[].class); Method getStateDrawable = StateListDrawable.class.getMethod("getStateDrawable", int.class); int index = (int) getStateDrawableIndex.invoke(stateListDrawable, currentState); Drawable drawable = (Drawable) getStateDrawable.invoke(stateListDrawable, index); viewHolder.iconImageView.setImageDrawable(drawable); } catch (Exception e) { viewHolder.iconImageView.setImageDrawable(item.getIcon()); } } else { viewHolder.iconImageView.setImageDrawable(item.getIcon()); } viewHolder.titleTextView.setText(item.getTitle()); viewHolder.titleTextView.setEnabled(item.isEnabled()); if (getItemColor() != -1) { viewHolder.titleTextView.setTextColor(getItemColor()); } } }
public class class_name { @SuppressWarnings("PrimitiveArrayArgumentToVariableArgMethod") private void visualizeItem(@NonNull final Item item, @NonNull final ItemViewHolder viewHolder) { viewHolder.iconImageView.setVisibility(iconCount > 0 ? View.VISIBLE : View.GONE); viewHolder.iconImageView.setEnabled(item.isEnabled()); if (item.getIcon() != null && item.getIcon() instanceof StateListDrawable) { StateListDrawable stateListDrawable = (StateListDrawable) item.getIcon(); try { int[] currentState = viewHolder.iconImageView.getDrawableState(); Method getStateDrawableIndex = StateListDrawable.class.getMethod("getStateDrawableIndex", int[].class); Method getStateDrawable = StateListDrawable.class.getMethod("getStateDrawable", int.class); int index = (int) getStateDrawableIndex.invoke(stateListDrawable, currentState); Drawable drawable = (Drawable) getStateDrawable.invoke(stateListDrawable, index); viewHolder.iconImageView.setImageDrawable(drawable); // depends on control dependency: [try], data = [none] } catch (Exception e) { viewHolder.iconImageView.setImageDrawable(item.getIcon()); } // depends on control dependency: [catch], data = [none] } else { viewHolder.iconImageView.setImageDrawable(item.getIcon()); // depends on control dependency: [if], data = [(item.getIcon()] } viewHolder.titleTextView.setText(item.getTitle()); viewHolder.titleTextView.setEnabled(item.isEnabled()); if (getItemColor() != -1) { viewHolder.titleTextView.setTextColor(getItemColor()); // depends on control dependency: [if], data = [(getItemColor()] } } }
public class class_name { public void logRequest( @Nullable HttpRequest request, int statusCode, @Nullable String statusMessage) { boolean isSuccess = HttpStatusCodes.isSuccess(statusCode); if (!loggerDelegate.isSummaryLoggable(isSuccess) && !loggerDelegate.isDetailsLoggable(isSuccess)) { return; } // Populate the RequestInfo builder from the request. RequestInfo requestInfo = buildRequestInfo(request); // Populate the ResponseInfo builder from the response. ResponseInfo responseInfo = buildResponseInfo(request, statusCode, statusMessage); RemoteCallReturn.Builder remoteCallReturnBuilder = new RemoteCallReturn.Builder().withRequestInfo(requestInfo).withResponseInfo(responseInfo); if (!isSuccess) { remoteCallReturnBuilder.withException( new ReportException(String.format("%s: %s", statusCode, statusMessage))); } RemoteCallReturn remoteCallReturn = remoteCallReturnBuilder.build(); loggerDelegate.logRequestSummary(remoteCallReturn); loggerDelegate.logRequestDetails(remoteCallReturn); } }
public class class_name { public void logRequest( @Nullable HttpRequest request, int statusCode, @Nullable String statusMessage) { boolean isSuccess = HttpStatusCodes.isSuccess(statusCode); if (!loggerDelegate.isSummaryLoggable(isSuccess) && !loggerDelegate.isDetailsLoggable(isSuccess)) { return; // depends on control dependency: [if], data = [none] } // Populate the RequestInfo builder from the request. RequestInfo requestInfo = buildRequestInfo(request); // Populate the ResponseInfo builder from the response. ResponseInfo responseInfo = buildResponseInfo(request, statusCode, statusMessage); RemoteCallReturn.Builder remoteCallReturnBuilder = new RemoteCallReturn.Builder().withRequestInfo(requestInfo).withResponseInfo(responseInfo); if (!isSuccess) { remoteCallReturnBuilder.withException( new ReportException(String.format("%s: %s", statusCode, statusMessage))); // depends on control dependency: [if], data = [none] } RemoteCallReturn remoteCallReturn = remoteCallReturnBuilder.build(); loggerDelegate.logRequestSummary(remoteCallReturn); loggerDelegate.logRequestDetails(remoteCallReturn); } }
public class class_name { public void setFilePath(String filePath) { this.filePath = filePath; if (!this.filePath.endsWith(File.separator)) { this.filePath += File.separator; } } }
public class class_name { public void setFilePath(String filePath) { this.filePath = filePath; if (!this.filePath.endsWith(File.separator)) { this.filePath += File.separator; // depends on control dependency: [if], data = [none] } } }
public class class_name { private static Object readQueryString(String queryName, Class<?> paramType, Type genericType, Annotation[] paramAnns, Message m, String defaultValue, boolean decode) { MultivaluedMap<String, String> queryMap = new UriInfoImpl(m, null).getQueryParameters(decode); if ("".equals(queryName)) { return InjectionUtils.handleBean(paramType, paramAnns, queryMap, ParameterType.QUERY, m, false); } return InjectionUtils.createParameterObject(queryMap.get(queryName), paramType, genericType, paramAnns, defaultValue, false, ParameterType.QUERY, m); } }
public class class_name { private static Object readQueryString(String queryName, Class<?> paramType, Type genericType, Annotation[] paramAnns, Message m, String defaultValue, boolean decode) { MultivaluedMap<String, String> queryMap = new UriInfoImpl(m, null).getQueryParameters(decode); if ("".equals(queryName)) { return InjectionUtils.handleBean(paramType, paramAnns, queryMap, ParameterType.QUERY, m, false); // depends on control dependency: [if], data = [none] } return InjectionUtils.createParameterObject(queryMap.get(queryName), paramType, genericType, paramAnns, defaultValue, false, ParameterType.QUERY, m); } }
public class class_name { @Override public EClass getIfcRelContainedInSpatialStructure() { if (ifcRelContainedInSpatialStructureEClass == null) { ifcRelContainedInSpatialStructureEClass = (EClass) EPackage.Registry.INSTANCE .getEPackage(Ifc4Package.eNS_URI).getEClassifiers().get(542); } return ifcRelContainedInSpatialStructureEClass; } }
public class class_name { @Override public EClass getIfcRelContainedInSpatialStructure() { if (ifcRelContainedInSpatialStructureEClass == null) { ifcRelContainedInSpatialStructureEClass = (EClass) EPackage.Registry.INSTANCE .getEPackage(Ifc4Package.eNS_URI).getEClassifiers().get(542); // depends on control dependency: [if], data = [none] } return ifcRelContainedInSpatialStructureEClass; } }
public class class_name { public ManagementGate getOutputGate(final int index) { if (index < this.outputGates.size()) { return this.outputGates.get(index); } return null; } }
public class class_name { public ManagementGate getOutputGate(final int index) { if (index < this.outputGates.size()) { return this.outputGates.get(index); // depends on control dependency: [if], data = [(index] } return null; } }
public class class_name { public void setHeartBeatInterval(long heartBeatInterval) { if (heartBeatInterval < 100) return; if(logger.isLoggingEnabled(StackLogger.TRACE_DEBUG)) { logger.logDebug("Setting HeartBeatInterval from " + this.heartBeatInterval + " to " + heartBeatInterval); } this.heartBeatInterval = heartBeatInterval; // if(sipNodes.isEmpty()) { // logger.logInfo("Computing SIP Nodes to be sent to the LB"); // updateConnectorsAsSIPNode(); // } this.hearBeatTaskToRun.cancel(); this.hearBeatTaskToRun = new BalancerPingTimerTask(); this.heartBeatTimer.scheduleAtFixedRate(this.hearBeatTaskToRun, 0, this.heartBeatInterval); } }
public class class_name { public void setHeartBeatInterval(long heartBeatInterval) { if (heartBeatInterval < 100) return; if(logger.isLoggingEnabled(StackLogger.TRACE_DEBUG)) { logger.logDebug("Setting HeartBeatInterval from " + this.heartBeatInterval + " to " + heartBeatInterval); // depends on control dependency: [if], data = [none] } this.heartBeatInterval = heartBeatInterval; // if(sipNodes.isEmpty()) { // logger.logInfo("Computing SIP Nodes to be sent to the LB"); // updateConnectorsAsSIPNode(); // } this.hearBeatTaskToRun.cancel(); this.hearBeatTaskToRun = new BalancerPingTimerTask(); this.heartBeatTimer.scheduleAtFixedRate(this.hearBeatTaskToRun, 0, this.heartBeatInterval); } }
public class class_name { public static boolean haveVotersReachedPosition( final ClusterMember[] clusterMembers, final long position, final long leadershipTermId) { for (final ClusterMember member : clusterMembers) { if (member.vote != null && (member.logPosition < position || member.leadershipTermId != leadershipTermId)) { return false; } } return true; } }
public class class_name { public static boolean haveVotersReachedPosition( final ClusterMember[] clusterMembers, final long position, final long leadershipTermId) { for (final ClusterMember member : clusterMembers) { if (member.vote != null && (member.logPosition < position || member.leadershipTermId != leadershipTermId)) { return false; // depends on control dependency: [if], data = [none] } } return true; } }
public class class_name { protected int getResolutionIndex(double resolution) { if (layer instanceof TileBasedLayer) { return ((TileBasedLayer) layer).getTileConfiguration().getResolutionIndex(resolution); } return viewPort.getResolutionIndex(resolution); } }
public class class_name { protected int getResolutionIndex(double resolution) { if (layer instanceof TileBasedLayer) { return ((TileBasedLayer) layer).getTileConfiguration().getResolutionIndex(resolution); // depends on control dependency: [if], data = [none] } return viewPort.getResolutionIndex(resolution); } }
public class class_name { private static Map<String, String> dictionaryToMap( final Dictionary dictionary ) { final Map<String, String> map = new HashMap<String, String>(); try { // first try a shortcut if( dictionary instanceof Hashtable ) { map.putAll( (Hashtable<String, String>) dictionary ); } else { final Enumeration keys = dictionary.keys(); while( keys.hasMoreElements() ) { final String key = (String) keys.nextElement(); map.put( key, (String) dictionary.get( key ) ); } } return map; } catch( ClassCastException e ) { throw new IllegalArgumentException( "Dictionary entries must have String keys and values" ); } } }
public class class_name { private static Map<String, String> dictionaryToMap( final Dictionary dictionary ) { final Map<String, String> map = new HashMap<String, String>(); try { // first try a shortcut if( dictionary instanceof Hashtable ) { map.putAll( (Hashtable<String, String>) dictionary ); // depends on control dependency: [if], data = [none] } else { final Enumeration keys = dictionary.keys(); while( keys.hasMoreElements() ) { final String key = (String) keys.nextElement(); map.put( key, (String) dictionary.get( key ) ); // depends on control dependency: [while], data = [none] } } return map; // depends on control dependency: [try], data = [none] } catch( ClassCastException e ) { throw new IllegalArgumentException( "Dictionary entries must have String keys and values" ); } // depends on control dependency: [catch], data = [none] } }
public class class_name { @FFDCIgnore(IllegalStateException.class) private void updateMonitorService() { if ( !coveringPaths.isEmpty() ) { if ( service == null ) { try { // If we are shutting down, we want to generate the exception quickly. BundleContext bundleContext = getContainerFactoryHolder().getBundleContext(); // throws 'IllegalStateException' setServiceProperties(); service = bundleContext.registerService(FileMonitor.class, this, serviceProperties); // See comments on 'loadZipEntries' for why the entries must be loaded now. loadZipEntries(); } catch ( IllegalStateException e ) { // Ignore; the framework is shutting down. } } else { // Do nothing: There is already a service registration. } } else { if ( service != null ) { try { service.unregister(); } catch ( IllegalStateException e ) { // Ignore; framework is shutting down. } service = null; } else { // Do nothing: There is already no service registration. } } } }
public class class_name { @FFDCIgnore(IllegalStateException.class) private void updateMonitorService() { if ( !coveringPaths.isEmpty() ) { if ( service == null ) { try { // If we are shutting down, we want to generate the exception quickly. BundleContext bundleContext = getContainerFactoryHolder().getBundleContext(); // throws 'IllegalStateException' setServiceProperties(); // depends on control dependency: [try], data = [none] service = bundleContext.registerService(FileMonitor.class, this, serviceProperties); // depends on control dependency: [try], data = [none] // See comments on 'loadZipEntries' for why the entries must be loaded now. loadZipEntries(); // depends on control dependency: [try], data = [none] } catch ( IllegalStateException e ) { // Ignore; the framework is shutting down. } // depends on control dependency: [catch], data = [none] } else { // Do nothing: There is already a service registration. } } else { if ( service != null ) { try { service.unregister(); // depends on control dependency: [try], data = [none] } catch ( IllegalStateException e ) { // Ignore; framework is shutting down. } // depends on control dependency: [catch], data = [none] service = null; // depends on control dependency: [if], data = [none] } else { // Do nothing: There is already no service registration. } } } }
public class class_name { public List<PossibleState> bfs(int min) throws ModelException { List<PossibleState> bootStrap = new LinkedList<>(); TransitionTarget initial = model.getInitialTarget(); PossibleState initialState = new PossibleState(initial, fillInitialVariables()); bootStrap.add(initialState); while (bootStrap.size() < min) { PossibleState state = bootStrap.remove(0); TransitionTarget nextState = state.nextState; if (nextState.getId().equalsIgnoreCase("end")) { throw new ModelException("Could not achieve required bootstrap without reaching end state"); } //run every action in series List<Map<String, String>> product = new LinkedList<>(); product.add(new HashMap<>(state.variables)); OnEntry entry = nextState.getOnEntry(); List<Action> actions = entry.getActions(); for (Action action : actions) { for (CustomTagExtension tagExtension : tagExtensionList) { if (tagExtension.getTagActionClass().isInstance(action)) { product = tagExtension.pipelinePossibleStates(action, product); } } } //go through every transition and see which of the products are valid, adding them to the list List<Transition> transitions = nextState.getTransitionsList(); for (Transition transition : transitions) { String condition = transition.getCond(); TransitionTarget target = ((List<TransitionTarget>) transition.getTargets()).get(0); for (Map<String, String> p : product) { Boolean pass; if (condition == null) { pass = true; } else { //scrub the context clean so we may use it to evaluate transition conditional Context context = this.getRootContext(); context.reset(); //set up new context for (Map.Entry<String, String> e : p.entrySet()) { context.set(e.getKey(), e.getValue()); } //evaluate condition try { pass = (Boolean) this.getEvaluator().eval(context, condition); } catch (SCXMLExpressionException ex) { pass = false; } } //transition condition satisfied, add to bootstrap list if (pass) { PossibleState result = new PossibleState(target, p); bootStrap.add(result); } } } } return bootStrap; } }
public class class_name { public List<PossibleState> bfs(int min) throws ModelException { List<PossibleState> bootStrap = new LinkedList<>(); TransitionTarget initial = model.getInitialTarget(); PossibleState initialState = new PossibleState(initial, fillInitialVariables()); bootStrap.add(initialState); while (bootStrap.size() < min) { PossibleState state = bootStrap.remove(0); TransitionTarget nextState = state.nextState; if (nextState.getId().equalsIgnoreCase("end")) { throw new ModelException("Could not achieve required bootstrap without reaching end state"); } //run every action in series List<Map<String, String>> product = new LinkedList<>(); product.add(new HashMap<>(state.variables)); OnEntry entry = nextState.getOnEntry(); List<Action> actions = entry.getActions(); for (Action action : actions) { for (CustomTagExtension tagExtension : tagExtensionList) { if (tagExtension.getTagActionClass().isInstance(action)) { product = tagExtension.pipelinePossibleStates(action, product); // depends on control dependency: [if], data = [none] } } } //go through every transition and see which of the products are valid, adding them to the list List<Transition> transitions = nextState.getTransitionsList(); for (Transition transition : transitions) { String condition = transition.getCond(); TransitionTarget target = ((List<TransitionTarget>) transition.getTargets()).get(0); for (Map<String, String> p : product) { Boolean pass; if (condition == null) { pass = true; // depends on control dependency: [if], data = [none] } else { //scrub the context clean so we may use it to evaluate transition conditional Context context = this.getRootContext(); context.reset(); // depends on control dependency: [if], data = [none] //set up new context for (Map.Entry<String, String> e : p.entrySet()) { context.set(e.getKey(), e.getValue()); // depends on control dependency: [for], data = [e] } //evaluate condition try { pass = (Boolean) this.getEvaluator().eval(context, condition); // depends on control dependency: [try], data = [none] } catch (SCXMLExpressionException ex) { pass = false; } // depends on control dependency: [catch], data = [none] } //transition condition satisfied, add to bootstrap list if (pass) { PossibleState result = new PossibleState(target, p); bootStrap.add(result); // depends on control dependency: [if], data = [none] } } } } return bootStrap; } }
public class class_name { public void rollback() throws SQLException { cmdPrologue(); lock.lock(); try { if (inTransaction()) { executeQuery("ROLLBACK"); } } catch (Exception e) { /* eat exception */ } finally { lock.unlock(); } } }
public class class_name { public void rollback() throws SQLException { cmdPrologue(); lock.lock(); try { if (inTransaction()) { executeQuery("ROLLBACK"); // depends on control dependency: [if], data = [none] } } catch (Exception e) { /* eat exception */ } finally { lock.unlock(); } } }
public class class_name { public static void saveImage(Image image, File file, String imgFileFormat){ FileOutputStream fos = null; try { fos = new FileOutputStream(file); saveImage(image, fos, imgFileFormat); } catch (FileNotFoundException e) { throw new ImageSaverException(e); } finally { closeQuietly(fos); } } }
public class class_name { public static void saveImage(Image image, File file, String imgFileFormat){ FileOutputStream fos = null; try { fos = new FileOutputStream(file); // depends on control dependency: [try], data = [none] saveImage(image, fos, imgFileFormat); // depends on control dependency: [try], data = [none] } catch (FileNotFoundException e) { throw new ImageSaverException(e); } finally { // depends on control dependency: [catch], data = [none] closeQuietly(fos); } } }
public class class_name { private <S extends StaticSlot, R extends StaticRef> StaticRef findBestDeclToAdd( StaticSymbolTable<S, R> otherSymbolTable, S slot) { StaticRef decl = slot.getDeclaration(); if (isGoodRefToAdd(decl)) { return decl; } for (R ref : otherSymbolTable.getReferences(slot)) { if (isGoodRefToAdd(ref)) { return ref; } } return null; } }
public class class_name { private <S extends StaticSlot, R extends StaticRef> StaticRef findBestDeclToAdd( StaticSymbolTable<S, R> otherSymbolTable, S slot) { StaticRef decl = slot.getDeclaration(); if (isGoodRefToAdd(decl)) { return decl; // depends on control dependency: [if], data = [none] } for (R ref : otherSymbolTable.getReferences(slot)) { if (isGoodRefToAdd(ref)) { return ref; // depends on control dependency: [if], data = [none] } } return null; } }
public class class_name { public Result call(Route route, RequestContext context) throws Exception { // Is CORS required? String originHeader = context.request().getHeader(ORIGIN); if (originHeader != null) { originHeader = originHeader.toLowerCase(); } // If not Preflight if (route.getHttpMethod() != HttpMethod.OPTIONS) { return retrieveAndReturnResult(context, originHeader); } // OPTIONS route exists, don't use filter! (might manually implement // CORS?) if (!route.isUnbound()) { return context.proceed(); } // Try "Preflight" // Find existing methods for other routes Collection<Route> routes = router.getRoutes(); List<String> methods = new ArrayList<>(4); // expect POST PUT GET DELETE for (Route r : routes) { if (r.matches(r.getHttpMethod(), route.getUrl())) { methods.add(r.getHttpMethod().name()); } } // If there's none, proceed to 404 if (methods.isEmpty()) { return context.proceed(); } String requestMethod = context.request().getHeader(ACCESS_CONTROL_REQUEST_METHOD); // If it's not a CORS request, just proceed! if (originHeader == null || requestMethod == null) { return context.proceed(); } Result res = Results.ok(); // setup result if (!methods.contains(requestMethod.toUpperCase())) { res = Results.unauthorized("No such method for this route"); } Integer maxAge = getMaxAge(); if (maxAge != null) { res = res.with(ACCESS_CONTROL_MAX_AGE, String.valueOf(maxAge)); } // Otherwise we should be return OK with the appropriate headers. String exposedHeaders = getExposedHeadersHeader(); String allowedHosts = getAllowedHostsHeader(originHeader); String allowedMethods = Joiner.on(", ").join(methods); Result result = res.with(ACCESS_CONTROL_ALLOW_ORIGIN, allowedHosts) .with(ACCESS_CONTROL_ALLOW_METHODS, allowedMethods).with(ACCESS_CONTROL_ALLOW_HEADERS, exposedHeaders); if (getAllowCredentials()) { result = result.with(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); } return result; } }
public class class_name { public Result call(Route route, RequestContext context) throws Exception { // Is CORS required? String originHeader = context.request().getHeader(ORIGIN); if (originHeader != null) { originHeader = originHeader.toLowerCase(); } // If not Preflight if (route.getHttpMethod() != HttpMethod.OPTIONS) { return retrieveAndReturnResult(context, originHeader); } // OPTIONS route exists, don't use filter! (might manually implement // CORS?) if (!route.isUnbound()) { return context.proceed(); } // Try "Preflight" // Find existing methods for other routes Collection<Route> routes = router.getRoutes(); List<String> methods = new ArrayList<>(4); // expect POST PUT GET DELETE for (Route r : routes) { if (r.matches(r.getHttpMethod(), route.getUrl())) { methods.add(r.getHttpMethod().name()); // depends on control dependency: [if], data = [none] } } // If there's none, proceed to 404 if (methods.isEmpty()) { return context.proceed(); } String requestMethod = context.request().getHeader(ACCESS_CONTROL_REQUEST_METHOD); // If it's not a CORS request, just proceed! if (originHeader == null || requestMethod == null) { return context.proceed(); } Result res = Results.ok(); // setup result if (!methods.contains(requestMethod.toUpperCase())) { res = Results.unauthorized("No such method for this route"); } Integer maxAge = getMaxAge(); if (maxAge != null) { res = res.with(ACCESS_CONTROL_MAX_AGE, String.valueOf(maxAge)); } // Otherwise we should be return OK with the appropriate headers. String exposedHeaders = getExposedHeadersHeader(); String allowedHosts = getAllowedHostsHeader(originHeader); String allowedMethods = Joiner.on(", ").join(methods); Result result = res.with(ACCESS_CONTROL_ALLOW_ORIGIN, allowedHosts) .with(ACCESS_CONTROL_ALLOW_METHODS, allowedMethods).with(ACCESS_CONTROL_ALLOW_HEADERS, exposedHeaders); if (getAllowCredentials()) { result = result.with(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); } return result; } }
public class class_name { private String getScheduling(TaskType value) { String result = "fixed-work"; if (value != null && value == TaskType.FIXED_DURATION) { result = "fixed-duration"; } return (result); } }
public class class_name { private String getScheduling(TaskType value) { String result = "fixed-work"; if (value != null && value == TaskType.FIXED_DURATION) { result = "fixed-duration"; // depends on control dependency: [if], data = [none] } return (result); } }
public class class_name { public AnalyticModel getCalibratedModel(Set<ParameterObject> objectsToCalibrate) throws SolverException { final ParameterAggregation<ParameterObject> parameterAggregate = new ParameterAggregation<>(objectsToCalibrate); // Set solver parameters final RandomVariable[] initialParameters; // Apply parameter transformation to solver parameter space if(parameterTransformation != null) { initialParameters = parameterTransformation.getSolverParameter(parameterAggregate.getParameter()); } else { initialParameters = parameterAggregate.getParameter(); } final RandomVariable[] zeros = new RandomVariable[calibrationProducts.size()]; final RandomVariable[] ones = new RandomVariable[calibrationProducts.size()]; final RandomVariable[] lowerBound = new RandomVariable[initialParameters.length]; final RandomVariable[] upperBound = new RandomVariable[initialParameters.length]; java.util.Arrays.fill(zeros, new RandomVariableFromDoubleArray(0.0)); java.util.Arrays.fill(ones, new RandomVariableFromDoubleArray(1.0)); java.util.Arrays.fill(lowerBound, new RandomVariableFromDoubleArray(Double.NEGATIVE_INFINITY)); java.util.Arrays.fill(upperBound, new RandomVariableFromDoubleArray(Double.POSITIVE_INFINITY)); StochasticOptimizer.ObjectiveFunction objectiveFunction = new StochasticOptimizer.ObjectiveFunction() { @Override public void setValues(RandomVariable[] parameters, RandomVariable[] values) throws SolverException { RandomVariable[] modelParameters = parameters; try { if(parameterTransformation != null) { modelParameters = parameterTransformation.getParameter(parameters); // Copy back the parameter constrain to inform the optimizer System.arraycopy(parameterTransformation.getSolverParameter(modelParameters), 0, parameters, 0, parameters.length); } Map<ParameterObject, RandomVariable[]> curvesParameterPairs = parameterAggregate.getObjectsToModifyForParameter(modelParameters); AnalyticModel modelClone = model.getCloneForParameter(curvesParameterPairs); for(int i=0; i<calibrationProducts.size(); i++) { values[i] = calibrationProducts.get(i).getValue(evaluationTime, modelClone); } if(calibrationTargetValues != null) { for(int i=0; i<calibrationTargetValues.size(); i++) { values[i].sub(calibrationTargetValues.get(i)); } } } catch (CloneNotSupportedException e) { throw new SolverException(e); } } }; if(optimizerFactory == null) { int maxThreads = Math.min(2 * Math.max(Runtime.getRuntime().availableProcessors(), 1), initialParameters.length); optimizerFactory = new StochasticPathwiseOptimizerFactoryLevenbergMarquardt(maxIterations, calibrationAccuracy, maxThreads); } StochasticOptimizer optimizer = optimizerFactory.getOptimizer(objectiveFunction, initialParameters, lowerBound, upperBound, zeros); optimizer.run(); iterations = optimizer.getIterations(); RandomVariable[] bestParameters = optimizer.getBestFitParameters(); if(parameterTransformation != null) { bestParameters = parameterTransformation.getParameter(bestParameters); } AnalyticModel calibratedModel = null; try { Map<ParameterObject, RandomVariable[]> curvesParameterPairs = parameterAggregate.getObjectsToModifyForParameter(bestParameters); calibratedModel = model.getCloneForParameter(curvesParameterPairs); } catch (CloneNotSupportedException e) { throw new SolverException(e); } accuracy = 0.0; for(int i=0; i<calibrationProducts.size(); i++) { double error = calibrationProducts.get(i).getValue(evaluationTime, calibratedModel).getStandardDeviation(); if(calibrationTargetValues != null) { error -= calibrationTargetValues.get(i); } accuracy += error * error; } accuracy = Math.sqrt(accuracy/calibrationProducts.size()); return calibratedModel; } }
public class class_name { public AnalyticModel getCalibratedModel(Set<ParameterObject> objectsToCalibrate) throws SolverException { final ParameterAggregation<ParameterObject> parameterAggregate = new ParameterAggregation<>(objectsToCalibrate); // Set solver parameters final RandomVariable[] initialParameters; // Apply parameter transformation to solver parameter space if(parameterTransformation != null) { initialParameters = parameterTransformation.getSolverParameter(parameterAggregate.getParameter()); } else { initialParameters = parameterAggregate.getParameter(); } final RandomVariable[] zeros = new RandomVariable[calibrationProducts.size()]; final RandomVariable[] ones = new RandomVariable[calibrationProducts.size()]; final RandomVariable[] lowerBound = new RandomVariable[initialParameters.length]; final RandomVariable[] upperBound = new RandomVariable[initialParameters.length]; java.util.Arrays.fill(zeros, new RandomVariableFromDoubleArray(0.0)); java.util.Arrays.fill(ones, new RandomVariableFromDoubleArray(1.0)); java.util.Arrays.fill(lowerBound, new RandomVariableFromDoubleArray(Double.NEGATIVE_INFINITY)); java.util.Arrays.fill(upperBound, new RandomVariableFromDoubleArray(Double.POSITIVE_INFINITY)); StochasticOptimizer.ObjectiveFunction objectiveFunction = new StochasticOptimizer.ObjectiveFunction() { @Override public void setValues(RandomVariable[] parameters, RandomVariable[] values) throws SolverException { RandomVariable[] modelParameters = parameters; try { if(parameterTransformation != null) { modelParameters = parameterTransformation.getParameter(parameters); // depends on control dependency: [if], data = [none] // Copy back the parameter constrain to inform the optimizer System.arraycopy(parameterTransformation.getSolverParameter(modelParameters), 0, parameters, 0, parameters.length); // depends on control dependency: [if], data = [(parameterTransformation] } Map<ParameterObject, RandomVariable[]> curvesParameterPairs = parameterAggregate.getObjectsToModifyForParameter(modelParameters); AnalyticModel modelClone = model.getCloneForParameter(curvesParameterPairs); for(int i=0; i<calibrationProducts.size(); i++) { values[i] = calibrationProducts.get(i).getValue(evaluationTime, modelClone); // depends on control dependency: [for], data = [i] } if(calibrationTargetValues != null) { for(int i=0; i<calibrationTargetValues.size(); i++) { values[i].sub(calibrationTargetValues.get(i)); // depends on control dependency: [for], data = [i] } } } catch (CloneNotSupportedException e) { throw new SolverException(e); } } }; if(optimizerFactory == null) { int maxThreads = Math.min(2 * Math.max(Runtime.getRuntime().availableProcessors(), 1), initialParameters.length); optimizerFactory = new StochasticPathwiseOptimizerFactoryLevenbergMarquardt(maxIterations, calibrationAccuracy, maxThreads); } StochasticOptimizer optimizer = optimizerFactory.getOptimizer(objectiveFunction, initialParameters, lowerBound, upperBound, zeros); optimizer.run(); iterations = optimizer.getIterations(); RandomVariable[] bestParameters = optimizer.getBestFitParameters(); if(parameterTransformation != null) { bestParameters = parameterTransformation.getParameter(bestParameters); } AnalyticModel calibratedModel = null; try { Map<ParameterObject, RandomVariable[]> curvesParameterPairs = parameterAggregate.getObjectsToModifyForParameter(bestParameters); calibratedModel = model.getCloneForParameter(curvesParameterPairs); } catch (CloneNotSupportedException e) { throw new SolverException(e); } accuracy = 0.0; for(int i=0; i<calibrationProducts.size(); i++) { double error = calibrationProducts.get(i).getValue(evaluationTime, calibratedModel).getStandardDeviation(); if(calibrationTargetValues != null) { error -= calibrationTargetValues.get(i); } accuracy += error * error; } accuracy = Math.sqrt(accuracy/calibrationProducts.size()); return calibratedModel; } }
public class class_name { public PullResult pullFromRepository(Git git, String remote, String remoteBranch, String username, String password) { try { return git.pull() .setRemote(remote) .setRemoteBranchName(remoteBranch) .setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password)) .call(); } catch (GitAPIException e) { throw new IllegalStateException(e); } } }
public class class_name { public PullResult pullFromRepository(Git git, String remote, String remoteBranch, String username, String password) { try { return git.pull() .setRemote(remote) .setRemoteBranchName(remoteBranch) .setCredentialsProvider(new UsernamePasswordCredentialsProvider(username, password)) .call(); // depends on control dependency: [try], data = [none] } catch (GitAPIException e) { throw new IllegalStateException(e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private void addCacheControl(HttpAcceptSession session, File requestFile, String requestPath) { CacheControlHandler cacheControlHandler = urlCacheControlMap.computeIfAbsent(requestPath, path -> patterns.stream() .filter(patternCacheControl -> PatternMatcherUtils.caseInsensitiveMatch(requestPath, patternCacheControl.getPattern())) .findFirst() .map(patternCacheControl -> new CacheControlHandler(requestFile, patternCacheControl)) .orElse(null) ); if (cacheControlHandler != null) { addCacheControlHeader(session, requestFile, cacheControlHandler); } } }
public class class_name { private void addCacheControl(HttpAcceptSession session, File requestFile, String requestPath) { CacheControlHandler cacheControlHandler = urlCacheControlMap.computeIfAbsent(requestPath, path -> patterns.stream() .filter(patternCacheControl -> PatternMatcherUtils.caseInsensitiveMatch(requestPath, patternCacheControl.getPattern())) .findFirst() .map(patternCacheControl -> new CacheControlHandler(requestFile, patternCacheControl)) .orElse(null) ); if (cacheControlHandler != null) { addCacheControlHeader(session, requestFile, cacheControlHandler); // depends on control dependency: [if], data = [none] } } }
public class class_name { private void findLinesInRegion( List<LineSegment2D_F32> gridLines ) { List<Edgel> list = edgels.copyIntoList(null); int iterations = 0; // exit if not enough points or max iterations exceeded while( iterations++ < maxDetectLines) { if( !robustMatcher.process(list) ) break; // remove the found edges from the main list List<Edgel> matchSet = robustMatcher.getMatchSet(); // make sure the match set is large enough if( matchSet.size() < minInlierSize ) break; for( Edgel e : matchSet ) { list.remove(e); } gridLines.add(convertToLineSegment(matchSet, robustMatcher.getModelParameters())); } } }
public class class_name { private void findLinesInRegion( List<LineSegment2D_F32> gridLines ) { List<Edgel> list = edgels.copyIntoList(null); int iterations = 0; // exit if not enough points or max iterations exceeded while( iterations++ < maxDetectLines) { if( !robustMatcher.process(list) ) break; // remove the found edges from the main list List<Edgel> matchSet = robustMatcher.getMatchSet(); // make sure the match set is large enough if( matchSet.size() < minInlierSize ) break; for( Edgel e : matchSet ) { list.remove(e); // depends on control dependency: [for], data = [e] } gridLines.add(convertToLineSegment(matchSet, robustMatcher.getModelParameters())); // depends on control dependency: [while], data = [none] } } }
public class class_name { @SuppressWarnings("unchecked") public void addFieldMsg(String key, String value) { if (key == null) { return; } Map<String, String> fieldMsgs = null; // 字段错误信息 if (!this.statusInfo.containsKey(WebResponseConstant.MESSAGE_FIELD)) { fieldMsgs = new HashMap<String, String>(); this.statusInfo.put(WebResponseConstant.MESSAGE_FIELD, fieldMsgs); } fieldMsgs = (Map<String, String>) (this.statusInfo.get(WebResponseConstant.MESSAGE_FIELD)); fieldMsgs.put(key, value); } }
public class class_name { @SuppressWarnings("unchecked") public void addFieldMsg(String key, String value) { if (key == null) { return; // depends on control dependency: [if], data = [none] } Map<String, String> fieldMsgs = null; // 字段错误信息 if (!this.statusInfo.containsKey(WebResponseConstant.MESSAGE_FIELD)) { fieldMsgs = new HashMap<String, String>(); // depends on control dependency: [if], data = [none] this.statusInfo.put(WebResponseConstant.MESSAGE_FIELD, fieldMsgs); // depends on control dependency: [if], data = [none] } fieldMsgs = (Map<String, String>) (this.statusInfo.get(WebResponseConstant.MESSAGE_FIELD)); fieldMsgs.put(key, value); } }
public class class_name { private static Object evaluate(Object target, String expression) { try { if (target instanceof List) { List<?> list = (List<?>) target; int index = Integer.parseInt(expression); if (index < 0) { index += list.size(); } return list.get(index); } else { Method getter = findAccessor(target, expression); if (getter == null) { return null; } return getter.invoke(target); } } catch (IllegalAccessException exception) { throw new IllegalStateException("BOOM", exception); } catch (InvocationTargetException exception) { if (exception.getCause() instanceof RuntimeException) { throw (RuntimeException) exception.getCause(); } throw new RuntimeException("BOOM", exception); } } }
public class class_name { private static Object evaluate(Object target, String expression) { try { if (target instanceof List) { List<?> list = (List<?>) target; int index = Integer.parseInt(expression); if (index < 0) { index += list.size(); // depends on control dependency: [if], data = [none] } return list.get(index); // depends on control dependency: [if], data = [none] } else { Method getter = findAccessor(target, expression); if (getter == null) { return null; // depends on control dependency: [if], data = [none] } return getter.invoke(target); // depends on control dependency: [if], data = [none] } } catch (IllegalAccessException exception) { throw new IllegalStateException("BOOM", exception); } catch (InvocationTargetException exception) { // depends on control dependency: [catch], data = [none] if (exception.getCause() instanceof RuntimeException) { throw (RuntimeException) exception.getCause(); } throw new RuntimeException("BOOM", exception); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void marshall(AdminLinkProviderForUserRequest adminLinkProviderForUserRequest, ProtocolMarshaller protocolMarshaller) { if (adminLinkProviderForUserRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(adminLinkProviderForUserRequest.getUserPoolId(), USERPOOLID_BINDING); protocolMarshaller.marshall(adminLinkProviderForUserRequest.getDestinationUser(), DESTINATIONUSER_BINDING); protocolMarshaller.marshall(adminLinkProviderForUserRequest.getSourceUser(), SOURCEUSER_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(AdminLinkProviderForUserRequest adminLinkProviderForUserRequest, ProtocolMarshaller protocolMarshaller) { if (adminLinkProviderForUserRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(adminLinkProviderForUserRequest.getUserPoolId(), USERPOOLID_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(adminLinkProviderForUserRequest.getDestinationUser(), DESTINATIONUSER_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(adminLinkProviderForUserRequest.getSourceUser(), SOURCEUSER_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 static void main (String[] args) { // set up a throttle for 5 ops per 10 seconds Throttle throttle = new Throttle(5, 10000); // try doing one operation per second and we should hit the throttle on the sixth operation // and then kick in again on the eleventh, only to stop again on the fifteenth for (int i = 0; i < 20; i++) { System.out.println((i+1) + ". Throttle: " + throttle.throttleOp()); // pause for a sec try { Thread.sleep(1000L); } catch (InterruptedException ie) {} } } }
public class class_name { public static void main (String[] args) { // set up a throttle for 5 ops per 10 seconds Throttle throttle = new Throttle(5, 10000); // try doing one operation per second and we should hit the throttle on the sixth operation // and then kick in again on the eleventh, only to stop again on the fifteenth for (int i = 0; i < 20; i++) { System.out.println((i+1) + ". Throttle: " + throttle.throttleOp()); // depends on control dependency: [for], data = [i] // pause for a sec try { Thread.sleep(1000L); } // depends on control dependency: [try], data = [none] catch (InterruptedException ie) {} // depends on control dependency: [catch], data = [none] } } }
public class class_name { @Override public EEnum getPrimitiveEnum() { if (primitiveEnumEEnum == null) { primitiveEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(StorePackage.eNS_URI).getEClassifiers().get(66); } return primitiveEnumEEnum; } }
public class class_name { @Override public EEnum getPrimitiveEnum() { if (primitiveEnumEEnum == null) { primitiveEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(StorePackage.eNS_URI).getEClassifiers().get(66); // depends on control dependency: [if], data = [none] } return primitiveEnumEEnum; } }
public class class_name { @Override public void run() { try { Thread.sleep(WATCHER_INTERVAL); } catch (InterruptedException e) { LOG.error(Messages.get().container(Messages.ERR_UPLOAD_INTERRUPT_WATCH_DOG_1, m_listener.toString()), e); } if (m_listener != null) { if (((m_listener.getBytesRead() > 0) && (m_listener.getPercent() >= 100)) || m_listener.isCanceled()) { LOG.debug(Messages.get().container(Messages.LOG_UPLOAD_FINISHED_WATCHER_1, m_listener.toString())); m_listener = null; } else { if (isFrozen()) { m_listener.cancelUpload(new CmsUploadException( Messages.get().getBundle().key( Messages.ERR_UPLOAD_FROZEN_1, new Integer(CmsUploadBean.DEFAULT_UPLOAD_TIMEOUT / 1000)))); } else { run(); } } } } }
public class class_name { @Override public void run() { try { Thread.sleep(WATCHER_INTERVAL); // depends on control dependency: [try], data = [none] } catch (InterruptedException e) { LOG.error(Messages.get().container(Messages.ERR_UPLOAD_INTERRUPT_WATCH_DOG_1, m_listener.toString()), e); } // depends on control dependency: [catch], data = [none] if (m_listener != null) { if (((m_listener.getBytesRead() > 0) && (m_listener.getPercent() >= 100)) || m_listener.isCanceled()) { LOG.debug(Messages.get().container(Messages.LOG_UPLOAD_FINISHED_WATCHER_1, m_listener.toString())); // depends on control dependency: [if], data = [none] m_listener = null; // depends on control dependency: [if], data = [none] } else { if (isFrozen()) { m_listener.cancelUpload(new CmsUploadException( Messages.get().getBundle().key( Messages.ERR_UPLOAD_FROZEN_1, new Integer(CmsUploadBean.DEFAULT_UPLOAD_TIMEOUT / 1000)))); // depends on control dependency: [if], data = [none] } else { run(); // depends on control dependency: [if], data = [none] } } } } }
public class class_name { protected static String getBits(int b) { Formatter s = new Formatter(); for (int i = 31; i >= 0; i--) { if ((b & (1 << i)) != 0) { s.format("1"); } else { s.format("0"); } if (i % 8 == 0) { s.format("|"); } } return s.toString(); } }
public class class_name { protected static String getBits(int b) { Formatter s = new Formatter(); for (int i = 31; i >= 0; i--) { if ((b & (1 << i)) != 0) { s.format("1"); // depends on control dependency: [if], data = [none] } else { s.format("0"); // depends on control dependency: [if], data = [none] } if (i % 8 == 0) { s.format("|"); // depends on control dependency: [if], data = [none] } } return s.toString(); } }
public class class_name { private void definePackageForFindClass(final String name, final String packageName) { try { AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { @Override public Object run() { String path = name.replace('.', '/').concat(".class"); for (URL url : getURLs()) { try { if (url.getContent() instanceof JarFile) { JarFile jarFile = (JarFile) url.getContent(); // Check the jar entry data before needlessly creating the // manifest if (jarFile.getJarEntryData(path) != null && jarFile.getManifest() != null) { definePackage(packageName, jarFile.getManifest(), url); return null; } } } catch (IOException ex) { // Ignore } } return null; } }, AccessController.getContext()); } catch (java.security.PrivilegedActionException ex) { // Ignore } } }
public class class_name { private void definePackageForFindClass(final String name, final String packageName) { try { AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() { @Override public Object run() { String path = name.replace('.', '/').concat(".class"); for (URL url : getURLs()) { try { if (url.getContent() instanceof JarFile) { JarFile jarFile = (JarFile) url.getContent(); // Check the jar entry data before needlessly creating the // manifest if (jarFile.getJarEntryData(path) != null && jarFile.getManifest() != null) { definePackage(packageName, jarFile.getManifest(), url); // depends on control dependency: [if], data = [none] return null; // depends on control dependency: [if], data = [null] } } } catch (IOException ex) { // Ignore } // depends on control dependency: [catch], data = [none] } return null; } }, AccessController.getContext()); // depends on control dependency: [try], data = [none] } catch (java.security.PrivilegedActionException ex) { // Ignore } // depends on control dependency: [catch], data = [none] } }
public class class_name { protected <T> boolean handleRWMapper(ProviderInfo<T> em, Class<?> expectedType, Message m, Class<?> providerClass) { Class<?> mapperClass = ClassHelper.getRealClass(bus, em.getOldProvider()); Type[] types = null; if (m != null && MessageUtils.isTrue(m.getContextualProperty(IGNORE_TYPE_VARIABLES))) { types = new Type[] { mapperClass }; } else { types = getGenericInterfaces(mapperClass, expectedType); } for (Type t : types) { if (t instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) t; Type[] args = pt.getActualTypeArguments(); for (int i = 0; i < args.length; i++) { Type arg = args[i]; if (arg instanceof TypeVariable) { TypeVariable<?> var = (TypeVariable<?>) arg; Type[] bounds = var.getBounds(); boolean isResolved = false; for (int j = 0; j < bounds.length; j++) { Class<?> cls = InjectionUtils.getRawType(bounds[j]); if (cls != null && cls.isAssignableFrom(expectedType)) { isResolved = true; break; } } if (!isResolved) { return false; } return true; } Class<?> actualClass = InjectionUtils.getRawType(arg); if (actualClass == null) { continue; } if (expectedType.isArray() && !actualClass.isArray()) { expectedType = expectedType.getComponentType(); } if (actualClass.isAssignableFrom(expectedType) || actualClass == Object.class) { return true; } } } else if (t instanceof Class && providerClass.isAssignableFrom((Class<?>) t)) { return true; } } return false; } }
public class class_name { protected <T> boolean handleRWMapper(ProviderInfo<T> em, Class<?> expectedType, Message m, Class<?> providerClass) { Class<?> mapperClass = ClassHelper.getRealClass(bus, em.getOldProvider()); Type[] types = null; if (m != null && MessageUtils.isTrue(m.getContextualProperty(IGNORE_TYPE_VARIABLES))) { types = new Type[] { mapperClass }; // depends on control dependency: [if], data = [none] } else { types = getGenericInterfaces(mapperClass, expectedType); // depends on control dependency: [if], data = [(m] } for (Type t : types) { if (t instanceof ParameterizedType) { ParameterizedType pt = (ParameterizedType) t; Type[] args = pt.getActualTypeArguments(); for (int i = 0; i < args.length; i++) { Type arg = args[i]; if (arg instanceof TypeVariable) { TypeVariable<?> var = (TypeVariable<?>) arg; Type[] bounds = var.getBounds(); boolean isResolved = false; for (int j = 0; j < bounds.length; j++) { Class<?> cls = InjectionUtils.getRawType(bounds[j]); if (cls != null && cls.isAssignableFrom(expectedType)) { isResolved = true; // depends on control dependency: [if], data = [none] break; } } if (!isResolved) { return false; // depends on control dependency: [if], data = [none] } return true; // depends on control dependency: [if], data = [none] } Class<?> actualClass = InjectionUtils.getRawType(arg); if (actualClass == null) { continue; } if (expectedType.isArray() && !actualClass.isArray()) { expectedType = expectedType.getComponentType(); // depends on control dependency: [if], data = [none] } if (actualClass.isAssignableFrom(expectedType) || actualClass == Object.class) { return true; // depends on control dependency: [if], data = [none] } } } else if (t instanceof Class && providerClass.isAssignableFrom((Class<?>) t)) { return true; // depends on control dependency: [if], data = [none] } } return false; } }
public class class_name { public static CommerceDiscountUserSegmentRel toModel( CommerceDiscountUserSegmentRelSoap soapModel) { if (soapModel == null) { return null; } CommerceDiscountUserSegmentRel model = new CommerceDiscountUserSegmentRelImpl(); model.setCommerceDiscountUserSegmentRelId(soapModel.getCommerceDiscountUserSegmentRelId()); model.setGroupId(soapModel.getGroupId()); model.setCompanyId(soapModel.getCompanyId()); model.setUserId(soapModel.getUserId()); model.setUserName(soapModel.getUserName()); model.setCreateDate(soapModel.getCreateDate()); model.setModifiedDate(soapModel.getModifiedDate()); model.setCommerceDiscountId(soapModel.getCommerceDiscountId()); model.setCommerceUserSegmentEntryId(soapModel.getCommerceUserSegmentEntryId()); return model; } }
public class class_name { public static CommerceDiscountUserSegmentRel toModel( CommerceDiscountUserSegmentRelSoap soapModel) { if (soapModel == null) { return null; // depends on control dependency: [if], data = [none] } CommerceDiscountUserSegmentRel model = new CommerceDiscountUserSegmentRelImpl(); model.setCommerceDiscountUserSegmentRelId(soapModel.getCommerceDiscountUserSegmentRelId()); model.setGroupId(soapModel.getGroupId()); model.setCompanyId(soapModel.getCompanyId()); model.setUserId(soapModel.getUserId()); model.setUserName(soapModel.getUserName()); model.setCreateDate(soapModel.getCreateDate()); model.setModifiedDate(soapModel.getModifiedDate()); model.setCommerceDiscountId(soapModel.getCommerceDiscountId()); model.setCommerceUserSegmentEntryId(soapModel.getCommerceUserSegmentEntryId()); return model; } }
public class class_name { protected <RESULT> Task.Monitor<RESULT> runTask(ExecutorService executorService, final Task<RESULT> task, final Task.Callback<RESULT> callback) { final Task.Monitor<RESULT> monitor = new Task.Monitor(task, uiThreadRunner, callback); Future<Void> future = executorService.submit(new Callable<Void>() { @Override public Void call() throws Exception { if (monitor.getState() == Task.Monitor.State.CANCELED) { return null; } monitor.setState(Task.Monitor.State.STARTED); if (callback != null) { uiThreadRunner.post(new Runnable() { @Override public void run() { callback.onStarted(monitor); } }); } try { final RESULT result = task.execute(monitor); if (monitor.getState() != Task.Monitor.State.CANCELED) { monitor.setState(Task.Monitor.State.DONE); if (callback != null) { uiThreadRunner.post(new Runnable() { @Override public void run() { callback.onSuccess(result); callback.onFinally(); } }); } } } catch (final Exception e) { if (e instanceof MvcGraphException) { //Injection exception will always be thrown out since it's a development //time error uiThreadRunner.post(new Runnable() { @Override public void run() { throw new RuntimeException(e); } }); } boolean interruptedByCancel = false; if (e instanceof InterruptedException) { if (monitor.getState() == Task.Monitor.State.INTERRUPTED) { interruptedByCancel = true; } } //If the exception is an interruption caused by cancelling, then ignore it if (!interruptedByCancel) { monitor.setState(Task.Monitor.State.ERRED); if (callback != null) { uiThreadRunner.post(new Runnable() { @Override public void run() { try { callback.onException(e); } catch (Exception e) { throw new RuntimeException(e); } finally { callback.onFinally(); } } }); } else { uiThreadRunner.post(new Runnable() { @Override public void run() { throw new RuntimeException(e); } }); } } } return null; } }); monitor.setFuture(future); return monitor; } }
public class class_name { protected <RESULT> Task.Monitor<RESULT> runTask(ExecutorService executorService, final Task<RESULT> task, final Task.Callback<RESULT> callback) { final Task.Monitor<RESULT> monitor = new Task.Monitor(task, uiThreadRunner, callback); Future<Void> future = executorService.submit(new Callable<Void>() { @Override public Void call() throws Exception { if (monitor.getState() == Task.Monitor.State.CANCELED) { return null; } monitor.setState(Task.Monitor.State.STARTED); if (callback != null) { uiThreadRunner.post(new Runnable() { @Override public void run() { callback.onStarted(monitor); } }); } try { final RESULT result = task.execute(monitor); if (monitor.getState() != Task.Monitor.State.CANCELED) { monitor.setState(Task.Monitor.State.DONE); // depends on control dependency: [if], data = [none] if (callback != null) { uiThreadRunner.post(new Runnable() { @Override public void run() { callback.onSuccess(result); callback.onFinally(); } }); // depends on control dependency: [if], data = [none] } } } catch (final Exception e) { if (e instanceof MvcGraphException) { //Injection exception will always be thrown out since it's a development //time error uiThreadRunner.post(new Runnable() { @Override public void run() { throw new RuntimeException(e); } }); // depends on control dependency: [if], data = [none] } boolean interruptedByCancel = false; if (e instanceof InterruptedException) { if (monitor.getState() == Task.Monitor.State.INTERRUPTED) { interruptedByCancel = true; // depends on control dependency: [if], data = [none] } } //If the exception is an interruption caused by cancelling, then ignore it if (!interruptedByCancel) { monitor.setState(Task.Monitor.State.ERRED); // depends on control dependency: [if], data = [none] if (callback != null) { uiThreadRunner.post(new Runnable() { @Override public void run() { try { callback.onException(e); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new RuntimeException(e); } finally { // depends on control dependency: [catch], data = [none] callback.onFinally(); } } }); // depends on control dependency: [if], data = [none] } else { uiThreadRunner.post(new Runnable() { @Override public void run() { throw new RuntimeException(e); } }); // depends on control dependency: [if], data = [none] } } } return null; } }); monitor.setFuture(future); return monitor; } }
public class class_name { @Override public final Iterable<SubmitterDocument> findAll(final String filename) { final Query searchQuery = new Query(Criteria.where("filename").is(filename)); final List<SubmitterDocumentMongo> submitterDocumentsMongo = mongoTemplate.find(searchQuery, SubmitterDocumentMongo.class); if (submitterDocumentsMongo == null) { return null; } final List<SubmitterDocument> submitterDocuments = new ArrayList<>(); for (final SubmitterDocument submitterDocument : submitterDocumentsMongo) { final Submitter submitter = (Submitter) toObjConverter .createGedObject(null, submitterDocument); submitterDocument.setGedObject(submitter); submitterDocuments.add(submitterDocument); } return submitterDocuments; } }
public class class_name { @Override public final Iterable<SubmitterDocument> findAll(final String filename) { final Query searchQuery = new Query(Criteria.where("filename").is(filename)); final List<SubmitterDocumentMongo> submitterDocumentsMongo = mongoTemplate.find(searchQuery, SubmitterDocumentMongo.class); if (submitterDocumentsMongo == null) { return null; // depends on control dependency: [if], data = [none] } final List<SubmitterDocument> submitterDocuments = new ArrayList<>(); for (final SubmitterDocument submitterDocument : submitterDocumentsMongo) { final Submitter submitter = (Submitter) toObjConverter .createGedObject(null, submitterDocument); submitterDocument.setGedObject(submitter); // depends on control dependency: [for], data = [submitterDocument] submitterDocuments.add(submitterDocument); // depends on control dependency: [for], data = [submitterDocument] } return submitterDocuments; } }
public class class_name { void unregisterSessionIfNeeded(HttpSession session) { if (session != null) { try { session.getCreationTime(); // https://issues.jenkins-ci.org/browse/JENKINS-20532 // https://bugs.eclipse.org/bugs/show_bug.cgi?id=413019 session.getLastAccessedTime(); } catch (final IllegalStateException e) { // session.getCreationTime() lance IllegalStateException si la session est invalidée synchronized (session) { sessionDestroyed(new HttpSessionEvent(session)); } } } } }
public class class_name { void unregisterSessionIfNeeded(HttpSession session) { if (session != null) { try { session.getCreationTime(); // depends on control dependency: [try], data = [none] // https://issues.jenkins-ci.org/browse/JENKINS-20532 // https://bugs.eclipse.org/bugs/show_bug.cgi?id=413019 session.getLastAccessedTime(); // depends on control dependency: [try], data = [none] } catch (final IllegalStateException e) { // session.getCreationTime() lance IllegalStateException si la session est invalidée synchronized (session) { sessionDestroyed(new HttpSessionEvent(session)); } } // depends on control dependency: [catch], data = [none] } } }
public class class_name { @Override public final LedgerDetail retrieveDetail( final Map<String, Object> pAddParam, final Account pAccount, final Date pDate1, final Date pDate2, final String pSubaccId, final LedgerPrevious ledgerPrevious) throws Exception { LedgerDetail result = new LedgerDetail(); if (this.queryDetail == null) { String flName = "/" + "accounting" + "/" + "ledger" //+ "/" + "queryDetail.sql";fast query cause error due changing subacc name + "/" + "queryDetailSl.sql"; this.queryDetail = loadString(flName); } String query = queryDetail.replace(":DATE1", String.valueOf(pDate1.getTime())); query = query.replace(":DATE2", String.valueOf(pDate2.getTime())); query = query.replace(":ACCID", "'" + pAccount.getItsId() + "'"); String whereSubaccDebit = ""; String whereSubaccCredit = ""; if (pSubaccId != null && pSubaccId.length() > 0) { whereSubaccDebit = " and SUBACCDEBITID='" + pSubaccId + "'"; whereSubaccCredit = " and SUBACCCREDITID='" + pSubaccId + "'"; } query = query.replace(":SUBACCDEBIT", whereSubaccDebit); query = query.replace(":SUBACCCREDIT", whereSubaccCredit); IRecordSet<RS> recordSet = null; try { recordSet = getSrvDatabase().retrieveRecords(query); if (recordSet.moveToFirst()) { do { LedgerDetailLine ldl = new LedgerDetailLine(); ldl.setItsDate(new Date(recordSet.getLong("ITSDATE"))); ldl.setSourceId(recordSet.getLong("SOURCEID")); ldl.setSourceType(recordSet.getInteger("SOURCETYPE")); ldl.setDescription(recordSet.getString("DESCRIPTION")); ldl.setSubaccName(recordSet.getString("SUBACC")); ldl.setCorrAccName(recordSet.getString("CORACCNAME")); ldl.setCorrSubaccName(recordSet.getString("CORSUBACC")); ldl.setCorrAccNumber(recordSet.getString("CORACCNUMBER")); Boolean isDebit = recordSet.getInteger("ISDEBIT") == 1; if (isDebit) { ldl.setDebit(BigDecimal .valueOf(recordSet.getDouble("ITSTOTAL")) .setScale(getSrvAccSettings().lazyGetAccSettings(pAddParam) .getCostPrecision(), getSrvAccSettings() .lazyGetAccSettings(pAddParam).getRoundingMode())); } else { ldl.setCredit(BigDecimal .valueOf(recordSet.getDouble("ITSTOTAL")) .setScale(getSrvAccSettings().lazyGetAccSettings(pAddParam) .getCostPrecision(), getSrvAccSettings() .lazyGetAccSettings(pAddParam).getRoundingMode())); } result.setDebitAcc(result.getDebitAcc().add(ldl.getDebit())); result.setCreditAcc(result.getCreditAcc().add(ldl.getCredit())); if (result.getSubaccDebitTotal().get(ldl.getSubaccName()) == null) { result.getSubaccDebitTotal() .put(ldl.getSubaccName(), BigDecimal.ZERO); result.getSubaccCreditTotal() .put(ldl.getSubaccName(), BigDecimal.ZERO); } result.getSubaccDebitTotal().put(ldl.getSubaccName(), result.getSubaccDebitTotal().get(ldl.getSubaccName()) .add(ldl.getDebit())); result.getSubaccCreditTotal().put(ldl.getSubaccName(), result.getSubaccCreditTotal().get(ldl.getSubaccName()) .add(ldl.getCredit())); if (pAccount.getNormalBalanceType() == ENormalBalanceType.DEBIT) { result.getSubaccBalanceTotal().put(ldl.getSubaccName(), result.getSubaccDebitTotal().get(ldl.getSubaccName()) .subtract(result.getSubaccCreditTotal() .get(ldl.getSubaccName()))); result.setBalanceAcc(result.getDebitAcc() .subtract(result.getCreditAcc())); ldl.setBalance(result.getBalanceAcc()); ldl.setBalanceSubacc(result.getSubaccBalanceTotal(). get(ldl.getSubaccName())); } else { result.getSubaccBalanceTotal().put(ldl.getSubaccName(), result.getSubaccCreditTotal().get(ldl.getSubaccName()) .subtract(result.getSubaccDebitTotal() .get(ldl.getSubaccName()))); result.setBalanceAcc(result.getCreditAcc() .subtract(result.getDebitAcc())); ldl.setBalance(result.getBalanceAcc()); ldl.setBalanceSubacc(result.getSubaccBalanceTotal(). get(ldl.getSubaccName())); } result.getItsLines().add(ldl); } while (recordSet.moveToNext()); } } finally { if (recordSet != null) { recordSet.close(); } } for (String subaccName : result.getSubaccDebitTotal().keySet()) { if (ledgerPrevious.getLinesMap().get(subaccName) == null) { ledgerPrevious.getLinesMap().put(subaccName, new LedgerPreviousLine()); } } return result; } }
public class class_name { @Override public final LedgerDetail retrieveDetail( final Map<String, Object> pAddParam, final Account pAccount, final Date pDate1, final Date pDate2, final String pSubaccId, final LedgerPrevious ledgerPrevious) throws Exception { LedgerDetail result = new LedgerDetail(); if (this.queryDetail == null) { String flName = "/" + "accounting" + "/" + "ledger" //+ "/" + "queryDetail.sql";fast query cause error due changing subacc name + "/" + "queryDetailSl.sql"; this.queryDetail = loadString(flName); } String query = queryDetail.replace(":DATE1", String.valueOf(pDate1.getTime())); query = query.replace(":DATE2", String.valueOf(pDate2.getTime())); query = query.replace(":ACCID", "'" + pAccount.getItsId() + "'"); String whereSubaccDebit = ""; String whereSubaccCredit = ""; if (pSubaccId != null && pSubaccId.length() > 0) { whereSubaccDebit = " and SUBACCDEBITID='" + pSubaccId + "'"; whereSubaccCredit = " and SUBACCCREDITID='" + pSubaccId + "'"; } query = query.replace(":SUBACCDEBIT", whereSubaccDebit); query = query.replace(":SUBACCCREDIT", whereSubaccCredit); IRecordSet<RS> recordSet = null; try { recordSet = getSrvDatabase().retrieveRecords(query); if (recordSet.moveToFirst()) { do { LedgerDetailLine ldl = new LedgerDetailLine(); ldl.setItsDate(new Date(recordSet.getLong("ITSDATE"))); ldl.setSourceId(recordSet.getLong("SOURCEID")); ldl.setSourceType(recordSet.getInteger("SOURCETYPE")); ldl.setDescription(recordSet.getString("DESCRIPTION")); ldl.setSubaccName(recordSet.getString("SUBACC")); ldl.setCorrAccName(recordSet.getString("CORACCNAME")); ldl.setCorrSubaccName(recordSet.getString("CORSUBACC")); ldl.setCorrAccNumber(recordSet.getString("CORACCNUMBER")); Boolean isDebit = recordSet.getInteger("ISDEBIT") == 1; if (isDebit) { ldl.setDebit(BigDecimal .valueOf(recordSet.getDouble("ITSTOTAL")) .setScale(getSrvAccSettings().lazyGetAccSettings(pAddParam) .getCostPrecision(), getSrvAccSettings() .lazyGetAccSettings(pAddParam).getRoundingMode())); // depends on control dependency: [if], data = [none] } else { ldl.setCredit(BigDecimal .valueOf(recordSet.getDouble("ITSTOTAL")) .setScale(getSrvAccSettings().lazyGetAccSettings(pAddParam) .getCostPrecision(), getSrvAccSettings() .lazyGetAccSettings(pAddParam).getRoundingMode())); // depends on control dependency: [if], data = [none] } result.setDebitAcc(result.getDebitAcc().add(ldl.getDebit())); result.setCreditAcc(result.getCreditAcc().add(ldl.getCredit())); if (result.getSubaccDebitTotal().get(ldl.getSubaccName()) == null) { result.getSubaccDebitTotal() .put(ldl.getSubaccName(), BigDecimal.ZERO); // depends on control dependency: [if], data = [none] result.getSubaccCreditTotal() .put(ldl.getSubaccName(), BigDecimal.ZERO); // depends on control dependency: [if], data = [none] } result.getSubaccDebitTotal().put(ldl.getSubaccName(), result.getSubaccDebitTotal().get(ldl.getSubaccName()) .add(ldl.getDebit())); result.getSubaccCreditTotal().put(ldl.getSubaccName(), result.getSubaccCreditTotal().get(ldl.getSubaccName()) .add(ldl.getCredit())); if (pAccount.getNormalBalanceType() == ENormalBalanceType.DEBIT) { result.getSubaccBalanceTotal().put(ldl.getSubaccName(), result.getSubaccDebitTotal().get(ldl.getSubaccName()) .subtract(result.getSubaccCreditTotal() .get(ldl.getSubaccName()))); // depends on control dependency: [if], data = [none] result.setBalanceAcc(result.getDebitAcc() .subtract(result.getCreditAcc())); // depends on control dependency: [if], data = [none] ldl.setBalance(result.getBalanceAcc()); // depends on control dependency: [if], data = [none] ldl.setBalanceSubacc(result.getSubaccBalanceTotal(). get(ldl.getSubaccName())); // depends on control dependency: [if], data = [none] } else { result.getSubaccBalanceTotal().put(ldl.getSubaccName(), result.getSubaccCreditTotal().get(ldl.getSubaccName()) .subtract(result.getSubaccDebitTotal() .get(ldl.getSubaccName()))); // depends on control dependency: [if], data = [none] result.setBalanceAcc(result.getCreditAcc() .subtract(result.getDebitAcc())); // depends on control dependency: [if], data = [none] ldl.setBalance(result.getBalanceAcc()); // depends on control dependency: [if], data = [none] ldl.setBalanceSubacc(result.getSubaccBalanceTotal(). get(ldl.getSubaccName())); // depends on control dependency: [if], data = [none] } result.getItsLines().add(ldl); } while (recordSet.moveToNext()); } } finally { if (recordSet != null) { recordSet.close(); // depends on control dependency: [if], data = [none] } } for (String subaccName : result.getSubaccDebitTotal().keySet()) { if (ledgerPrevious.getLinesMap().get(subaccName) == null) { ledgerPrevious.getLinesMap().put(subaccName, new LedgerPreviousLine()); } } return result; } }
public class class_name { public static String toVerb(String string) { if (string == null) { return string; } if (string.length() == 1) { return string.toLowerCase(); } return string.substring(0, 1).toLowerCase() + string.substring(1, string.length()); } }
public class class_name { public static String toVerb(String string) { if (string == null) { return string; // depends on control dependency: [if], data = [none] } if (string.length() == 1) { return string.toLowerCase(); // depends on control dependency: [if], data = [none] } return string.substring(0, 1).toLowerCase() + string.substring(1, string.length()); } }
public class class_name { public int next(int ele) { int idx, bit, val; idx = ele >> SHIFT; bit = ele & MASK; val = data[idx] >>> bit; do { val >>>= 1; bit++; if (val == 0) { idx++; if (idx == data.length) { return -1; } val = data[idx]; bit = 0; } } while ((val & 1) == 0); return (idx << SHIFT) + bit; } }
public class class_name { public int next(int ele) { int idx, bit, val; idx = ele >> SHIFT; bit = ele & MASK; val = data[idx] >>> bit; do { val >>>= 1; bit++; if (val == 0) { idx++; // depends on control dependency: [if], data = [none] if (idx == data.length) { return -1; // depends on control dependency: [if], data = [none] } val = data[idx]; // depends on control dependency: [if], data = [none] bit = 0; // depends on control dependency: [if], data = [none] } } while ((val & 1) == 0); return (idx << SHIFT) + bit; } }
public class class_name { public static Optional<StartMusicRequest> createStartMusicRequest(Identification source, Identification target, Playlist playlist, boolean isUsingJava) { if (target.equals(source)) return Optional.empty(); try { StartMusicRequest request = new StartMusicRequest(source, isUsingJava); request.addResource(new SelectorResource(source, target)); if (playlist != null) request.addResource(new PlaylistResource(target, playlist, source)); return Optional.of(request); } catch (IllegalArgumentException e) { return Optional.empty(); } } }
public class class_name { public static Optional<StartMusicRequest> createStartMusicRequest(Identification source, Identification target, Playlist playlist, boolean isUsingJava) { if (target.equals(source)) return Optional.empty(); try { StartMusicRequest request = new StartMusicRequest(source, isUsingJava); request.addResource(new SelectorResource(source, target)); // depends on control dependency: [try], data = [none] if (playlist != null) request.addResource(new PlaylistResource(target, playlist, source)); return Optional.of(request); // depends on control dependency: [try], data = [none] } catch (IllegalArgumentException e) { return Optional.empty(); } // depends on control dependency: [catch], data = [none] } }
public class class_name { @Override public void shutdown() { // delay a little bit in case an added job is still taking it's time getting started right // before shutdown is called. try { // System.out.println("waiting..."); Thread.sleep(100); } catch (Exception ignore) { } if (shuttingDown || closed) { return; } shuttingDown = true; logger.info("Scheduler shutting down..."); standby(); this.quartzSchedulerThread.halt(); notifySchedulerListenersShuttingdown(); // notify Jobs, so they can gracefully shutdown List<JobExecutionContext> jobs = getCurrentlyExecutingJobs(); for (JobExecutionContext job : jobs) { if (job.getJobInstance() instanceof InterruptableJob) { try { ((InterruptableJob) job.getJobInstance()).interrupt(); } catch (Throwable e) { // do nothing, this was just a courtesy effort logger.warn( "Encountered error when interrupting job {} during shutdown: {}", job.getJobDetail().getName(), e); } } } logger.info("Threadpool shutting down..."); quartzSchedulerResources.getThreadPool().shutdown(); // Scheduler thread may have be waiting for the fire time of an acquired // trigger and need time to release the trigger once halted, so make sure // the thread is dead before continuing to shutdown the job store. try { this.quartzSchedulerThread.join(); } catch (InterruptedException ignore) { } closed = true; shutdownPlugins(); notifySchedulerListenersShutdown(); logger.info("Scheduler shutdown complete."); } }
public class class_name { @Override public void shutdown() { // delay a little bit in case an added job is still taking it's time getting started right // before shutdown is called. try { // System.out.println("waiting..."); Thread.sleep(100); // depends on control dependency: [try], data = [none] } catch (Exception ignore) { } // depends on control dependency: [catch], data = [none] if (shuttingDown || closed) { return; // depends on control dependency: [if], data = [none] } shuttingDown = true; logger.info("Scheduler shutting down..."); standby(); this.quartzSchedulerThread.halt(); notifySchedulerListenersShuttingdown(); // notify Jobs, so they can gracefully shutdown List<JobExecutionContext> jobs = getCurrentlyExecutingJobs(); for (JobExecutionContext job : jobs) { if (job.getJobInstance() instanceof InterruptableJob) { try { ((InterruptableJob) job.getJobInstance()).interrupt(); // depends on control dependency: [try], data = [none] } catch (Throwable e) { // do nothing, this was just a courtesy effort logger.warn( "Encountered error when interrupting job {} during shutdown: {}", job.getJobDetail().getName(), e); } // depends on control dependency: [catch], data = [none] } } logger.info("Threadpool shutting down..."); quartzSchedulerResources.getThreadPool().shutdown(); // Scheduler thread may have be waiting for the fire time of an acquired // trigger and need time to release the trigger once halted, so make sure // the thread is dead before continuing to shutdown the job store. try { this.quartzSchedulerThread.join(); // depends on control dependency: [try], data = [none] } catch (InterruptedException ignore) { } // depends on control dependency: [catch], data = [none] closed = true; shutdownPlugins(); notifySchedulerListenersShutdown(); logger.info("Scheduler shutdown complete."); } }
public class class_name { Set<PolicyNodeImpl> getPolicyNodesExpected(int depth, String expectedOID, boolean matchAny) { if (expectedOID.equals(ANY_POLICY)) { return getPolicyNodes(depth); } else { return getPolicyNodesExpectedHelper(depth, expectedOID, matchAny); } } }
public class class_name { Set<PolicyNodeImpl> getPolicyNodesExpected(int depth, String expectedOID, boolean matchAny) { if (expectedOID.equals(ANY_POLICY)) { return getPolicyNodes(depth); // depends on control dependency: [if], data = [none] } else { return getPolicyNodesExpectedHelper(depth, expectedOID, matchAny); // depends on control dependency: [if], data = [none] } } }
public class class_name { public final Parser<String> source() { return new Parser<String>() { @Override boolean apply(ParseContext ctxt) { int begin = ctxt.getIndex(); if (!Parser.this.apply(ctxt)) { return false; } ctxt.result = ctxt.source.subSequence(begin, ctxt.getIndex()).toString(); return true; } @Override public String toString() { return "source"; } }; } }
public class class_name { public final Parser<String> source() { return new Parser<String>() { @Override boolean apply(ParseContext ctxt) { int begin = ctxt.getIndex(); if (!Parser.this.apply(ctxt)) { return false; // depends on control dependency: [if], data = [none] } ctxt.result = ctxt.source.subSequence(begin, ctxt.getIndex()).toString(); return true; } @Override public String toString() { return "source"; } }; } }
public class class_name { private static String getRootPath(final String locationPattern) { int rootDirEnd = locationPattern.length(); while (AntPathMatcher.isPattern(locationPattern.substring(0, rootDirEnd))) { rootDirEnd = locationPattern.lastIndexOf('/', rootDirEnd - 2) + 1; } return locationPattern.substring(0, rootDirEnd); } }
public class class_name { private static String getRootPath(final String locationPattern) { int rootDirEnd = locationPattern.length(); while (AntPathMatcher.isPattern(locationPattern.substring(0, rootDirEnd))) { rootDirEnd = locationPattern.lastIndexOf('/', rootDirEnd - 2) + 1; // depends on control dependency: [while], data = [none] } return locationPattern.substring(0, rootDirEnd); } }
public class class_name { public void onStartServiceEvent( javax.slee.serviceactivity.ServiceStartedEvent event, ActivityContextInterface aci) { try { XDMClientChildSbbLocalObject child = (XDMClientChildSbbLocalObject) this .getXDMClientChildSbbChildRelation().create(ChildRelationExt.DEFAULT_CHILD_NAME); String[] resourceURIS = new String[] { getDocumentSelector() }; // String aserted = null; // subscribe to changes - before doc is created. // assume we are bound to the same localhost. // from/to must match child.subscribe(user, user, 60, resourceURIS); } catch (Exception e) { tracer.severe("failed to subscribe changes to doc", e); } } }
public class class_name { public void onStartServiceEvent( javax.slee.serviceactivity.ServiceStartedEvent event, ActivityContextInterface aci) { try { XDMClientChildSbbLocalObject child = (XDMClientChildSbbLocalObject) this .getXDMClientChildSbbChildRelation().create(ChildRelationExt.DEFAULT_CHILD_NAME); String[] resourceURIS = new String[] { getDocumentSelector() }; // String aserted = null; // subscribe to changes - before doc is created. // assume we are bound to the same localhost. // from/to must match child.subscribe(user, user, 60, resourceURIS); // depends on control dependency: [try], data = [none] } catch (Exception e) { tracer.severe("failed to subscribe changes to doc", e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { void mapOut(String out, Object comp, String comp_out) { if (comp == ca.getComponent()) { throw new ComponentException("cannot connect 'Out' with itself for " + out); } ComponentAccess ac_dest = lookup(comp); FieldAccess destAccess = (FieldAccess) ac_dest.output(comp_out); FieldAccess srcAccess = (FieldAccess) ca.output(out); checkFA(destAccess, comp, comp_out); checkFA(srcAccess, ca.getComponent(), out); FieldContent data = srcAccess.getData(); data.tagLeaf(); data.tagOut(); destAccess.setData(data); dataSet.add(data); if (log.isLoggable(Level.CONFIG)) { log.log(Level.CONFIG, String.format("@Out(%s) -> @Out(%s)", srcAccess, destAccess)); } // ens.fireMapOut(srcAccess, destAccess); } }
public class class_name { void mapOut(String out, Object comp, String comp_out) { if (comp == ca.getComponent()) { throw new ComponentException("cannot connect 'Out' with itself for " + out); } ComponentAccess ac_dest = lookup(comp); FieldAccess destAccess = (FieldAccess) ac_dest.output(comp_out); FieldAccess srcAccess = (FieldAccess) ca.output(out); checkFA(destAccess, comp, comp_out); checkFA(srcAccess, ca.getComponent(), out); FieldContent data = srcAccess.getData(); data.tagLeaf(); data.tagOut(); destAccess.setData(data); dataSet.add(data); if (log.isLoggable(Level.CONFIG)) { log.log(Level.CONFIG, String.format("@Out(%s) -> @Out(%s)", srcAccess, destAccess)); // depends on control dependency: [if], data = [none] } // ens.fireMapOut(srcAccess, destAccess); } }
public class class_name { public void putAll (IntMap<V> t) { // if we can, avoid creating Integer objects while copying for (IntEntry<V> entry : t.intEntrySet()) { put(entry.getIntKey(), entry.getValue()); } } }
public class class_name { public void putAll (IntMap<V> t) { // if we can, avoid creating Integer objects while copying for (IntEntry<V> entry : t.intEntrySet()) { put(entry.getIntKey(), entry.getValue()); // depends on control dependency: [for], data = [entry] } } }
public class class_name { @SuppressWarnings("unchecked") @FFDCIgnore(Exception.class) public static String[] parseStringArray(Object configAlias, String propertyKey, Object obj, String[] defaultValue) { final String[] emptyArray = new String[0]; if (obj != null) { try { if (obj instanceof String[]) { return (String[]) obj; } else if (obj instanceof String) { String commaList = (String) obj; // split the string, consuming/removing whitespace return commaList.split("\\s*,\\s*"); } else if (obj instanceof Collection) { return ((Collection<String>) obj).toArray(emptyArray); } } catch (Exception e) { Tr.warning(tc, "invalidStringArray", configAlias, propertyKey, obj); throw new IllegalArgumentException("String array value could not be parsed: key=" + propertyKey + ", value=" + obj, e); } // unknown type Tr.warning(tc, "invalidStringArray", configAlias, propertyKey, obj); throw new IllegalArgumentException("String array value could not be parsed: key=" + propertyKey + ", value=" + obj); } return defaultValue; } }
public class class_name { @SuppressWarnings("unchecked") @FFDCIgnore(Exception.class) public static String[] parseStringArray(Object configAlias, String propertyKey, Object obj, String[] defaultValue) { final String[] emptyArray = new String[0]; if (obj != null) { try { if (obj instanceof String[]) { return (String[]) obj; // depends on control dependency: [if], data = [none] } else if (obj instanceof String) { String commaList = (String) obj; // split the string, consuming/removing whitespace return commaList.split("\\s*,\\s*"); // depends on control dependency: [if], data = [none] } else if (obj instanceof Collection) { return ((Collection<String>) obj).toArray(emptyArray); // depends on control dependency: [if], data = [none] } } catch (Exception e) { Tr.warning(tc, "invalidStringArray", configAlias, propertyKey, obj); throw new IllegalArgumentException("String array value could not be parsed: key=" + propertyKey + ", value=" + obj, e); } // depends on control dependency: [catch], data = [none] // unknown type Tr.warning(tc, "invalidStringArray", configAlias, propertyKey, obj); // depends on control dependency: [if], data = [none] throw new IllegalArgumentException("String array value could not be parsed: key=" + propertyKey + ", value=" + obj); } return defaultValue; } }
public class class_name { public static String buildFullName(Package aPackage, String simpleName) { String fullName; if (aPackage != null) { fullName = aPackage.getId() + PACKAGE_SEPARATOR + simpleName; } else { fullName = simpleName; } return fullName; } }
public class class_name { public static String buildFullName(Package aPackage, String simpleName) { String fullName; if (aPackage != null) { fullName = aPackage.getId() + PACKAGE_SEPARATOR + simpleName; // depends on control dependency: [if], data = [none] } else { fullName = simpleName; // depends on control dependency: [if], data = [none] } return fullName; } }
public class class_name { public static Date toDate(String dateString) { if (dateString == null) return null; SimpleDateFormat dateFormat = new SimpleDateFormat(); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); for (String format: ALLOWED_DATE_FORMATS) { dateFormat.applyPattern(format); try { return dateFormat.parse(dateString); } catch (ParseException e) { } } return null; } }
public class class_name { public static Date toDate(String dateString) { if (dateString == null) return null; SimpleDateFormat dateFormat = new SimpleDateFormat(); dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); for (String format: ALLOWED_DATE_FORMATS) { dateFormat.applyPattern(format); // depends on control dependency: [for], data = [format] try { return dateFormat.parse(dateString); // depends on control dependency: [try], data = [none] } catch (ParseException e) { } // depends on control dependency: [catch], data = [none] } return null; } }
public class class_name { public OutlierResult run(Relation<O> relation) { DistanceQuery<O> dq = relation.getDistanceQuery(getDistanceFunction()); final double logPerp = FastMath.log(perplexity); ModifiableDoubleDBIDList dlist = DBIDUtil.newDistanceDBIDList(relation.size() - 1); DoubleDBIDListMIter di = dlist.iter(); double[] p = new double[relation.size() - 1]; FiniteProgress prog = LOG.isVerbose() ? new FiniteProgress("SOS scores", relation.size(), LOG) : null; WritableDoubleDataStore scores = DataStoreUtil.makeDoubleStorage(relation.getDBIDs(), DataStoreFactory.HINT_HOT | DataStoreFactory.HINT_DB, 1.); for(DBIDIter it = relation.iterDBIDs(); it.valid(); it.advance()) { // Build sorted neighbors list. dlist.clear(); for(DBIDIter i2 = relation.iterDBIDs(); i2.valid(); i2.advance()) { if(DBIDUtil.equal(it, i2)) { continue; } dlist.add(dq.distance(it, i2), i2); } dlist.sort(); // Compute affinities computePi(it, di, p, perplexity, logPerp); // Normalization factor: double s = sumOfProbabilities(it, di, p); if(s > 0) { nominateNeighbors(it, di, p, 1. / s, scores); } LOG.incrementProcessed(prog); } LOG.ensureCompleted(prog); // Find minimum and maximum. DoubleMinMax minmax = new DoubleMinMax(); for(DBIDIter it2 = relation.iterDBIDs(); it2.valid(); it2.advance()) { minmax.put(scores.doubleValue(it2)); } DoubleRelation scoreres = new MaterializedDoubleRelation("Stoachastic Outlier Selection", "sos-outlier", scores, relation.getDBIDs()); OutlierScoreMeta meta = new ProbabilisticOutlierScore(minmax.getMin(), minmax.getMax(), 0.); return new OutlierResult(meta, scoreres); } }
public class class_name { public OutlierResult run(Relation<O> relation) { DistanceQuery<O> dq = relation.getDistanceQuery(getDistanceFunction()); final double logPerp = FastMath.log(perplexity); ModifiableDoubleDBIDList dlist = DBIDUtil.newDistanceDBIDList(relation.size() - 1); DoubleDBIDListMIter di = dlist.iter(); double[] p = new double[relation.size() - 1]; FiniteProgress prog = LOG.isVerbose() ? new FiniteProgress("SOS scores", relation.size(), LOG) : null; WritableDoubleDataStore scores = DataStoreUtil.makeDoubleStorage(relation.getDBIDs(), DataStoreFactory.HINT_HOT | DataStoreFactory.HINT_DB, 1.); for(DBIDIter it = relation.iterDBIDs(); it.valid(); it.advance()) { // Build sorted neighbors list. dlist.clear(); // depends on control dependency: [for], data = [none] for(DBIDIter i2 = relation.iterDBIDs(); i2.valid(); i2.advance()) { if(DBIDUtil.equal(it, i2)) { continue; } dlist.add(dq.distance(it, i2), i2); // depends on control dependency: [for], data = [i2] } dlist.sort(); // depends on control dependency: [for], data = [none] // Compute affinities computePi(it, di, p, perplexity, logPerp); // depends on control dependency: [for], data = [it] // Normalization factor: double s = sumOfProbabilities(it, di, p); if(s > 0) { nominateNeighbors(it, di, p, 1. / s, scores); // depends on control dependency: [if], data = [none] } LOG.incrementProcessed(prog); // depends on control dependency: [for], data = [none] } LOG.ensureCompleted(prog); // Find minimum and maximum. DoubleMinMax minmax = new DoubleMinMax(); for(DBIDIter it2 = relation.iterDBIDs(); it2.valid(); it2.advance()) { minmax.put(scores.doubleValue(it2)); // depends on control dependency: [for], data = [it2] } DoubleRelation scoreres = new MaterializedDoubleRelation("Stoachastic Outlier Selection", "sos-outlier", scores, relation.getDBIDs()); OutlierScoreMeta meta = new ProbabilisticOutlierScore(minmax.getMin(), minmax.getMax(), 0.); return new OutlierResult(meta, scoreres); } }
public class class_name { public static String readResource(String path) { final long start = System.nanoTime(); try (InputStream is = UScale.class.getClassLoader().getResourceAsStream(path);) { int len = 0; byte[] buffer = new byte[2048]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); while ((len = is.read(buffer)) >= 0) { baos.write(buffer, 0, len); } return new String(baos.toByteArray(), StandardCharsets.UTF_8); } catch (IOException e) { LOGGER.log(Level.WARNING, e, () -> "IOException loading resource " + path); throw new IllegalStateException("Unable to read class loaded stream " + path, e); } catch (RuntimeException re) { LOGGER.log(Level.WARNING, re, () -> "Unexpected exception loading resource " + path); throw re; } finally { LOGGER.fine(() -> String.format("Loaded resource %s in %.3fms", path, (System.nanoTime() - start) / 1000000.0)); } } }
public class class_name { public static String readResource(String path) { final long start = System.nanoTime(); try (InputStream is = UScale.class.getClassLoader().getResourceAsStream(path);) { int len = 0; byte[] buffer = new byte[2048]; ByteArrayOutputStream baos = new ByteArrayOutputStream(); while ((len = is.read(buffer)) >= 0) { baos.write(buffer, 0, len); // depends on control dependency: [while], data = [none] } return new String(baos.toByteArray(), StandardCharsets.UTF_8); } catch (IOException e) { LOGGER.log(Level.WARNING, e, () -> "IOException loading resource " + path); throw new IllegalStateException("Unable to read class loaded stream " + path, e); } catch (RuntimeException re) { LOGGER.log(Level.WARNING, re, () -> "Unexpected exception loading resource " + path); throw re; } finally { LOGGER.fine(() -> String.format("Loaded resource %s in %.3fms", path, (System.nanoTime() - start) / 1000000.0)); } } }
public class class_name { public List<String> getMessages() { if (mMessages == null || mMessages.size() == 0) { mMessages = Collections.singletonList(super.getMessage()); } return mMessages; } }
public class class_name { public List<String> getMessages() { if (mMessages == null || mMessages.size() == 0) { mMessages = Collections.singletonList(super.getMessage()); // depends on control dependency: [if], data = [none] } return mMessages; } }
public class class_name { @Override public AliasType get(String key) { key = key.toUpperCase(); AliasType type = super.get(key); if (type == null) { register(type = new AliasType(key)); } return type; } }
public class class_name { @Override public AliasType get(String key) { key = key.toUpperCase(); AliasType type = super.get(key); if (type == null) { register(type = new AliasType(key)); // depends on control dependency: [if], data = [(type] } return type; } }
public class class_name { public void marshall(BatchGetObjectAttributes batchGetObjectAttributes, ProtocolMarshaller protocolMarshaller) { if (batchGetObjectAttributes == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(batchGetObjectAttributes.getObjectReference(), OBJECTREFERENCE_BINDING); protocolMarshaller.marshall(batchGetObjectAttributes.getSchemaFacet(), SCHEMAFACET_BINDING); protocolMarshaller.marshall(batchGetObjectAttributes.getAttributeNames(), ATTRIBUTENAMES_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(BatchGetObjectAttributes batchGetObjectAttributes, ProtocolMarshaller protocolMarshaller) { if (batchGetObjectAttributes == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(batchGetObjectAttributes.getObjectReference(), OBJECTREFERENCE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(batchGetObjectAttributes.getSchemaFacet(), SCHEMAFACET_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(batchGetObjectAttributes.getAttributeNames(), ATTRIBUTENAMES_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 Observable<ServiceResponse<SourceRepositoryPropertiesInner>> listSourceRepositoryPropertiesWithServiceResponseAsync(String resourceGroupName, String registryName, String buildTaskName) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (registryName == null) { throw new IllegalArgumentException("Parameter registryName is required and cannot be null."); } if (buildTaskName == null) { throw new IllegalArgumentException("Parameter buildTaskName is required and cannot be null."); } final String apiVersion = "2018-02-01-preview"; return service.listSourceRepositoryProperties(this.client.subscriptionId(), resourceGroupName, registryName, buildTaskName, apiVersion, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<SourceRepositoryPropertiesInner>>>() { @Override public Observable<ServiceResponse<SourceRepositoryPropertiesInner>> call(Response<ResponseBody> response) { try { ServiceResponse<SourceRepositoryPropertiesInner> clientResponse = listSourceRepositoryPropertiesDelegate(response); return Observable.just(clientResponse); } catch (Throwable t) { return Observable.error(t); } } }); } }
public class class_name { public Observable<ServiceResponse<SourceRepositoryPropertiesInner>> listSourceRepositoryPropertiesWithServiceResponseAsync(String resourceGroupName, String registryName, String buildTaskName) { if (this.client.subscriptionId() == null) { throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); } if (resourceGroupName == null) { throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); } if (registryName == null) { throw new IllegalArgumentException("Parameter registryName is required and cannot be null."); } if (buildTaskName == null) { throw new IllegalArgumentException("Parameter buildTaskName is required and cannot be null."); } final String apiVersion = "2018-02-01-preview"; return service.listSourceRepositoryProperties(this.client.subscriptionId(), resourceGroupName, registryName, buildTaskName, apiVersion, this.client.acceptLanguage(), this.client.userAgent()) .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<SourceRepositoryPropertiesInner>>>() { @Override public Observable<ServiceResponse<SourceRepositoryPropertiesInner>> call(Response<ResponseBody> response) { try { ServiceResponse<SourceRepositoryPropertiesInner> clientResponse = listSourceRepositoryPropertiesDelegate(response); return Observable.just(clientResponse); // depends on control dependency: [try], data = [none] } catch (Throwable t) { return Observable.error(t); } // depends on control dependency: [catch], data = [none] } }); } }
public class class_name { @Deprecated public static Long getLastModifiedTime(String resourceFile, Class clazz) { Assert.notNullOrEmptyTrimmed(resourceFile, "Missing resource file!"); try { URL url = clazz.getResource(resourceFile); return url.openConnection().getLastModified(); // get last modified date of resource } catch (IOException e) { return null; } } }
public class class_name { @Deprecated public static Long getLastModifiedTime(String resourceFile, Class clazz) { Assert.notNullOrEmptyTrimmed(resourceFile, "Missing resource file!"); try { URL url = clazz.getResource(resourceFile); return url.openConnection().getLastModified(); // get last modified date of resource // depends on control dependency: [try], data = [none] } catch (IOException e) { return null; } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static boolean isRegisteredOnServer(Context context) { final SharedPreferences prefs = getGCMPreferences(context); boolean isRegistered = prefs.getBoolean(PROPERTY_ON_SERVER, false); Log.v(TAG, "Is registered on server: " + isRegistered); if (isRegistered) { // checks if the information is not stale long expirationTime = prefs.getLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, -1); if (System.currentTimeMillis() > expirationTime) { Log.v(TAG, "flag expired on: " + new Timestamp(expirationTime)); return false; } } return isRegistered; } }
public class class_name { public static boolean isRegisteredOnServer(Context context) { final SharedPreferences prefs = getGCMPreferences(context); boolean isRegistered = prefs.getBoolean(PROPERTY_ON_SERVER, false); Log.v(TAG, "Is registered on server: " + isRegistered); if (isRegistered) { // checks if the information is not stale long expirationTime = prefs.getLong(PROPERTY_ON_SERVER_EXPIRATION_TIME, -1); if (System.currentTimeMillis() > expirationTime) { Log.v(TAG, "flag expired on: " + new Timestamp(expirationTime)); // depends on control dependency: [if], data = [expirationTime)] return false; // depends on control dependency: [if], data = [none] } } return isRegistered; } }
public class class_name { public Filters withKeyUsage(KeyUsageName... keyUsage) { java.util.ArrayList<String> keyUsageCopy = new java.util.ArrayList<String>(keyUsage.length); for (KeyUsageName value : keyUsage) { keyUsageCopy.add(value.toString()); } if (getKeyUsage() == null) { setKeyUsage(keyUsageCopy); } else { getKeyUsage().addAll(keyUsageCopy); } return this; } }
public class class_name { public Filters withKeyUsage(KeyUsageName... keyUsage) { java.util.ArrayList<String> keyUsageCopy = new java.util.ArrayList<String>(keyUsage.length); for (KeyUsageName value : keyUsage) { keyUsageCopy.add(value.toString()); // depends on control dependency: [for], data = [value] } if (getKeyUsage() == null) { setKeyUsage(keyUsageCopy); // depends on control dependency: [if], data = [none] } else { getKeyUsage().addAll(keyUsageCopy); // depends on control dependency: [if], data = [none] } return this; } }
public class class_name { public void write_attribute(final DeviceProxy deviceProxy, final DeviceAttribute[] deviceAttributes) throws DevFailed { checkIfTango(deviceProxy, "write_attribute"); build_connection(deviceProxy); // // Manage Access control // if (deviceProxy.access == TangoConst.ACCESS_READ) { // ping the device to throw execption // if failed (for reconnection) ping(deviceProxy); throwNotAuthorizedException(deviceProxy.devname + ".write_attribute()", "DeviceProxy.write_attribute()"); } // Build an AttributeValue IDL object array AttributeValue_4[] attributeValues_4 = new AttributeValue_4[0]; AttributeValue[] attributeValues = new AttributeValue[0]; if (deviceProxy.device_5 != null || deviceProxy.device_4 != null) { attributeValues_4 = new AttributeValue_4[deviceAttributes.length]; for (int i=0 ; i<deviceAttributes.length ; i++) { attributeValues_4[i] = deviceAttributes[i].getAttributeValueObject_4(); } } else { attributeValues = new AttributeValue[deviceAttributes.length]; for (int i = 0; i < deviceAttributes.length; i++) { attributeValues[i] = deviceAttributes[i].getAttributeValueObject_2(); } } boolean done = false; final int retries = deviceProxy.transparent_reconnection ? 2 : 1; for (int i = 0; i < retries && !done; i++) { // write attributes on device server try { if (deviceProxy.device_5 != null) { deviceProxy.device_5.write_attributes_4( attributeValues_4, DevLockManager.getInstance().getClntIdent()); } else if (deviceProxy.device_4 != null) { deviceProxy.device_4.write_attributes_4( attributeValues_4, DevLockManager.getInstance().getClntIdent()); } else if (deviceProxy.device_3 != null) { deviceProxy.device_3.write_attributes_3(attributeValues); } else { deviceProxy.device.write_attributes(attributeValues); } done = true; } catch (final DevFailed e) { // Except.print_exception(e); throw e; } catch (final MultiDevFailed e) { throw new NamedDevFailedList(e, name(deviceProxy), "DeviceProxy.write_attribute", "MultiDevFailed"); } catch (final Exception e) { manageExceptionReconnection(deviceProxy, retries, i, e, this.getClass() + ".DeviceProxy.write_attribute"); } } // End of for ( ; ; ) } }
public class class_name { public void write_attribute(final DeviceProxy deviceProxy, final DeviceAttribute[] deviceAttributes) throws DevFailed { checkIfTango(deviceProxy, "write_attribute"); build_connection(deviceProxy); // // Manage Access control // if (deviceProxy.access == TangoConst.ACCESS_READ) { // ping the device to throw execption // if failed (for reconnection) ping(deviceProxy); throwNotAuthorizedException(deviceProxy.devname + ".write_attribute()", "DeviceProxy.write_attribute()"); } // Build an AttributeValue IDL object array AttributeValue_4[] attributeValues_4 = new AttributeValue_4[0]; AttributeValue[] attributeValues = new AttributeValue[0]; if (deviceProxy.device_5 != null || deviceProxy.device_4 != null) { attributeValues_4 = new AttributeValue_4[deviceAttributes.length]; for (int i=0 ; i<deviceAttributes.length ; i++) { attributeValues_4[i] = deviceAttributes[i].getAttributeValueObject_4(); // depends on control dependency: [for], data = [i] } } else { attributeValues = new AttributeValue[deviceAttributes.length]; for (int i = 0; i < deviceAttributes.length; i++) { attributeValues[i] = deviceAttributes[i].getAttributeValueObject_2(); // depends on control dependency: [for], data = [i] } } boolean done = false; final int retries = deviceProxy.transparent_reconnection ? 2 : 1; for (int i = 0; i < retries && !done; i++) { // write attributes on device server try { if (deviceProxy.device_5 != null) { deviceProxy.device_5.write_attributes_4( attributeValues_4, DevLockManager.getInstance().getClntIdent()); } else if (deviceProxy.device_4 != null) { deviceProxy.device_4.write_attributes_4( attributeValues_4, DevLockManager.getInstance().getClntIdent()); } else if (deviceProxy.device_3 != null) { deviceProxy.device_3.write_attributes_3(attributeValues); } else { deviceProxy.device.write_attributes(attributeValues); } done = true; } catch (final DevFailed e) { // Except.print_exception(e); throw e; } catch (final MultiDevFailed e) { throw new NamedDevFailedList(e, name(deviceProxy), "DeviceProxy.write_attribute", "MultiDevFailed"); } catch (final Exception e) { manageExceptionReconnection(deviceProxy, retries, i, e, this.getClass() + ".DeviceProxy.write_attribute"); } } // End of for ( ; ; ) } }
public class class_name { final public void decrement(long time, long value) { if (!enabled) return; lastSampleTime = time; if (!sync) { count -= value; } else { synchronized (this) { count -= value; } } } }
public class class_name { final public void decrement(long time, long value) { if (!enabled) return; lastSampleTime = time; if (!sync) { count -= value; // depends on control dependency: [if], data = [none] } else { synchronized (this) { // depends on control dependency: [if], data = [none] count -= value; } } } }
public class class_name { public String toXmlString() { final StringBuilder buffer = new StringBuilder(); buffer.append("<"); buffer.append(getName()); Optional<String> attr = TagExtensions.attributesToString(getAttributes()); if (attr.isPresent()) { buffer.append(attr.get()); } if (isEndTag()) { buffer.append(">"); buffer.append(getContent()); if (getChildren() != null && !getChildren().isEmpty()) { for (final SimpleTag child : getChildren()) { buffer.append(child.toXmlString()); } } buffer.append("</"); buffer.append(getName()); buffer.append(">"); } else { buffer.append("/>"); } return buffer.toString(); } }
public class class_name { public String toXmlString() { final StringBuilder buffer = new StringBuilder(); buffer.append("<"); buffer.append(getName()); Optional<String> attr = TagExtensions.attributesToString(getAttributes()); if (attr.isPresent()) { buffer.append(attr.get()); // depends on control dependency: [if], data = [none] } if (isEndTag()) { buffer.append(">"); // depends on control dependency: [if], data = [none] buffer.append(getContent()); // depends on control dependency: [if], data = [none] if (getChildren() != null && !getChildren().isEmpty()) { for (final SimpleTag child : getChildren()) { buffer.append(child.toXmlString()); // depends on control dependency: [for], data = [child] } } buffer.append("</"); // depends on control dependency: [if], data = [none] buffer.append(getName()); // depends on control dependency: [if], data = [none] buffer.append(">"); // depends on control dependency: [if], data = [none] } else { buffer.append("/>"); // depends on control dependency: [if], data = [none] } return buffer.toString(); } }
public class class_name { public void release() { if (mEGLDisplay != EGL14.EGL_NO_DISPLAY) { // Android is unusual in that it uses a reference-counted EGLDisplay. So for // every eglInitialize() we need an eglTerminate(). EGL14.eglMakeCurrent(mEGLDisplay, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_CONTEXT); EGL14.eglDestroyContext(mEGLDisplay, mEGLContext); EGL14.eglReleaseThread(); EGL14.eglTerminate(mEGLDisplay); } mEGLDisplay = EGL14.EGL_NO_DISPLAY; mEGLContext = EGL14.EGL_NO_CONTEXT; mEGLConfig = null; } }
public class class_name { public void release() { if (mEGLDisplay != EGL14.EGL_NO_DISPLAY) { // Android is unusual in that it uses a reference-counted EGLDisplay. So for // every eglInitialize() we need an eglTerminate(). EGL14.eglMakeCurrent(mEGLDisplay, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_SURFACE, EGL14.EGL_NO_CONTEXT); // depends on control dependency: [if], data = [(mEGLDisplay] EGL14.eglDestroyContext(mEGLDisplay, mEGLContext); // depends on control dependency: [if], data = [(mEGLDisplay] EGL14.eglReleaseThread(); // depends on control dependency: [if], data = [none] EGL14.eglTerminate(mEGLDisplay); // depends on control dependency: [if], data = [(mEGLDisplay] } mEGLDisplay = EGL14.EGL_NO_DISPLAY; mEGLContext = EGL14.EGL_NO_CONTEXT; mEGLConfig = null; } }
public class class_name { @Override public CmsParameterConfiguration getConfiguration() { CmsParameterConfiguration result = new CmsParameterConfiguration(); CmsParameterConfiguration config = super.getConfiguration(); if (config != null) { result.putAll(config); } result.put(CONFIGURATION_REQUEST_PARAM_SUPPORT_ENABLED, String.valueOf(m_requestParamSupportEnabled)); return result; } }
public class class_name { @Override public CmsParameterConfiguration getConfiguration() { CmsParameterConfiguration result = new CmsParameterConfiguration(); CmsParameterConfiguration config = super.getConfiguration(); if (config != null) { result.putAll(config); // depends on control dependency: [if], data = [(config] } result.put(CONFIGURATION_REQUEST_PARAM_SUPPORT_ENABLED, String.valueOf(m_requestParamSupportEnabled)); return result; } }
public class class_name { public synchronized static PmiModuleConfig getConfigFromXMLFile(String xmlFilePath, boolean bFromCache, boolean bValidate) { //System.out.println ("[PerfModules] getConfigFromXMLFile(): " +xmlFilePath); PmiModuleConfig config = null; // if xmlFilePath = /com/ibm/websphere/pmi/customMod.xml // the moduleName/ID = customMod // Check in HashMap only if "bFromCache" is true // Otherwise, create a new instance of PmiModuleConfig - used in StatsImpl // to return the translated static info // VELA: PmiModuleConfig is cached with UID and not the shortName String modUID = getModuleUID(xmlFilePath); //System.out.println("### ModUID="+modUID); config = (PmiModuleConfig) moduleConfigs.get(modUID); //System.out.println("### config="+config); if (bFromCache) { // PmiModuleConfig is cached with moduleID (last part of the xml file name) as key. // This ASSUMES that moduleID is same as the XML file name // If moduleID and xml file names are different then XML will be parsed and loaded each time // NOTE:Module Name *MUST* be unique! /* * File f = new File (xmlFilePath); * String fileName = f.getName(); * int dotLoc = fileName.lastIndexOf("."); * if (dotLoc != -1) * { * String modName = fileName.substring (0, dotLoc-1); * config = (PmiModuleConfig)moduleConfigs.get (modName); * * if(config != null) * { * return config; * } * } */ if (config != null) { return config; } } else { // FIXED: When bFromCache = false and create a copy of the PmiModuleConfig instead of parsing the XML file again // added copy () to PmiModuleConfig and PmiDataInfo if (config != null) { return config.copy(); } } //System.out.println("#### not found in cache"); // Not found in cache. Try StatsTemplateLookup before loading from disk. if (bEnableStatsTemplateLookup) { int lookupCount = lookupList.size(); for (int i = 0; i < lookupCount; i++) { config = ((StatsTemplateLookup) lookupList.get(i)).getTemplate(modUID); if (config != null) break; else { // may be pre-defined. cut "com.ibm.websphere.pmi.xml." - 26 chars if (modUID.startsWith(DEFAULT_MODULE_PREFIX)) { config = ((StatsTemplateLookup) lookupList.get(i)).getTemplate(modUID.substring(26)); if (config != null) break; } } } if (config != null) { if (tc.isDebugEnabled()) Tr.debug(tc, "StatsTemplateLookup available for: " + xmlFilePath); config.setMbeanType(""); moduleConfigs.put(config.getUID(), config); if (!bFromCache) return config.copy(); else return config; } else { //System.out.println("---1 StatsTemplateLookup NOT available for: " + xmlFilePath ); if (tc.isDebugEnabled()) Tr.debug(tc, "StatsTemplateLookup NOT available for: " + xmlFilePath); } } //System.out.println("StatsTemplateLookup NOT available for: " + xmlFilePath ); // Not found in hard-coded lookup class. Load file from disk and parse it // d175652: ------ security code final String _xmlFile = xmlFilePath; final boolean _bDTDValidation = bValidate; parseException = null; try { //System.out.println("######## tryingt to get Config for "+_xmlFile); config = (PmiModuleConfig) AccessController.doPrivileged( new PrivilegedExceptionAction() { public Object run() throws Exception { return parser.parse(_xmlFile, _bDTDValidation); } }); } catch (PrivilegedActionException e) { parseException = e.getException(); } // ------ security code // Not in HashMap. Parse file //config = parser.parse(xmlFilePath, bValidate); // validate with DTD //System.out.println("######## Config ="+config); if (config != null) { if (bFromCache) { // there is no mbean type defined in template for custom pmi template // so set to none - to avoid PMI0006W in PmiJmxMapper config.setMbeanType(""); //String moduleID = config.getShortName(); //moduleConfigs.put(moduleID, config); // VELA: cache using UID as key "com.ibm.websphere.pmi.xml.beanModule" moduleConfigs.put(config.getUID(), config); if (tc.isDebugEnabled()) Tr.debug(tc, "Read PMI config for stats type: " + config.getUID()); return config; } else return config.copy(); } else { return config; // null } } }
public class class_name { public synchronized static PmiModuleConfig getConfigFromXMLFile(String xmlFilePath, boolean bFromCache, boolean bValidate) { //System.out.println ("[PerfModules] getConfigFromXMLFile(): " +xmlFilePath); PmiModuleConfig config = null; // if xmlFilePath = /com/ibm/websphere/pmi/customMod.xml // the moduleName/ID = customMod // Check in HashMap only if "bFromCache" is true // Otherwise, create a new instance of PmiModuleConfig - used in StatsImpl // to return the translated static info // VELA: PmiModuleConfig is cached with UID and not the shortName String modUID = getModuleUID(xmlFilePath); //System.out.println("### ModUID="+modUID); config = (PmiModuleConfig) moduleConfigs.get(modUID); //System.out.println("### config="+config); if (bFromCache) { // PmiModuleConfig is cached with moduleID (last part of the xml file name) as key. // This ASSUMES that moduleID is same as the XML file name // If moduleID and xml file names are different then XML will be parsed and loaded each time // NOTE:Module Name *MUST* be unique! /* * File f = new File (xmlFilePath); * String fileName = f.getName(); * int dotLoc = fileName.lastIndexOf("."); * if (dotLoc != -1) * { * String modName = fileName.substring (0, dotLoc-1); * config = (PmiModuleConfig)moduleConfigs.get (modName); * * if(config != null) * { * return config; * } * } */ if (config != null) { return config; // depends on control dependency: [if], data = [none] } } else { // FIXED: When bFromCache = false and create a copy of the PmiModuleConfig instead of parsing the XML file again // added copy () to PmiModuleConfig and PmiDataInfo if (config != null) { return config.copy(); // depends on control dependency: [if], data = [none] } } //System.out.println("#### not found in cache"); // Not found in cache. Try StatsTemplateLookup before loading from disk. if (bEnableStatsTemplateLookup) { int lookupCount = lookupList.size(); for (int i = 0; i < lookupCount; i++) { config = ((StatsTemplateLookup) lookupList.get(i)).getTemplate(modUID); // depends on control dependency: [for], data = [i] if (config != null) break; else { // may be pre-defined. cut "com.ibm.websphere.pmi.xml." - 26 chars if (modUID.startsWith(DEFAULT_MODULE_PREFIX)) { config = ((StatsTemplateLookup) lookupList.get(i)).getTemplate(modUID.substring(26)); // depends on control dependency: [if], data = [none] if (config != null) break; } } } if (config != null) { if (tc.isDebugEnabled()) Tr.debug(tc, "StatsTemplateLookup available for: " + xmlFilePath); config.setMbeanType(""); // depends on control dependency: [if], data = [none] moduleConfigs.put(config.getUID(), config); // depends on control dependency: [if], data = [(config] if (!bFromCache) return config.copy(); else return config; } else { //System.out.println("---1 StatsTemplateLookup NOT available for: " + xmlFilePath ); if (tc.isDebugEnabled()) Tr.debug(tc, "StatsTemplateLookup NOT available for: " + xmlFilePath); } } //System.out.println("StatsTemplateLookup NOT available for: " + xmlFilePath ); // Not found in hard-coded lookup class. Load file from disk and parse it // d175652: ------ security code final String _xmlFile = xmlFilePath; final boolean _bDTDValidation = bValidate; parseException = null; try { //System.out.println("######## tryingt to get Config for "+_xmlFile); config = (PmiModuleConfig) AccessController.doPrivileged( new PrivilegedExceptionAction() { public Object run() throws Exception { return parser.parse(_xmlFile, _bDTDValidation); } }); // depends on control dependency: [try], data = [none] } catch (PrivilegedActionException e) { parseException = e.getException(); } // depends on control dependency: [catch], data = [none] // ------ security code // Not in HashMap. Parse file //config = parser.parse(xmlFilePath, bValidate); // validate with DTD //System.out.println("######## Config ="+config); if (config != null) { if (bFromCache) { // there is no mbean type defined in template for custom pmi template // so set to none - to avoid PMI0006W in PmiJmxMapper config.setMbeanType(""); // depends on control dependency: [if], data = [none] //String moduleID = config.getShortName(); //moduleConfigs.put(moduleID, config); // VELA: cache using UID as key "com.ibm.websphere.pmi.xml.beanModule" moduleConfigs.put(config.getUID(), config); // depends on control dependency: [if], data = [none] if (tc.isDebugEnabled()) Tr.debug(tc, "Read PMI config for stats type: " + config.getUID()); return config; // depends on control dependency: [if], data = [none] } else return config.copy(); } else { return config; // null // depends on control dependency: [if], data = [none] } } }
public class class_name { private Object handleAssociation(final Object entity, final Map<String, Object> relationsMap, final EntityMetadata m, final PersistenceDelegator pd, boolean lazilyloaded, Map<Object, Object> relationStack) { for (Relation relation : m.getRelations()) { if (relation != null) { ForeignKey relationType = relation.getType(); Object relationalObject = PropertyAccessorHelper.getObject(entity, relation.getProperty()); if (KunderaCoreUtils.isEmptyOrNull(relationalObject) || ProxyHelper.isProxyOrCollection(relationalObject)) { onRelation(entity, relationsMap, m, pd, relation, relationType, lazilyloaded, relationStack); } // a bit of hack for neo4j only else if (!ProxyHelper.isProxyOrCollection(relationalObject) && Map.class.isAssignableFrom(relationalObject.getClass())) { Map relationalMap = (Map) relationalObject; for (Map.Entry entry : (Set<Map.Entry>) relationalMap.entrySet()) { Object entityObject = entry.getValue(); if (entityObject != null) { EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityObject.getClass()); PersistenceCacheManager.addEntityToPersistenceCache(entityObject, pd, PropertyAccessorHelper.getId(entityObject, metadata)); } } } } } return entity; } }
public class class_name { private Object handleAssociation(final Object entity, final Map<String, Object> relationsMap, final EntityMetadata m, final PersistenceDelegator pd, boolean lazilyloaded, Map<Object, Object> relationStack) { for (Relation relation : m.getRelations()) { if (relation != null) { ForeignKey relationType = relation.getType(); Object relationalObject = PropertyAccessorHelper.getObject(entity, relation.getProperty()); if (KunderaCoreUtils.isEmptyOrNull(relationalObject) || ProxyHelper.isProxyOrCollection(relationalObject)) { onRelation(entity, relationsMap, m, pd, relation, relationType, lazilyloaded, relationStack); // depends on control dependency: [if], data = [none] } // a bit of hack for neo4j only else if (!ProxyHelper.isProxyOrCollection(relationalObject) && Map.class.isAssignableFrom(relationalObject.getClass())) { Map relationalMap = (Map) relationalObject; for (Map.Entry entry : (Set<Map.Entry>) relationalMap.entrySet()) { Object entityObject = entry.getValue(); if (entityObject != null) { EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(kunderaMetadata, entityObject.getClass()); PersistenceCacheManager.addEntityToPersistenceCache(entityObject, pd, PropertyAccessorHelper.getId(entityObject, metadata)); // depends on control dependency: [if], data = [none] } } } } } return entity; } }
public class class_name { public Resource getCachedResource(URL url, long maxCacheMS, boolean bUseOlder) throws LiveDocumentNotAvailableException, LiveWebCacheUnavailableException, LiveWebTimeoutException, IOException { String urlString = url.toExternalForm(); if (requestPrefix != null) { urlString = requestPrefix + urlString; } HttpMethod method = null; try { method = new GetMethod(urlString); } catch(IllegalArgumentException e) { LOGGER.warning("Bad URL for live web fetch:" + urlString); throw new LiveDocumentNotAvailableException("Url:" + urlString + "does not look like an URL?"); } boolean success = false; try { int status = http.executeMethod(method); if(status == 200) { ByteArrayInputStream bais = new ByteArrayInputStream(method.getResponseBody()); ARCRecord r = new ARCRecord( new GZIPInputStream(bais), "id",0L,false,false,true); ArcResource ar = (ArcResource) ResourceFactory.ARCArchiveRecordToResource(r, null); if(ar.getStatusCode() == 502) { throw new LiveDocumentNotAvailableException(urlString); } else if(ar.getStatusCode() == 504) { throw new LiveWebTimeoutException("Timeout:" + urlString); } success = true; return ar; } else { throw new LiveWebCacheUnavailableException(urlString); } } catch (ResourceNotAvailableException e) { throw new LiveDocumentNotAvailableException(urlString); } catch (NoHttpResponseException e) { throw new LiveWebCacheUnavailableException("No Http Response for " + urlString); } catch (ConnectException e) { throw new LiveWebCacheUnavailableException(e.getLocalizedMessage() + " : " + urlString); } catch (SocketException e) { throw new LiveWebCacheUnavailableException(e.getLocalizedMessage() + " : " + urlString); } catch (SocketTimeoutException e) { throw new LiveWebTimeoutException(e.getLocalizedMessage() + " : " + urlString); } catch(ConnectTimeoutException e) { throw new LiveWebTimeoutException(e.getLocalizedMessage() + " : " + urlString); } finally { if (!success) { method.abort(); } method.releaseConnection(); } } }
public class class_name { public Resource getCachedResource(URL url, long maxCacheMS, boolean bUseOlder) throws LiveDocumentNotAvailableException, LiveWebCacheUnavailableException, LiveWebTimeoutException, IOException { String urlString = url.toExternalForm(); if (requestPrefix != null) { urlString = requestPrefix + urlString; } HttpMethod method = null; try { method = new GetMethod(urlString); } catch(IllegalArgumentException e) { LOGGER.warning("Bad URL for live web fetch:" + urlString); throw new LiveDocumentNotAvailableException("Url:" + urlString + "does not look like an URL?"); } boolean success = false; try { int status = http.executeMethod(method); if(status == 200) { ByteArrayInputStream bais = new ByteArrayInputStream(method.getResponseBody()); ARCRecord r = new ARCRecord( new GZIPInputStream(bais), "id",0L,false,false,true); ArcResource ar = (ArcResource) ResourceFactory.ARCArchiveRecordToResource(r, null); if(ar.getStatusCode() == 502) { throw new LiveDocumentNotAvailableException(urlString); } else if(ar.getStatusCode() == 504) { throw new LiveWebTimeoutException("Timeout:" + urlString); } success = true; // depends on control dependency: [if], data = [none] return ar; // depends on control dependency: [if], data = [none] } else { throw new LiveWebCacheUnavailableException(urlString); } } catch (ResourceNotAvailableException e) { throw new LiveDocumentNotAvailableException(urlString); } catch (NoHttpResponseException e) { throw new LiveWebCacheUnavailableException("No Http Response for " + urlString); } catch (ConnectException e) { throw new LiveWebCacheUnavailableException(e.getLocalizedMessage() + " : " + urlString); } catch (SocketException e) { throw new LiveWebCacheUnavailableException(e.getLocalizedMessage() + " : " + urlString); } catch (SocketTimeoutException e) { throw new LiveWebTimeoutException(e.getLocalizedMessage() + " : " + urlString); } catch(ConnectTimeoutException e) { throw new LiveWebTimeoutException(e.getLocalizedMessage() + " : " + urlString); } finally { if (!success) { method.abort(); // depends on control dependency: [if], data = [none] } method.releaseConnection(); } } }
public class class_name { public ClassDoc[] innerClasses(boolean filter) { ListBuffer<ClassDocImpl> innerClasses = new ListBuffer<>(); for (Symbol sym : tsym.members().getSymbols(NON_RECURSIVE)) { if (sym != null && sym.kind == TYP) { ClassSymbol s = (ClassSymbol)sym; if ((s.flags_field & Flags.SYNTHETIC) != 0) continue; if (!filter || env.isVisible(s)) { innerClasses.prepend(env.getClassDoc(s)); } } } //### Cache classes here? return innerClasses.toArray(new ClassDocImpl[innerClasses.length()]); } }
public class class_name { public ClassDoc[] innerClasses(boolean filter) { ListBuffer<ClassDocImpl> innerClasses = new ListBuffer<>(); for (Symbol sym : tsym.members().getSymbols(NON_RECURSIVE)) { if (sym != null && sym.kind == TYP) { ClassSymbol s = (ClassSymbol)sym; if ((s.flags_field & Flags.SYNTHETIC) != 0) continue; if (!filter || env.isVisible(s)) { innerClasses.prepend(env.getClassDoc(s)); // depends on control dependency: [if], data = [none] } } } //### Cache classes here? return innerClasses.toArray(new ClassDocImpl[innerClasses.length()]); } }
public class class_name { public static void loadJar(URLClassLoader loader, File jarFile) throws UtilException { try { final Method method = ClassUtil.getDeclaredMethod(URLClassLoader.class, "addURL", URL.class); if (null != method) { method.setAccessible(true); final List<File> jars = loopJar(jarFile); for (File jar : jars) { ReflectUtil.invoke(loader, method, new Object[] { jar.toURI().toURL() }); } } } catch (IOException e) { throw new UtilException(e); } } }
public class class_name { public static void loadJar(URLClassLoader loader, File jarFile) throws UtilException { try { final Method method = ClassUtil.getDeclaredMethod(URLClassLoader.class, "addURL", URL.class); if (null != method) { method.setAccessible(true); final List<File> jars = loopJar(jarFile); for (File jar : jars) { ReflectUtil.invoke(loader, method, new Object[] { jar.toURI().toURL() }); // depends on control dependency: [for], data = [jar] } } } catch (IOException e) { throw new UtilException(e); } } }
public class class_name { public ScreenComponent setupIconView(ScreenLoc itsLocation, ComponentParent targetScreen, Convert converter, int iDisplayFieldDesc, boolean bIncludeBlankOption) { ScreenComponent screenField = null; Record record = this.makeReferenceRecord(); // Set up the listener to read the current record on a valid main record ImageField fldDisplayFieldDesc = this.getIconField(record); if (fldDisplayFieldDesc.getListener(BlankButtonHandler.class) == null) fldDisplayFieldDesc.addListener(new BlankButtonHandler(null)); if (fldDisplayFieldDesc != null) { // The next two lines are so in GridScreen(s), the converter leads to this field, while it displays the fielddesc. FieldConverter fldDescConverter = new FieldDescConverter(fldDisplayFieldDesc, (Converter)converter); Map<String,Object> properties = new HashMap<String,Object>(); properties.put(ScreenModel.IMAGE, ScreenModel.NONE); properties.put(ScreenModel.NEVER_DISABLE, Constants.TRUE); screenField = createScreenComponent(ScreenModel.BUTTON_BOX, itsLocation, targetScreen, fldDescConverter, iDisplayFieldDesc, properties); //?{ //? public void setEnabled(boolean bEnabled) //? { //? super.setEnabled(true); // Never disable //? } //?}; String strDisplay = converter.getFieldDesc(); if (!(targetScreen instanceof GridScreenParent)) if ((strDisplay != null) && (strDisplay.length() > 0)) { // Since display string does not come with buttons ScreenLoc descLocation = targetScreen.getNextLocation(ScreenConstants.FIELD_DESC, ScreenConstants.DONT_SET_ANCHOR); properties = new HashMap<String,Object>(); properties.put(ScreenModel.DISPLAY_STRING, strDisplay); createScreenComponent(ScreenModel.STATIC_STRING, descLocation, targetScreen, converter, iDisplayFieldDesc, properties); } } if (((targetScreen instanceof GridScreenParent)) || (iDisplayFieldDesc == ScreenConstants.DONT_DISPLAY_FIELD_DESC)) { // If there is no popupbox to display the icon, I must explicitly read it. this.addListener(new ReadSecondaryHandler(fldDisplayFieldDesc.getRecord())); } return screenField; } }
public class class_name { public ScreenComponent setupIconView(ScreenLoc itsLocation, ComponentParent targetScreen, Convert converter, int iDisplayFieldDesc, boolean bIncludeBlankOption) { ScreenComponent screenField = null; Record record = this.makeReferenceRecord(); // Set up the listener to read the current record on a valid main record ImageField fldDisplayFieldDesc = this.getIconField(record); if (fldDisplayFieldDesc.getListener(BlankButtonHandler.class) == null) fldDisplayFieldDesc.addListener(new BlankButtonHandler(null)); if (fldDisplayFieldDesc != null) { // The next two lines are so in GridScreen(s), the converter leads to this field, while it displays the fielddesc. FieldConverter fldDescConverter = new FieldDescConverter(fldDisplayFieldDesc, (Converter)converter); Map<String,Object> properties = new HashMap<String,Object>(); properties.put(ScreenModel.IMAGE, ScreenModel.NONE); // depends on control dependency: [if], data = [none] properties.put(ScreenModel.NEVER_DISABLE, Constants.TRUE); // depends on control dependency: [if], data = [none] screenField = createScreenComponent(ScreenModel.BUTTON_BOX, itsLocation, targetScreen, fldDescConverter, iDisplayFieldDesc, properties); // depends on control dependency: [if], data = [none] //?{ //? public void setEnabled(boolean bEnabled) //? { //? super.setEnabled(true); // Never disable //? } //?}; String strDisplay = converter.getFieldDesc(); if (!(targetScreen instanceof GridScreenParent)) if ((strDisplay != null) && (strDisplay.length() > 0)) { // Since display string does not come with buttons ScreenLoc descLocation = targetScreen.getNextLocation(ScreenConstants.FIELD_DESC, ScreenConstants.DONT_SET_ANCHOR); properties = new HashMap<String,Object>(); // depends on control dependency: [if], data = [none] properties.put(ScreenModel.DISPLAY_STRING, strDisplay); // depends on control dependency: [if], data = [none] createScreenComponent(ScreenModel.STATIC_STRING, descLocation, targetScreen, converter, iDisplayFieldDesc, properties); // depends on control dependency: [if], data = [none] } } if (((targetScreen instanceof GridScreenParent)) || (iDisplayFieldDesc == ScreenConstants.DONT_DISPLAY_FIELD_DESC)) { // If there is no popupbox to display the icon, I must explicitly read it. this.addListener(new ReadSecondaryHandler(fldDisplayFieldDesc.getRecord())); // depends on control dependency: [if], data = [none] } return screenField; } }
public class class_name { public List<WebElement> findElements() { if (cachedElementList != null && shouldCache) { return cachedElementList; } List<WebElement> result; try { result = waitFor(() -> { List<WebElement> list = searchContext .findElements(getBy(by, searchContext)); return list.size() > 0 ? list : null; }); } catch (TimeoutException | StaleElementReferenceException e) { result = new ArrayList<>(); } if (shouldCache) { cachedElementList = result; } return result; } }
public class class_name { public List<WebElement> findElements() { if (cachedElementList != null && shouldCache) { return cachedElementList; // depends on control dependency: [if], data = [none] } List<WebElement> result; try { result = waitFor(() -> { List<WebElement> list = searchContext .findElements(getBy(by, searchContext)); // depends on control dependency: [try], data = [none] return list.size() > 0 ? list : null; // depends on control dependency: [try], data = [none] }); } catch (TimeoutException | StaleElementReferenceException e) { result = new ArrayList<>(); } // depends on control dependency: [catch], data = [none] if (shouldCache) { cachedElementList = result; // depends on control dependency: [if], data = [none] } return result; } }
public class class_name { boolean isDir(String src) { byte[][] components = INodeDirectory.getPathComponents(normalizePath(src)); readLock(); try { INode node = rootDir.getNode(components); return isDir(node); } finally { readUnlock(); } } }
public class class_name { boolean isDir(String src) { byte[][] components = INodeDirectory.getPathComponents(normalizePath(src)); readLock(); try { INode node = rootDir.getNode(components); return isDir(node); // depends on control dependency: [try], data = [none] } finally { readUnlock(); } } }
public class class_name { private static LossInfo doReduce(SameDiff sd, String outputName, boolean isMean, LossInfo.Builder b, Reduction reduction, SDVariable preReduceLoss, SDVariable label, SDVariable weights, int[] dimensions){ switch (reduction){ case NONE: //Return same shape as predictions/labels b.loss(preReduceLoss); break; case SPECIFIED_DIMS: //Reduce along specified dimensions if(isMean){ //Example: MSE + mean along examples b.loss(sd.mean(outputName, preReduceLoss, dimensions)); } else { //Example: L1 loss (sum) + mean along examples b.loss(sd.sum(outputName, preReduceLoss, dimensions)); } case SUM: if(isMean){ //Example: MSE (mean) + sum along examples SDVariable m = sd.mean(preReduceLoss, dimensions); b.loss(sd.sum(outputName, m)); } else { //Example: L1 loss (sum) + sum along examples -> sum along all dimensions b.loss(sd.sum(outputName, preReduceLoss)); } break; case MEAN_BY_WEIGHT: SDVariable weightSum = sd.sum(weights); if(isMean){ //Example: MSE (mean) + mean by weights over examples //reduce along dims + reduce along remaining dims == reduce along *all* dims SDVariable m2 = sd.mean(preReduceLoss); b.loss(m2.div(outputName, weightSum)); } else { //Example: L1 (sum) + mean by weights over examples SDVariable sum = sd.sum(preReduceLoss, dimensions); b.loss(sum.div(outputName, weightSum)); } break; case MEAN_BY_COUNT: SDVariable nonZeroWeights = nonZeroCount(weights, label); SDVariable r; if(isMean){ //Example: MSE (mean) + mean by count over examples r = sd.sum(preReduceLoss); } else { //Example: L1 (sum) + mean by count over examples SDVariable sum = sd.sum(preReduceLoss, dimensions); r = sd.mean(sum); } b.loss(r.div(outputName, nonZeroWeights)); break; default: throw new RuntimeException("Unknown reduction: " + reduction); } return b.build(); } }
public class class_name { private static LossInfo doReduce(SameDiff sd, String outputName, boolean isMean, LossInfo.Builder b, Reduction reduction, SDVariable preReduceLoss, SDVariable label, SDVariable weights, int[] dimensions){ switch (reduction){ case NONE: //Return same shape as predictions/labels b.loss(preReduceLoss); break; case SPECIFIED_DIMS: //Reduce along specified dimensions if(isMean){ //Example: MSE + mean along examples b.loss(sd.mean(outputName, preReduceLoss, dimensions)); // depends on control dependency: [if], data = [none] } else { //Example: L1 loss (sum) + mean along examples b.loss(sd.sum(outputName, preReduceLoss, dimensions)); // depends on control dependency: [if], data = [none] } case SUM: if(isMean){ //Example: MSE (mean) + sum along examples SDVariable m = sd.mean(preReduceLoss, dimensions); b.loss(sd.sum(outputName, m)); // depends on control dependency: [if], data = [none] } else { //Example: L1 loss (sum) + sum along examples -> sum along all dimensions b.loss(sd.sum(outputName, preReduceLoss)); // depends on control dependency: [if], data = [none] } break; case MEAN_BY_WEIGHT: SDVariable weightSum = sd.sum(weights); if(isMean){ //Example: MSE (mean) + mean by weights over examples //reduce along dims + reduce along remaining dims == reduce along *all* dims SDVariable m2 = sd.mean(preReduceLoss); b.loss(m2.div(outputName, weightSum)); // depends on control dependency: [if], data = [none] } else { //Example: L1 (sum) + mean by weights over examples SDVariable sum = sd.sum(preReduceLoss, dimensions); b.loss(sum.div(outputName, weightSum)); // depends on control dependency: [if], data = [none] } break; case MEAN_BY_COUNT: SDVariable nonZeroWeights = nonZeroCount(weights, label); SDVariable r; if(isMean){ //Example: MSE (mean) + mean by count over examples r = sd.sum(preReduceLoss); // depends on control dependency: [if], data = [none] } else { //Example: L1 (sum) + mean by count over examples SDVariable sum = sd.sum(preReduceLoss, dimensions); r = sd.mean(sum); // depends on control dependency: [if], data = [none] } b.loss(r.div(outputName, nonZeroWeights)); break; default: throw new RuntimeException("Unknown reduction: " + reduction); } return b.build(); } }
public class class_name { @Override public void postProcessInstance(ManagedClassSPI managedClass, Object instance) { if (instance == null) { // null instance is silently ignored since container ensure not null instance argument return; } for (Field dependency : managedClass.getDependencies()) { if (dependency.isSynthetic()) { // it seems there can be injected fields, created via byte code manipulation, when run with test coverage active // not clear why and how but was consistently observed on mock object from unit test run with coverage continue; } Classes.setFieldValue(instance, dependency, getDependencyValue(managedClass, dependency.getType())); } } }
public class class_name { @Override public void postProcessInstance(ManagedClassSPI managedClass, Object instance) { if (instance == null) { // null instance is silently ignored since container ensure not null instance argument return; // depends on control dependency: [if], data = [none] } for (Field dependency : managedClass.getDependencies()) { if (dependency.isSynthetic()) { // it seems there can be injected fields, created via byte code manipulation, when run with test coverage active // not clear why and how but was consistently observed on mock object from unit test run with coverage continue; } Classes.setFieldValue(instance, dependency, getDependencyValue(managedClass, dependency.getType())); // depends on control dependency: [for], data = [dependency] } } }
public class class_name { public Object getValue(Object object) throws IllegalAccessException, InvocationTargetException { Object result = null; if (getter != null) { result = getter.invoke(object); } else if (field != null) { if(!field.isAccessible()){ field.setAccessible(true); } result = field.get(object); } return result; } }
public class class_name { public Object getValue(Object object) throws IllegalAccessException, InvocationTargetException { Object result = null; if (getter != null) { result = getter.invoke(object); } else if (field != null) { if(!field.isAccessible()){ field.setAccessible(true); // depends on control dependency: [if], data = [none] } result = field.get(object); } return result; } }
public class class_name { protected T readObjectFromString(final String jsonString) { try { LOGGER.trace("Attempting to consume [{}]", jsonString); return this.objectMapper.readValue(jsonString, getTypeToSerialize()); } catch (final Exception e) { LOGGER.error("Cannot read/parse [{}] to deserialize into type [{}]. This may be caused " + "in the absence of a configuration/support module that knows how to interpret the fragment, " + "specially if the fragment describes a CAS registered service definition. " + "Internal parsing error is [{}]", DigestUtils.abbreviate(jsonString), getTypeToSerialize(), e.getMessage()); LOGGER.debug(e.getMessage(), e); } return null; } }
public class class_name { protected T readObjectFromString(final String jsonString) { try { LOGGER.trace("Attempting to consume [{}]", jsonString); return this.objectMapper.readValue(jsonString, getTypeToSerialize()); // depends on control dependency: [try], data = [none] } catch (final Exception e) { LOGGER.error("Cannot read/parse [{}] to deserialize into type [{}]. This may be caused " + "in the absence of a configuration/support module that knows how to interpret the fragment, " + "specially if the fragment describes a CAS registered service definition. " + "Internal parsing error is [{}]", DigestUtils.abbreviate(jsonString), getTypeToSerialize(), e.getMessage()); LOGGER.debug(e.getMessage(), e); } // depends on control dependency: [catch], data = [none] return null; } }
public class class_name { private void initLogThreshold(Long threshold) { this.logThreshold = threshold; final LogTemplate<Split> toLogger = toSLF4J(getClass().getName(), "debug"); if (threshold == null) { callTreeLogTemplate = toLogger; } else { callTreeLogTemplate = whenSplitLongerThanMilliseconds(toLogger, threshold); } } }
public class class_name { private void initLogThreshold(Long threshold) { this.logThreshold = threshold; final LogTemplate<Split> toLogger = toSLF4J(getClass().getName(), "debug"); if (threshold == null) { callTreeLogTemplate = toLogger; // depends on control dependency: [if], data = [none] } else { callTreeLogTemplate = whenSplitLongerThanMilliseconds(toLogger, threshold); // depends on control dependency: [if], data = [none] } } }
public class class_name { @SuppressWarnings("unchecked") public T tags(final Collection<String> tags) { if (this.tags == null) { this.tags = new HashSet<>(); } this.tags.addAll(tags); return (T) this; } }
public class class_name { @SuppressWarnings("unchecked") public T tags(final Collection<String> tags) { if (this.tags == null) { this.tags = new HashSet<>(); // depends on control dependency: [if], data = [none] } this.tags.addAll(tags); return (T) this; } }
public class class_name { private long getWaitTimeMs(TestContext context) { if (StringUtils.hasText(seconds)) { return Long.valueOf(context.replaceDynamicContentInString(seconds)) * 1000; } else { return Long.valueOf(context.replaceDynamicContentInString(milliseconds)); } } }
public class class_name { private long getWaitTimeMs(TestContext context) { if (StringUtils.hasText(seconds)) { return Long.valueOf(context.replaceDynamicContentInString(seconds)) * 1000; // depends on control dependency: [if], data = [none] } else { return Long.valueOf(context.replaceDynamicContentInString(milliseconds)); // depends on control dependency: [if], data = [none] } } }
public class class_name { public String determineUsername() { if (StringUtils.hasText(this.username)) { return this.username; } if (EmbeddedDatabaseConnection.isEmbedded(determineDriverClassName())) { return "sa"; } return null; } }
public class class_name { public String determineUsername() { if (StringUtils.hasText(this.username)) { return this.username; // depends on control dependency: [if], data = [none] } if (EmbeddedDatabaseConnection.isEmbedded(determineDriverClassName())) { return "sa"; // depends on control dependency: [if], data = [none] } return null; } }
public class class_name { public void setStateIcon(StateIcon icon) { if (m_stateIcon == null) { m_stateIcon = new HTML(); m_stateIcon.addClickHandler(m_iconSuperClickHandler); m_contentPanel.add(m_stateIcon); } String iconTitle = null; I_CmsListItemWidgetCss listItemWidgetCss = I_CmsLayoutBundle.INSTANCE.listItemWidgetCss(); String styleStateIcon = I_CmsLayoutBundle.INSTANCE.listItemWidgetCss().stateIcon(); switch (icon) { case export: m_stateIcon.setStyleName(styleStateIcon + " " + listItemWidgetCss.export()); iconTitle = Messages.get().key(Messages.GUI_ICON_TITLE_EXPORT_0); break; case secure: m_stateIcon.setStyleName(styleStateIcon + " " + listItemWidgetCss.secure()); iconTitle = Messages.get().key(Messages.GUI_ICON_TITLE_SECURE_0); break; case copy: m_stateIcon.setStyleName(styleStateIcon + " " + listItemWidgetCss.copyModel()); break; case standard: default: m_stateIcon.setStyleName(I_CmsLayoutBundle.INSTANCE.listItemWidgetCss().stateIcon()); break; } m_stateIcon.setTitle(concatIconTitles(m_iconTitle, iconTitle)); m_stateIcon.getElement().getStyle().setCursor(Style.Cursor.POINTER); } }
public class class_name { public void setStateIcon(StateIcon icon) { if (m_stateIcon == null) { m_stateIcon = new HTML(); // depends on control dependency: [if], data = [none] m_stateIcon.addClickHandler(m_iconSuperClickHandler); // depends on control dependency: [if], data = [none] m_contentPanel.add(m_stateIcon); // depends on control dependency: [if], data = [(m_stateIcon] } String iconTitle = null; I_CmsListItemWidgetCss listItemWidgetCss = I_CmsLayoutBundle.INSTANCE.listItemWidgetCss(); String styleStateIcon = I_CmsLayoutBundle.INSTANCE.listItemWidgetCss().stateIcon(); switch (icon) { case export: m_stateIcon.setStyleName(styleStateIcon + " " + listItemWidgetCss.export()); iconTitle = Messages.get().key(Messages.GUI_ICON_TITLE_EXPORT_0); break; case secure: m_stateIcon.setStyleName(styleStateIcon + " " + listItemWidgetCss.secure()); iconTitle = Messages.get().key(Messages.GUI_ICON_TITLE_SECURE_0); break; case copy: m_stateIcon.setStyleName(styleStateIcon + " " + listItemWidgetCss.copyModel()); break; case standard: default: m_stateIcon.setStyleName(I_CmsLayoutBundle.INSTANCE.listItemWidgetCss().stateIcon()); break; } m_stateIcon.setTitle(concatIconTitles(m_iconTitle, iconTitle)); m_stateIcon.getElement().getStyle().setCursor(Style.Cursor.POINTER); } }
public class class_name { protected static Boolean compare( // was BooleanValue Object val0, Object val1, boolean lessThan, boolean permissive) { if (tc.isAnyTracingEnabled() && tc.isEntryEnabled()) tc.entry(cclass, "compare", new Object[] { val0, val1, new Boolean(lessThan), new Boolean(permissive) }); Boolean theReturn = null; // Encode the types of the two arguments into sixteen cases based on the classification // Number/Boolean/String/Serializable. All other types (and nulls) result in the NULL // answer. int ans0 = (val0 instanceof Number) // was NumericValue ? 0 : (val0 instanceof Boolean) // was BooleanValue ? 1 : (val0 instanceof String) ? 2 : (val0 instanceof Serializable) ? 3 : 4; int ans1 = (val1 instanceof Number) // was NumericValue ? 0 : (val1 instanceof Boolean) // was BooleanValue ? 1 : (val1 instanceof String) ? 2 : (val1 instanceof Serializable) ? 3 : 4; if (ans0 > 3 || ans1 > 3) { if (tc.isAnyTracingEnabled() && tc.isEntryEnabled()) tc.exit(cclass, "compare", null); return null; } int category = ans0 * 4 + ans1; // Categories: val1 // val0 Number Boolean String Object // Number 0 1 2 3 // Boolean 4 5 6 7 // String 8 9 10 11 // Object 12 13 14 15 // For the permissive mode (only) do the permissive mode casts according to the // category. if (permissive) switch (category) { case 0 : case 5 : case 10 : case 15 : break; // equal types: no casts needed case 2 : // Number/String: attempt to cast val1 to number val1 = castToNumber(val1); if (val1 == null) { if (tc.isAnyTracingEnabled() && tc.isEntryEnabled()) tc.exit(cclass, "compare", null); return null; } category = 0; break; case 6 : // Boolean/String: attempt to cast val1 to Boolean val1 = castToBoolean(val1); if (val1 == null) { if (tc.isAnyTracingEnabled() && tc.isEntryEnabled()) tc.exit(cclass, "compare", null); return null; } category = 5; break; case 8 : // String/Number: attempt to cast val0 to number val0 = castToNumber(val0); if (val0 == null) { if (tc.isAnyTracingEnabled() && tc.isEntryEnabled()) tc.exit(cclass, "compare", null); return null; } category = 0; break; case 9 : // String/Boolean: attempt to cast val0 to Boolean val0 = castToBoolean(val0); if (val0 == null) { if (tc.isAnyTracingEnabled() && tc.isEntryEnabled()) tc.exit(cclass, "compare", null); return null; } category = 4; break; default : // Other cases have no legal casts, even in permissive mode if (tc.isAnyTracingEnabled() && tc.isEntryEnabled()) tc.exit(cclass, "compare", null); return null; } // Now do the actual evalution switch (category) { case 0 : // both types are Number. Do the arithimetic in the appropriate precision // depending on the Java binary promotion rules. int comp = compare((Number) val0, (Number) val1); if (lessThan) theReturn = Boolean.valueOf(comp < 0); else theReturn = Boolean.valueOf(comp == 0); if (tc.isAnyTracingEnabled() && tc.isEntryEnabled()) tc.exit(cclass, "compare", theReturn); return theReturn; case 5 : case 10: if (lessThan) if(permissive) { val1 = castToNumber(val1); if (val1 == null) { if (tc.isAnyTracingEnabled() && tc.isEntryEnabled()) tc.exit(cclass, "compare", null); return null; } val0 = castToNumber(val0); if (val0 == null) { if (tc.isAnyTracingEnabled() && tc.isEntryEnabled()) tc.exit(cclass, "compare", null); return null; } int comp2 = compare((Number) val0, (Number) val1); // was ((NumericValue) val0).compareTo(val1) theReturn = Boolean.valueOf(comp2 < 0); // was BooleanValue if (tc.isAnyTracingEnabled() && tc.isEntryEnabled()) tc.exit(cclass, "compare", theReturn); return theReturn; } else { if (tc.isAnyTracingEnabled() && tc.isEntryEnabled()) tc.exit(cclass, "compare", null); return null; } case 15: // Both types are comparable and non-Null, but only equality is defined if (lessThan) { if (tc.isAnyTracingEnabled() && tc.isEntryEnabled()) tc.exit(cclass, "compare", null); return null; } else { theReturn = Boolean.valueOf(val0.equals(val1)); if (tc.isAnyTracingEnabled() && tc.isEntryEnabled()) tc.exit(cclass, "compare", theReturn); return theReturn; } default : // All other cases are disallowed if (tc.isAnyTracingEnabled() && tc.isEntryEnabled()) tc.exit(cclass, "compare", null); return null; } } }
public class class_name { protected static Boolean compare( // was BooleanValue Object val0, Object val1, boolean lessThan, boolean permissive) { if (tc.isAnyTracingEnabled() && tc.isEntryEnabled()) tc.entry(cclass, "compare", new Object[] { val0, val1, new Boolean(lessThan), new Boolean(permissive) }); Boolean theReturn = null; // Encode the types of the two arguments into sixteen cases based on the classification // Number/Boolean/String/Serializable. All other types (and nulls) result in the NULL // answer. int ans0 = (val0 instanceof Number) // was NumericValue ? 0 : (val0 instanceof Boolean) // was BooleanValue ? 1 : (val0 instanceof String) ? 2 : (val0 instanceof Serializable) ? 3 : 4; int ans1 = (val1 instanceof Number) // was NumericValue ? 0 : (val1 instanceof Boolean) // was BooleanValue ? 1 : (val1 instanceof String) ? 2 : (val1 instanceof Serializable) ? 3 : 4; if (ans0 > 3 || ans1 > 3) { if (tc.isAnyTracingEnabled() && tc.isEntryEnabled()) tc.exit(cclass, "compare", null); return null; // depends on control dependency: [if], data = [none] } int category = ans0 * 4 + ans1; // Categories: val1 // val0 Number Boolean String Object // Number 0 1 2 3 // Boolean 4 5 6 7 // String 8 9 10 11 // Object 12 13 14 15 // For the permissive mode (only) do the permissive mode casts according to the // category. if (permissive) switch (category) { case 0 : case 5 : case 10 : case 15 : break; // equal types: no casts needed case 2 : // Number/String: attempt to cast val1 to number val1 = castToNumber(val1); if (val1 == null) { if (tc.isAnyTracingEnabled() && tc.isEntryEnabled()) tc.exit(cclass, "compare", null); return null; // depends on control dependency: [if], data = [none] } category = 0; // depends on control dependency: [if], data = [none] break; case 6 : // Boolean/String: attempt to cast val1 to Boolean val1 = castToBoolean(val1); if (val1 == null) { if (tc.isAnyTracingEnabled() && tc.isEntryEnabled()) tc.exit(cclass, "compare", null); return null; // depends on control dependency: [if], data = [none] } category = 5; // depends on control dependency: [if], data = [none] break; case 8 : // String/Number: attempt to cast val0 to number val0 = castToNumber(val0); if (val0 == null) { if (tc.isAnyTracingEnabled() && tc.isEntryEnabled()) tc.exit(cclass, "compare", null); return null; // depends on control dependency: [if], data = [none] } category = 0; // depends on control dependency: [if], data = [none] break; case 9 : // String/Boolean: attempt to cast val0 to Boolean val0 = castToBoolean(val0); if (val0 == null) { if (tc.isAnyTracingEnabled() && tc.isEntryEnabled()) tc.exit(cclass, "compare", null); return null; // depends on control dependency: [if], data = [none] } category = 4; // depends on control dependency: [if], data = [none] break; default : // Other cases have no legal casts, even in permissive mode if (tc.isAnyTracingEnabled() && tc.isEntryEnabled()) tc.exit(cclass, "compare", null); return null; // depends on control dependency: [if], data = [none] } // Now do the actual evalution switch (category) { case 0 : // both types are Number. Do the arithimetic in the appropriate precision // depending on the Java binary promotion rules. int comp = compare((Number) val0, (Number) val1); if (lessThan) theReturn = Boolean.valueOf(comp < 0); else theReturn = Boolean.valueOf(comp == 0); if (tc.isAnyTracingEnabled() && tc.isEntryEnabled()) tc.exit(cclass, "compare", theReturn); return theReturn; case 5 : case 10: if (lessThan) if(permissive) { val1 = castToNumber(val1); // depends on control dependency: [if], data = [none] if (val1 == null) { if (tc.isAnyTracingEnabled() && tc.isEntryEnabled()) tc.exit(cclass, "compare", null); return null; // depends on control dependency: [if], data = [none] } val0 = castToNumber(val0); // depends on control dependency: [if], data = [none] if (val0 == null) { if (tc.isAnyTracingEnabled() && tc.isEntryEnabled()) tc.exit(cclass, "compare", null); return null; // depends on control dependency: [if], data = [none] } int comp2 = compare((Number) val0, (Number) val1); // was ((NumericValue) val0).compareTo(val1) theReturn = Boolean.valueOf(comp2 < 0); // was BooleanValue // depends on control dependency: [if], data = [none] if (tc.isAnyTracingEnabled() && tc.isEntryEnabled()) tc.exit(cclass, "compare", theReturn); return theReturn; // depends on control dependency: [if], data = [none] } else { if (tc.isAnyTracingEnabled() && tc.isEntryEnabled()) tc.exit(cclass, "compare", null); return null; // depends on control dependency: [if], data = [none] } case 15: // Both types are comparable and non-Null, but only equality is defined if (lessThan) { if (tc.isAnyTracingEnabled() && tc.isEntryEnabled()) tc.exit(cclass, "compare", null); return null; // depends on control dependency: [if], data = [none] } else { theReturn = Boolean.valueOf(val0.equals(val1)); // depends on control dependency: [if], data = [none] if (tc.isAnyTracingEnabled() && tc.isEntryEnabled()) tc.exit(cclass, "compare", theReturn); return theReturn; // depends on control dependency: [if], data = [none] } default : // All other cases are disallowed if (tc.isAnyTracingEnabled() && tc.isEntryEnabled()) tc.exit(cclass, "compare", null); return null; } } }
public class class_name { public AsyncTask<Params, Progress, Result> executeTask(Params... params) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { try { return executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params); } catch (Throwable t) { return execute(params); } } else return execute(params); } }
public class class_name { public AsyncTask<Params, Progress, Result> executeTask(Params... params) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { try { return executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params); // depends on control dependency: [try], data = [none] } catch (Throwable t) { return execute(params); } // depends on control dependency: [catch], data = [none] } else return execute(params); } }
public class class_name { @Override public StoreKey getStoreKey() { final StoreType type = getStoreType(); if ( type == null ) { return null; } final String name = matcher.group( NAME_GRP ); if ( isEmpty( name ) ) { return null; } return new StoreKey( type, name ); } }
public class class_name { @Override public StoreKey getStoreKey() { final StoreType type = getStoreType(); if ( type == null ) { return null; // depends on control dependency: [if], data = [none] } final String name = matcher.group( NAME_GRP ); if ( isEmpty( name ) ) { return null; // depends on control dependency: [if], data = [none] } return new StoreKey( type, name ); } }
public class class_name { @Override public InputStream openResourceStream(String className, String resourceName) throws ClassSource_Exception { String methodName = "openResourceStream"; if (!isProviderResource(resourceName)) { if (tc.isDebugEnabled()) { Tr.debug(tc, MessageFormat.format("[ {0} ] [ {1} ] ENTER/RETURN [ null ]: Provider does not contain [ {2} ]", getHashText(), methodName, resourceName)); } return null; } InputStream result; try { long initialTime = getTime(); result = getProvider().openResource(resourceName); // throws IOException long finalTime = getTime(); addStreamTime(finalTime - initialTime); } catch (Throwable th) { // defect 84235:we are generating multiple Warning/Error messages for each error // due to each level reporting them. // Disable the following warning and defer message generation to a higher level, // preferably the ultimate consumer of the exception. //Tr.warning(tc, "ANNO_CLASSSOURCE_OPEN2_EXCEPTION", // getHashText(), resourceName, null, null, className); String eMsg = "[ " + getHashText() + " ]" + " Failed to open [ " + resourceName + " ]" + " for class [ " + className + " ]"; throw getFactory().wrapIntoClassSourceException(CLASS_NAME, methodName, eMsg, th); } if (result == null) { // defect 84235:we are generating multiple Warning/Error messages for each error // due to each level reporting them. // Disable the following warning and defer message generation to a higher level, // preferably the ultimate consumer of the exception. //Tr.warning(tc, "ANNO_CLASSSOURCE_OPEN2_EXCEPTION", // getHashText(), resourceName, null, null, className); String eMsg = "[ " + getHashText() + " ]" + " Failed to open [ " + resourceName + " ]" + " for class [ " + className + " ]"; throw getFactory().newClassSourceException(eMsg); } return result; } }
public class class_name { @Override public InputStream openResourceStream(String className, String resourceName) throws ClassSource_Exception { String methodName = "openResourceStream"; if (!isProviderResource(resourceName)) { if (tc.isDebugEnabled()) { Tr.debug(tc, MessageFormat.format("[ {0} ] [ {1} ] ENTER/RETURN [ null ]: Provider does not contain [ {2} ]", getHashText(), methodName, resourceName)); // depends on control dependency: [if], data = [none] } return null; } InputStream result; try { long initialTime = getTime(); result = getProvider().openResource(resourceName); // throws IOException long finalTime = getTime(); addStreamTime(finalTime - initialTime); } catch (Throwable th) { // defect 84235:we are generating multiple Warning/Error messages for each error // due to each level reporting them. // Disable the following warning and defer message generation to a higher level, // preferably the ultimate consumer of the exception. //Tr.warning(tc, "ANNO_CLASSSOURCE_OPEN2_EXCEPTION", // getHashText(), resourceName, null, null, className); String eMsg = "[ " + getHashText() + " ]" + " Failed to open [ " + resourceName + " ]" + " for class [ " + className + " ]"; throw getFactory().wrapIntoClassSourceException(CLASS_NAME, methodName, eMsg, th); } if (result == null) { // defect 84235:we are generating multiple Warning/Error messages for each error // due to each level reporting them. // Disable the following warning and defer message generation to a higher level, // preferably the ultimate consumer of the exception. //Tr.warning(tc, "ANNO_CLASSSOURCE_OPEN2_EXCEPTION", // getHashText(), resourceName, null, null, className); String eMsg = "[ " + getHashText() + " ]" + " Failed to open [ " + resourceName + " ]" + " for class [ " + className + " ]"; throw getFactory().newClassSourceException(eMsg); } return result; } }
public class class_name { @DELETE public Response deleteContent(@PathParam("spaceID") String spaceID, @PathParam("contentID") String contentID, @QueryParam("storeID") String storeID) { StringBuilder msg = new StringBuilder("deleting content("); msg.append(spaceID); msg.append(", "); msg.append(contentID); msg.append(", "); msg.append(storeID); msg.append(")"); try { contentResource.deleteContent(spaceID, contentID, storeID); String responseText = "Content " + contentID + " deleted successfully"; return responseOk(msg.toString(), responseText); } catch (ResourceNotFoundException e) { return responseNotFound(msg.toString(), e, NOT_FOUND); } catch (ResourceException e) { return responseBad(msg.toString(), e, INTERNAL_SERVER_ERROR); } catch (Exception e) { return responseBad(msg.toString(), e, INTERNAL_SERVER_ERROR); } } }
public class class_name { @DELETE public Response deleteContent(@PathParam("spaceID") String spaceID, @PathParam("contentID") String contentID, @QueryParam("storeID") String storeID) { StringBuilder msg = new StringBuilder("deleting content("); msg.append(spaceID); msg.append(", "); msg.append(contentID); msg.append(", "); msg.append(storeID); msg.append(")"); try { contentResource.deleteContent(spaceID, contentID, storeID); // depends on control dependency: [try], data = [none] String responseText = "Content " + contentID + " deleted successfully"; return responseOk(msg.toString(), responseText); // depends on control dependency: [try], data = [none] } catch (ResourceNotFoundException e) { return responseNotFound(msg.toString(), e, NOT_FOUND); } catch (ResourceException e) { // depends on control dependency: [catch], data = [none] return responseBad(msg.toString(), e, INTERNAL_SERVER_ERROR); } catch (Exception e) { // depends on control dependency: [catch], data = [none] return responseBad(msg.toString(), e, INTERNAL_SERVER_ERROR); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private boolean upgrade(final ChannelHandlerContext ctx, final FullHttpRequest request) { // Select the best protocol based on those requested in the UPGRADE header. final List<CharSequence> requestedProtocols = splitHeader(request.headers().get(HttpHeaderNames.UPGRADE)); final int numRequestedProtocols = requestedProtocols.size(); UpgradeCodec upgradeCodec = null; CharSequence upgradeProtocol = null; for (int i = 0; i < numRequestedProtocols; i ++) { final CharSequence p = requestedProtocols.get(i); final UpgradeCodec c = upgradeCodecFactory.newUpgradeCodec(p); if (c != null) { upgradeProtocol = p; upgradeCodec = c; break; } } if (upgradeCodec == null) { // None of the requested protocols are supported, don't upgrade. return false; } // Make sure the CONNECTION header is present. List<String> connectionHeaderValues = request.headers().getAll(HttpHeaderNames.CONNECTION); if (connectionHeaderValues == null) { return false; } final StringBuilder concatenatedConnectionValue = new StringBuilder(connectionHeaderValues.size() * 10); for (CharSequence connectionHeaderValue : connectionHeaderValues) { concatenatedConnectionValue.append(connectionHeaderValue).append(COMMA); } concatenatedConnectionValue.setLength(concatenatedConnectionValue.length() - 1); // Make sure the CONNECTION header contains UPGRADE as well as all protocol-specific headers. Collection<CharSequence> requiredHeaders = upgradeCodec.requiredUpgradeHeaders(); List<CharSequence> values = splitHeader(concatenatedConnectionValue); if (!containsContentEqualsIgnoreCase(values, HttpHeaderNames.UPGRADE) || !containsAllContentEqualsIgnoreCase(values, requiredHeaders)) { return false; } // Ensure that all required protocol-specific headers are found in the request. for (CharSequence requiredHeader : requiredHeaders) { if (!request.headers().contains(requiredHeader)) { return false; } } // Prepare and send the upgrade response. Wait for this write to complete before upgrading, // since we need the old codec in-place to properly encode the response. final FullHttpResponse upgradeResponse = createUpgradeResponse(upgradeProtocol); if (!upgradeCodec.prepareUpgradeResponse(ctx, request, upgradeResponse.headers())) { return false; } // Create the user event to be fired once the upgrade completes. final UpgradeEvent event = new UpgradeEvent(upgradeProtocol, request); // After writing the upgrade response we immediately prepare the // pipeline for the next protocol to avoid a race between completion // of the write future and receiving data before the pipeline is // restructured. try { final ChannelFuture writeComplete = ctx.writeAndFlush(upgradeResponse); // Perform the upgrade to the new protocol. sourceCodec.upgradeFrom(ctx); upgradeCodec.upgradeTo(ctx, request); // Remove this handler from the pipeline. ctx.pipeline().remove(HttpServerUpgradeHandler.this); // Notify that the upgrade has occurred. Retain the event to offset // the release() in the finally block. ctx.fireUserEventTriggered(event.retain()); // Add the listener last to avoid firing upgrade logic after // the channel is already closed since the listener may fire // immediately if the write failed eagerly. writeComplete.addListener(ChannelFutureListener.CLOSE_ON_FAILURE); } finally { // Release the event if the upgrade event wasn't fired. event.release(); } return true; } }
public class class_name { private boolean upgrade(final ChannelHandlerContext ctx, final FullHttpRequest request) { // Select the best protocol based on those requested in the UPGRADE header. final List<CharSequence> requestedProtocols = splitHeader(request.headers().get(HttpHeaderNames.UPGRADE)); final int numRequestedProtocols = requestedProtocols.size(); UpgradeCodec upgradeCodec = null; CharSequence upgradeProtocol = null; for (int i = 0; i < numRequestedProtocols; i ++) { final CharSequence p = requestedProtocols.get(i); final UpgradeCodec c = upgradeCodecFactory.newUpgradeCodec(p); if (c != null) { upgradeProtocol = p; // depends on control dependency: [if], data = [none] upgradeCodec = c; // depends on control dependency: [if], data = [none] break; } } if (upgradeCodec == null) { // None of the requested protocols are supported, don't upgrade. return false; // depends on control dependency: [if], data = [none] } // Make sure the CONNECTION header is present. List<String> connectionHeaderValues = request.headers().getAll(HttpHeaderNames.CONNECTION); if (connectionHeaderValues == null) { return false; // depends on control dependency: [if], data = [none] } final StringBuilder concatenatedConnectionValue = new StringBuilder(connectionHeaderValues.size() * 10); for (CharSequence connectionHeaderValue : connectionHeaderValues) { concatenatedConnectionValue.append(connectionHeaderValue).append(COMMA); // depends on control dependency: [for], data = [connectionHeaderValue] } concatenatedConnectionValue.setLength(concatenatedConnectionValue.length() - 1); // Make sure the CONNECTION header contains UPGRADE as well as all protocol-specific headers. Collection<CharSequence> requiredHeaders = upgradeCodec.requiredUpgradeHeaders(); List<CharSequence> values = splitHeader(concatenatedConnectionValue); if (!containsContentEqualsIgnoreCase(values, HttpHeaderNames.UPGRADE) || !containsAllContentEqualsIgnoreCase(values, requiredHeaders)) { return false; // depends on control dependency: [if], data = [none] } // Ensure that all required protocol-specific headers are found in the request. for (CharSequence requiredHeader : requiredHeaders) { if (!request.headers().contains(requiredHeader)) { return false; // depends on control dependency: [if], data = [none] } } // Prepare and send the upgrade response. Wait for this write to complete before upgrading, // since we need the old codec in-place to properly encode the response. final FullHttpResponse upgradeResponse = createUpgradeResponse(upgradeProtocol); if (!upgradeCodec.prepareUpgradeResponse(ctx, request, upgradeResponse.headers())) { return false; // depends on control dependency: [if], data = [none] } // Create the user event to be fired once the upgrade completes. final UpgradeEvent event = new UpgradeEvent(upgradeProtocol, request); // After writing the upgrade response we immediately prepare the // pipeline for the next protocol to avoid a race between completion // of the write future and receiving data before the pipeline is // restructured. try { final ChannelFuture writeComplete = ctx.writeAndFlush(upgradeResponse); // Perform the upgrade to the new protocol. sourceCodec.upgradeFrom(ctx); // depends on control dependency: [try], data = [none] upgradeCodec.upgradeTo(ctx, request); // depends on control dependency: [try], data = [none] // Remove this handler from the pipeline. ctx.pipeline().remove(HttpServerUpgradeHandler.this); // depends on control dependency: [try], data = [none] // Notify that the upgrade has occurred. Retain the event to offset // the release() in the finally block. ctx.fireUserEventTriggered(event.retain()); // depends on control dependency: [try], data = [none] // Add the listener last to avoid firing upgrade logic after // the channel is already closed since the listener may fire // immediately if the write failed eagerly. writeComplete.addListener(ChannelFutureListener.CLOSE_ON_FAILURE); // depends on control dependency: [try], data = [none] } finally { // Release the event if the upgrade event wasn't fired. event.release(); } return true; } }
public class class_name { @VisibleForTesting public static Optional<WhitelistBlacklist> getViewWhiteBackListFromWorkUnit(WorkUnitState workUnit) { Optional<WhitelistBlacklist> optionalViewWhiteBlacklist = Optional.absent(); if (workUnit == null) { return optionalViewWhiteBlacklist; } if (workUnit.contains(HIVE_CONVERSION_VIEW_REGISTRATION_WHITELIST) || workUnit.contains(HIVE_CONVERSION_VIEW_REGISTRATION_BLACKLIST)) { String viewWhiteList = workUnit.getProp(HIVE_CONVERSION_VIEW_REGISTRATION_WHITELIST, StringUtils.EMPTY); String viewBlackList = workUnit.getProp(HIVE_CONVERSION_VIEW_REGISTRATION_BLACKLIST, StringUtils.EMPTY); try { optionalViewWhiteBlacklist = Optional.of(new WhitelistBlacklist(viewWhiteList, viewBlackList)); } catch (IOException e) { Throwables.propagate(e); } } return optionalViewWhiteBlacklist; } }
public class class_name { @VisibleForTesting public static Optional<WhitelistBlacklist> getViewWhiteBackListFromWorkUnit(WorkUnitState workUnit) { Optional<WhitelistBlacklist> optionalViewWhiteBlacklist = Optional.absent(); if (workUnit == null) { return optionalViewWhiteBlacklist; // depends on control dependency: [if], data = [none] } if (workUnit.contains(HIVE_CONVERSION_VIEW_REGISTRATION_WHITELIST) || workUnit.contains(HIVE_CONVERSION_VIEW_REGISTRATION_BLACKLIST)) { String viewWhiteList = workUnit.getProp(HIVE_CONVERSION_VIEW_REGISTRATION_WHITELIST, StringUtils.EMPTY); String viewBlackList = workUnit.getProp(HIVE_CONVERSION_VIEW_REGISTRATION_BLACKLIST, StringUtils.EMPTY); try { optionalViewWhiteBlacklist = Optional.of(new WhitelistBlacklist(viewWhiteList, viewBlackList)); // depends on control dependency: [try], data = [none] } catch (IOException e) { Throwables.propagate(e); } // depends on control dependency: [catch], data = [none] } return optionalViewWhiteBlacklist; } }
public class class_name { public static Fetch createDefaultAttributeFetch(Attribute attr, String languageCode) { Fetch fetch; if (isReferenceType(attr)) { fetch = new Fetch(); EntityType refEntityType = attr.getRefEntity(); String idAttrName = refEntityType.getIdAttribute().getName(); fetch.field(idAttrName); String labelAttrName = refEntityType.getLabelAttribute(languageCode).getName(); if (!labelAttrName.equals(idAttrName)) { fetch.field(labelAttrName); } if (attr.getDataType() == FILE) { fetch.field(FileMetaMetadata.URL); } } else { fetch = null; } return fetch; } }
public class class_name { public static Fetch createDefaultAttributeFetch(Attribute attr, String languageCode) { Fetch fetch; if (isReferenceType(attr)) { fetch = new Fetch(); // depends on control dependency: [if], data = [none] EntityType refEntityType = attr.getRefEntity(); String idAttrName = refEntityType.getIdAttribute().getName(); fetch.field(idAttrName); // depends on control dependency: [if], data = [none] String labelAttrName = refEntityType.getLabelAttribute(languageCode).getName(); if (!labelAttrName.equals(idAttrName)) { fetch.field(labelAttrName); // depends on control dependency: [if], data = [none] } if (attr.getDataType() == FILE) { fetch.field(FileMetaMetadata.URL); // depends on control dependency: [if], data = [none] } } else { fetch = null; // depends on control dependency: [if], data = [none] } return fetch; } }
public class class_name { public static boolean intersects(Geometry one, Geometry two) { if (one == null || two == null || isEmpty(one) || isEmpty(two)) { return false; } if (Geometry.POINT.equals(one.getGeometryType())) { return intersectsPoint(one, two); } else if (Geometry.LINE_STRING.equals(one.getGeometryType())) { return intersectsLineString(one, two); } else if (Geometry.MULTI_POINT.equals(one.getGeometryType()) || Geometry.MULTI_LINE_STRING.equals(one.getGeometryType())) { return intersectsMultiSomething(one, two); } List<Coordinate> coords1 = new ArrayList<Coordinate>(); List<Coordinate> coords2 = new ArrayList<Coordinate>(); getAllCoordinates(one, coords1); getAllCoordinates(two, coords2); for (int i = 0; i < coords1.size() - 1; i++) { for (int j = 0; j < coords2.size() - 1; j++) { if (MathService.intersectsLineSegment(coords1.get(i), coords1.get(i + 1), coords2.get(j), coords2.get(j + 1))) { return true; } } } return false; } }
public class class_name { public static boolean intersects(Geometry one, Geometry two) { if (one == null || two == null || isEmpty(one) || isEmpty(two)) { return false; // depends on control dependency: [if], data = [none] } if (Geometry.POINT.equals(one.getGeometryType())) { return intersectsPoint(one, two); // depends on control dependency: [if], data = [none] } else if (Geometry.LINE_STRING.equals(one.getGeometryType())) { return intersectsLineString(one, two); // depends on control dependency: [if], data = [none] } else if (Geometry.MULTI_POINT.equals(one.getGeometryType()) || Geometry.MULTI_LINE_STRING.equals(one.getGeometryType())) { return intersectsMultiSomething(one, two); // depends on control dependency: [if], data = [none] } List<Coordinate> coords1 = new ArrayList<Coordinate>(); List<Coordinate> coords2 = new ArrayList<Coordinate>(); getAllCoordinates(one, coords1); getAllCoordinates(two, coords2); for (int i = 0; i < coords1.size() - 1; i++) { for (int j = 0; j < coords2.size() - 1; j++) { if (MathService.intersectsLineSegment(coords1.get(i), coords1.get(i + 1), coords2.get(j), coords2.get(j + 1))) { return true; // depends on control dependency: [if], data = [none] } } } return false; } }
public class class_name { public final Map<Type, String> toStringParts() { Map<Type, String> result = new LinkedHashMap<>(); // Preserve order for #toString(). result.put(Type.MCC, mcc != 0 ? "mcc" + mcc : ""); result.put(Type.MNC, mnc != 0 ? "mnc" + mnc : ""); result.put(Type.LANGUAGE_STRING, languageString()); result.put(Type.LOCALE_SCRIPT_STRING, localeScriptString()); result.put(Type.REGION_STRING, !regionString().isEmpty() ? "r" + regionString() : ""); result.put(Type.LOCALE_VARIANT_STRING, localeVariantString()); result.put(Type.SCREEN_LAYOUT_DIRECTION, getOrDefault(SCREENLAYOUT_LAYOUTDIR_VALUES, screenLayoutDirection(), "")); result.put(Type.SMALLEST_SCREEN_WIDTH_DP, smallestScreenWidthDp != 0 ? "sw" + smallestScreenWidthDp + "dp" : ""); result.put(Type.SCREEN_WIDTH_DP, screenWidthDp != 0 ? "w" + screenWidthDp + "dp" : ""); result.put(Type.SCREEN_HEIGHT_DP, screenHeightDp != 0 ? "h" + screenHeightDp + "dp" : ""); result.put(Type.SCREEN_LAYOUT_SIZE, getOrDefault(SCREENLAYOUT_SIZE_VALUES, screenLayoutSize(), "")); result.put(Type.SCREEN_LAYOUT_LONG, getOrDefault(SCREENLAYOUT_LONG_VALUES, screenLayoutLong(), "")); result.put(Type.SCREEN_LAYOUT_ROUND, getOrDefault(SCREENLAYOUT_ROUND_VALUES, screenLayoutRound(), "")); result.put(Type.COLOR_MODE_HDR, getOrDefault(COLOR_MODE_HDR_VALUES, colorModeHdr(), "")); result.put( Type.COLOR_MODE_WIDE_COLOR_GAMUT, getOrDefault(COLOR_MODE_WIDE_COLOR_GAMUT_VALUES, colorModeWideColorGamut(), "")); result.put(Type.ORIENTATION, getOrDefault(ORIENTATION_VALUES, orientation, "")); result.put(Type.UI_MODE_TYPE, getOrDefault(UI_MODE_TYPE_VALUES, uiModeType(), "")); result.put(Type.UI_MODE_NIGHT, getOrDefault(UI_MODE_NIGHT_VALUES, uiModeNight(), "")); result.put(Type.DENSITY_DPI, getOrDefault(DENSITY_DPI_VALUES, density, density + "dpi")); result.put(Type.TOUCHSCREEN, getOrDefault(TOUCHSCREEN_VALUES, touchscreen, "")); result.put(Type.KEYBOARD_HIDDEN, getOrDefault(KEYBOARDHIDDEN_VALUES, keyboardHidden(), "")); result.put(Type.KEYBOARD, getOrDefault(KEYBOARD_VALUES, keyboard, "")); result.put(Type.NAVIGATION_HIDDEN, getOrDefault(NAVIGATIONHIDDEN_VALUES, navigationHidden(), "")); result.put(Type.NAVIGATION, getOrDefault(NAVIGATION_VALUES, navigation, "")); result.put(Type.SCREEN_SIZE, screenWidth != 0 || screenHeight != 0 ? screenWidth + "x" + screenHeight : ""); String sdkVersion = ""; if (this.sdkVersion != 0) { sdkVersion = "v" + this.sdkVersion; if (minorVersion != 0) { sdkVersion += "." + minorVersion; } } result.put(Type.SDK_VERSION, sdkVersion); return result; } }
public class class_name { public final Map<Type, String> toStringParts() { Map<Type, String> result = new LinkedHashMap<>(); // Preserve order for #toString(). result.put(Type.MCC, mcc != 0 ? "mcc" + mcc : ""); result.put(Type.MNC, mnc != 0 ? "mnc" + mnc : ""); result.put(Type.LANGUAGE_STRING, languageString()); result.put(Type.LOCALE_SCRIPT_STRING, localeScriptString()); result.put(Type.REGION_STRING, !regionString().isEmpty() ? "r" + regionString() : ""); result.put(Type.LOCALE_VARIANT_STRING, localeVariantString()); result.put(Type.SCREEN_LAYOUT_DIRECTION, getOrDefault(SCREENLAYOUT_LAYOUTDIR_VALUES, screenLayoutDirection(), "")); result.put(Type.SMALLEST_SCREEN_WIDTH_DP, smallestScreenWidthDp != 0 ? "sw" + smallestScreenWidthDp + "dp" : ""); result.put(Type.SCREEN_WIDTH_DP, screenWidthDp != 0 ? "w" + screenWidthDp + "dp" : ""); result.put(Type.SCREEN_HEIGHT_DP, screenHeightDp != 0 ? "h" + screenHeightDp + "dp" : ""); result.put(Type.SCREEN_LAYOUT_SIZE, getOrDefault(SCREENLAYOUT_SIZE_VALUES, screenLayoutSize(), "")); result.put(Type.SCREEN_LAYOUT_LONG, getOrDefault(SCREENLAYOUT_LONG_VALUES, screenLayoutLong(), "")); result.put(Type.SCREEN_LAYOUT_ROUND, getOrDefault(SCREENLAYOUT_ROUND_VALUES, screenLayoutRound(), "")); result.put(Type.COLOR_MODE_HDR, getOrDefault(COLOR_MODE_HDR_VALUES, colorModeHdr(), "")); result.put( Type.COLOR_MODE_WIDE_COLOR_GAMUT, getOrDefault(COLOR_MODE_WIDE_COLOR_GAMUT_VALUES, colorModeWideColorGamut(), "")); result.put(Type.ORIENTATION, getOrDefault(ORIENTATION_VALUES, orientation, "")); result.put(Type.UI_MODE_TYPE, getOrDefault(UI_MODE_TYPE_VALUES, uiModeType(), "")); result.put(Type.UI_MODE_NIGHT, getOrDefault(UI_MODE_NIGHT_VALUES, uiModeNight(), "")); result.put(Type.DENSITY_DPI, getOrDefault(DENSITY_DPI_VALUES, density, density + "dpi")); result.put(Type.TOUCHSCREEN, getOrDefault(TOUCHSCREEN_VALUES, touchscreen, "")); result.put(Type.KEYBOARD_HIDDEN, getOrDefault(KEYBOARDHIDDEN_VALUES, keyboardHidden(), "")); result.put(Type.KEYBOARD, getOrDefault(KEYBOARD_VALUES, keyboard, "")); result.put(Type.NAVIGATION_HIDDEN, getOrDefault(NAVIGATIONHIDDEN_VALUES, navigationHidden(), "")); result.put(Type.NAVIGATION, getOrDefault(NAVIGATION_VALUES, navigation, "")); result.put(Type.SCREEN_SIZE, screenWidth != 0 || screenHeight != 0 ? screenWidth + "x" + screenHeight : ""); String sdkVersion = ""; if (this.sdkVersion != 0) { sdkVersion = "v" + this.sdkVersion; // depends on control dependency: [if], data = [none] if (minorVersion != 0) { sdkVersion += "." + minorVersion; // depends on control dependency: [if], data = [none] } } result.put(Type.SDK_VERSION, sdkVersion); return result; } }
public class class_name { public synchronized String format(long inDate) { long seconds = inDate / 1000; // Is it not suitable to cache? if (seconds<_lastSeconds || _lastSeconds>0 && seconds>_lastSeconds+__hitWindow) { // It's a cache miss _misses++; if (_misses<__MaxMisses) { Date d = new Date(inDate); return _tzFormat.format(d); } } else if (_misses>0) _misses--; // Check if we are in the same second // and don't care about millis if (_lastSeconds==seconds && !_millis) return _lastResult; Date d = new Date(inDate); // Check if we need a new format string long minutes = seconds/60; if (_lastMinutes != minutes) { _lastMinutes = minutes; _secFormatString=_minFormat.format(d); int i; int l; if (_millis) { i=_secFormatString.indexOf("ss.SSS"); l=6; } else { i=_secFormatString.indexOf("ss"); l=2; } _secFormatString0=_secFormatString.substring(0,i); _secFormatString1=_secFormatString.substring(i+l); } // Always format if we get here _lastSeconds = seconds; StringBuffer sb=new StringBuffer(_secFormatString.length()); synchronized(sb) { sb.append(_secFormatString0); int s=(int)(seconds%60); if (s<10) sb.append('0'); sb.append(s); if (_millis) { long millis = inDate%1000; if (millis<10) sb.append(".00"); else if (millis<100) sb.append(".0"); else sb.append('.'); sb.append(millis); } sb.append(_secFormatString1); _lastResult=sb.toString(); } return _lastResult; } }
public class class_name { public synchronized String format(long inDate) { long seconds = inDate / 1000; // Is it not suitable to cache? if (seconds<_lastSeconds || _lastSeconds>0 && seconds>_lastSeconds+__hitWindow) { // It's a cache miss _misses++; // depends on control dependency: [if], data = [none] if (_misses<__MaxMisses) { Date d = new Date(inDate); return _tzFormat.format(d); // depends on control dependency: [if], data = [none] } } else if (_misses>0) _misses--; // Check if we are in the same second // and don't care about millis if (_lastSeconds==seconds && !_millis) return _lastResult; Date d = new Date(inDate); // Check if we need a new format string long minutes = seconds/60; if (_lastMinutes != minutes) { _lastMinutes = minutes; // depends on control dependency: [if], data = [none] _secFormatString=_minFormat.format(d); // depends on control dependency: [if], data = [none] int i; int l; if (_millis) { i=_secFormatString.indexOf("ss.SSS"); // depends on control dependency: [if], data = [none] l=6; // depends on control dependency: [if], data = [none] } else { i=_secFormatString.indexOf("ss"); // depends on control dependency: [if], data = [none] l=2; // depends on control dependency: [if], data = [none] } _secFormatString0=_secFormatString.substring(0,i); // depends on control dependency: [if], data = [none] _secFormatString1=_secFormatString.substring(i+l); // depends on control dependency: [if], data = [none] } // Always format if we get here _lastSeconds = seconds; StringBuffer sb=new StringBuffer(_secFormatString.length()); synchronized(sb) { sb.append(_secFormatString0); int s=(int)(seconds%60); if (s<10) sb.append('0'); sb.append(s); if (_millis) { long millis = inDate%1000; if (millis<10) sb.append(".00"); else if (millis<100) sb.append(".0"); else sb.append('.'); sb.append(millis); // depends on control dependency: [if], data = [none] } sb.append(_secFormatString1); _lastResult=sb.toString(); } return _lastResult; } }
public class class_name { private static Browser parseBrowser(String userAgentString) { for (Browser brower : Browser.browers) { if (brower.isMatch(userAgentString)) { return brower; } } return Browser.Unknown; } }
public class class_name { private static Browser parseBrowser(String userAgentString) { for (Browser brower : Browser.browers) { if (brower.isMatch(userAgentString)) { return brower; // depends on control dependency: [if], data = [none] } } return Browser.Unknown; } }
public class class_name { public Collection getAllUploadFile(HttpServletRequest request) { Collection uploadList = null; try { HttpSession session = request.getSession(); if (session != null) { uploadList = (Collection) session.getAttribute(PIC_NAME_PACKAGE); } } catch (Exception ex) { Debug.logError("[JdonFramework] not found the upload files in session" + ex, module); } return uploadList; } }
public class class_name { public Collection getAllUploadFile(HttpServletRequest request) { Collection uploadList = null; try { HttpSession session = request.getSession(); if (session != null) { uploadList = (Collection) session.getAttribute(PIC_NAME_PACKAGE); // depends on control dependency: [if], data = [none] } } catch (Exception ex) { Debug.logError("[JdonFramework] not found the upload files in session" + ex, module); } // depends on control dependency: [catch], data = [none] return uploadList; } }