code
stringlengths
130
281k
code_dependency
stringlengths
182
306k
public class class_name { public String getRootPath(){ if(this.isValid() && this.setRootPath!=null){ return StringUtils.substringBefore(this.getAbsolutePath(), this.setRootPath); } return null; } }
public class class_name { public String getRootPath(){ if(this.isValid() && this.setRootPath!=null){ return StringUtils.substringBefore(this.getAbsolutePath(), this.setRootPath); // depends on control dependency: [if], data = [none] } return null; } }
public class class_name { public Matrix getL () { Matrix X = MatrixFactory.createMatrix(m,n); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i > j) { X.set(i, j, LU[i][j]); } else if (i == j) { X.set(i, j, 1); } } } return X; } }
public class class_name { public Matrix getL () { Matrix X = MatrixFactory.createMatrix(m,n); for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { if (i > j) { X.set(i, j, LU[i][j]); // depends on control dependency: [if], data = [(i] } else if (i == j) { X.set(i, j, 1); // depends on control dependency: [if], data = [(i] } } } return X; } }
public class class_name { static boolean hasCustomOpenShiftUrl(OpenShiftConfig config) { try { URI masterUri = new URI(config.getMasterUrl()).resolve("/"); URI openshfitUri = new URI(config.getOpenShiftUrl()).resolve("/"); return !masterUri.equals(openshfitUri); } catch (Exception e) { throw KubernetesClientException.launderThrowable(e); } } }
public class class_name { static boolean hasCustomOpenShiftUrl(OpenShiftConfig config) { try { URI masterUri = new URI(config.getMasterUrl()).resolve("/"); URI openshfitUri = new URI(config.getOpenShiftUrl()).resolve("/"); return !masterUri.equals(openshfitUri); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw KubernetesClientException.launderThrowable(e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { protected String buildBasicAuthValue(String user, String password){ StringBuilder sb = new StringBuilder(); if (StringUtils.isNotEmpty(user)){ sb.append(user); } if (StringUtils.isNotEmpty(password)){ if (sb.length() > 0){ sb.append(':'); } sb.append(password); } return buildBasicAuthValue(sb.toString()); } }
public class class_name { protected String buildBasicAuthValue(String user, String password){ StringBuilder sb = new StringBuilder(); if (StringUtils.isNotEmpty(user)){ sb.append(user); // depends on control dependency: [if], data = [none] } if (StringUtils.isNotEmpty(password)){ if (sb.length() > 0){ sb.append(':'); // depends on control dependency: [if], data = [none] } sb.append(password); // depends on control dependency: [if], data = [none] } return buildBasicAuthValue(sb.toString()); } }
public class class_name { @Override public void complete(ValidationResult validationResult) { LOG.info("Finding patterns..."); // FIXME: There may be a better way to handle getting the full list of stops Map<String, Stop> stopById = new HashMap<>(); for (Stop stop : feed.stops) { stopById.put(stop.stop_id, stop); } // FIXME In the editor we need patterns to exist separately from and before trips themselves, so me make another table. Map<TripPatternKey, Pattern> patterns = patternFinder.createPatternObjects(stopById, errorStorage); Connection connection = null; try { // TODO this assumes gtfs-lib is using an SQL database and not a MapDB. // Maybe we should just create patterns in a separate step, but that would mean iterating over the // stop_times twice. LOG.info("Creating pattern and pattern stops tables."); connection = feed.getConnection(); Statement statement = connection.createStatement(); String tripsTableName = feed.tablePrefix + "trips"; String patternsTableName = feed.tablePrefix + "patterns"; String patternStopsTableName = feed.tablePrefix + "pattern_stops"; statement.execute(String.format("alter table %s add column pattern_id varchar", tripsTableName)); // FIXME: Here we're creating a pattern table that has an integer ID field (similar to the other GTFS tables) // AND a varchar pattern_id with essentially the same value cast to a string. Perhaps the pattern ID should // be a UUID or something, just to better distinguish it from the int ID? Table patternsTable = new Table(patternsTableName, Pattern.class, Requirement.EDITOR, Table.PATTERNS.fields); Table patternStopsTable = new Table(patternStopsTableName, PatternStop.class, Requirement.EDITOR, Table.PATTERN_STOP.fields); // Create pattern and pattern stops table, each with serial ID fields. patternsTable.createSqlTable(connection, null, true); patternStopsTable.createSqlTable(connection, null, true); // Generate prepared statements for inserts. String insertPatternSql = patternsTable.generateInsertSql(true); String insertPatternStopSql = patternStopsTable.generateInsertSql(true); PreparedStatement insertPatternStatement = connection.prepareStatement(insertPatternSql); BatchTracker patternTracker = new BatchTracker("pattern", insertPatternStatement); PreparedStatement insertPatternStopStatement = connection.prepareStatement(insertPatternStopSql); BatchTracker patternStopTracker = new BatchTracker("pattern stop", insertPatternStopStatement); int currentPatternIndex = 0; LOG.info("Storing patterns and pattern stops"); // If using Postgres, load pattern to trips mapping into temp table for quick updating. boolean postgresText = (connection.getMetaData().getDatabaseProductName().equals("PostgreSQL")); if (postgresText) { // NOTE: temp table name must NOT be prefixed with schema because temp tables are prefixed with their own // connection-unique schema. tempPatternForTripsTable = "pattern_for_trips"; tempPatternForTripsTextFile = File.createTempFile(tempPatternForTripsTable, "text"); LOG.info("Loading via temporary text file at {}", tempPatternForTripsTextFile.getAbsolutePath()); // Create temp table for updating trips with pattern IDs to be dropped at the end of the transaction. String createTempSql = String.format("create temp table %s(trip_id varchar, pattern_id varchar) on commit drop", tempPatternForTripsTable); LOG.info(createTempSql); statement.execute(createTempSql); patternForTripsFileStream = new PrintStream(new BufferedOutputStream(new FileOutputStream(tempPatternForTripsTextFile))); } for (Map.Entry<TripPatternKey, Pattern> entry : patterns.entrySet()) { Pattern pattern = entry.getValue(); LOG.debug("Batching pattern {}", pattern.pattern_id); TripPatternKey key = entry.getKey(); pattern.setStatementParameters(insertPatternStatement, true); patternTracker.addBatch(); // Construct pattern stops based on values in trip pattern key. // FIXME: Use pattern stops table here? int lastValidDeparture = key.departureTimes.get(0); for (int i = 0; i < key.stops.size(); i++) { int travelTime = 0; String stopId = key.stops.get(i); int arrival = key.arrivalTimes.get(i); if (i > 0) { int prevDeparture = key.departureTimes.get(i - 1); // Set travel time for all stops except the first. if (prevDeparture != INT_MISSING) { // Update the previous departure if it's not missing. Otherwise, base travel time based on the // most recent valid departure. lastValidDeparture = prevDeparture; } travelTime = arrival == INT_MISSING || lastValidDeparture == INT_MISSING ? INT_MISSING : arrival - lastValidDeparture; } int departure = key.departureTimes.get(i); int dwellTime = arrival == INT_MISSING || departure == INT_MISSING ? INT_MISSING : departure - arrival; insertPatternStopStatement.setString(1, pattern.pattern_id); // Stop sequence is zero-based. setIntParameter(insertPatternStopStatement, 2, i); insertPatternStopStatement.setString(3, stopId); setIntParameter(insertPatternStopStatement,4, travelTime); setIntParameter(insertPatternStopStatement,5, dwellTime); setIntParameter(insertPatternStopStatement,6, key.dropoffTypes.get(i)); setIntParameter(insertPatternStopStatement,7, key.pickupTypes.get(i)); setDoubleParameter(insertPatternStopStatement, 8, key.shapeDistances.get(i)); setIntParameter(insertPatternStopStatement,9, key.timepoints.get(i)); patternStopTracker.addBatch(); } // Finally, update all trips on this pattern to reference this pattern's ID. String questionMarks = String.join(", ", Collections.nCopies(pattern.associatedTrips.size(), "?")); PreparedStatement updateTripStatement = connection.prepareStatement( String.format("update %s set pattern_id = ? where trip_id in (%s)", tripsTableName, questionMarks)); int oneBasedIndex = 1; updateTripStatement.setString(oneBasedIndex++, pattern.pattern_id); // Prepare each trip in pattern to update trips table. for (String tripId : pattern.associatedTrips) { if (postgresText) { // Add line to temp csv file if using postgres. // No need to worry about null trip IDs because the trips have already been processed. String[] strings = new String[]{tripId, pattern.pattern_id}; // Print a new line in the standard postgres text format: // https://www.postgresql.org/docs/9.1/static/sql-copy.html#AEN64380 patternForTripsFileStream.println(String.join("\t", strings)); } else { // Otherwise, set statement parameter. updateTripStatement.setString(oneBasedIndex++, tripId); } } if (!postgresText) { // Execute trip update statement if not using temp text file. LOG.info("Updating {} trips with pattern ID {} (%d/%d)", pattern.associatedTrips.size(), pattern.pattern_id, currentPatternIndex, patterns.size()); updateTripStatement.executeUpdate(); } currentPatternIndex += 1; } // Send any remaining prepared statement calls to the database backend. patternTracker.executeRemaining(); patternStopTracker.executeRemaining(); LOG.info("Done storing patterns and pattern stops."); if (postgresText) { // Finally, copy the pattern for trips text file into a table, create an index on trip IDs, and update // the trips table. LOG.info("Updating trips with pattern IDs"); patternForTripsFileStream.close(); // Copy file contents into temp pattern for trips table. copyFromFile(connection, tempPatternForTripsTextFile, tempPatternForTripsTable); // Before updating the trips with pattern IDs, index the table on trip_id. String patternForTripsIndexSql = String.format("create index temp_trips_pattern_id_idx on %s (trip_id)", tempPatternForTripsTable); LOG.info(patternForTripsIndexSql); statement.execute(patternForTripsIndexSql); // Finally, execute the update statement. String updateTripsSql = String.format("update %s set pattern_id = %s.pattern_id from %s where %s.trip_id = %s.trip_id", tripsTableName, tempPatternForTripsTable, tempPatternForTripsTable, tripsTableName, tempPatternForTripsTable); LOG.info(updateTripsSql); statement.executeUpdate(updateTripsSql); // Delete temp file. Temp table will be dropped after the transaction is committed. tempPatternForTripsTextFile.delete(); LOG.info("Updating trips complete"); } LOG.info("Creating index on patterns"); statement.executeUpdate(String.format("alter table %s add primary key (pattern_id)", patternsTableName)); LOG.info("Creating index on pattern stops"); statement.executeUpdate(String.format("alter table %s add primary key (pattern_id, stop_sequence)", patternStopsTableName)); // Index new pattern_id column on trips. The other tables are already indexed because they have primary keys. LOG.info("Indexing trips on pattern id."); statement.execute(String.format("create index trips_pattern_id_idx on %s (pattern_id)", tripsTableName)); LOG.info("Done indexing."); connection.commit(); } catch (SQLException | IOException e) { // Rollback transaction if failure occurs on creating patterns. DbUtils.rollbackAndCloseQuietly(connection); // This exception will be stored as a validator failure. throw new RuntimeException(e); } finally { // Close transaction finally. DbUtils.closeQuietly(connection); } } }
public class class_name { @Override public void complete(ValidationResult validationResult) { LOG.info("Finding patterns..."); // FIXME: There may be a better way to handle getting the full list of stops Map<String, Stop> stopById = new HashMap<>(); for (Stop stop : feed.stops) { stopById.put(stop.stop_id, stop); // depends on control dependency: [for], data = [stop] } // FIXME In the editor we need patterns to exist separately from and before trips themselves, so me make another table. Map<TripPatternKey, Pattern> patterns = patternFinder.createPatternObjects(stopById, errorStorage); Connection connection = null; try { // TODO this assumes gtfs-lib is using an SQL database and not a MapDB. // Maybe we should just create patterns in a separate step, but that would mean iterating over the // stop_times twice. LOG.info("Creating pattern and pattern stops tables."); connection = feed.getConnection(); Statement statement = connection.createStatement(); String tripsTableName = feed.tablePrefix + "trips"; String patternsTableName = feed.tablePrefix + "patterns"; String patternStopsTableName = feed.tablePrefix + "pattern_stops"; statement.execute(String.format("alter table %s add column pattern_id varchar", tripsTableName)); // FIXME: Here we're creating a pattern table that has an integer ID field (similar to the other GTFS tables) // AND a varchar pattern_id with essentially the same value cast to a string. Perhaps the pattern ID should // be a UUID or something, just to better distinguish it from the int ID? Table patternsTable = new Table(patternsTableName, Pattern.class, Requirement.EDITOR, Table.PATTERNS.fields); Table patternStopsTable = new Table(patternStopsTableName, PatternStop.class, Requirement.EDITOR, Table.PATTERN_STOP.fields); // Create pattern and pattern stops table, each with serial ID fields. patternsTable.createSqlTable(connection, null, true); patternStopsTable.createSqlTable(connection, null, true); // Generate prepared statements for inserts. String insertPatternSql = patternsTable.generateInsertSql(true); String insertPatternStopSql = patternStopsTable.generateInsertSql(true); PreparedStatement insertPatternStatement = connection.prepareStatement(insertPatternSql); BatchTracker patternTracker = new BatchTracker("pattern", insertPatternStatement); PreparedStatement insertPatternStopStatement = connection.prepareStatement(insertPatternStopSql); BatchTracker patternStopTracker = new BatchTracker("pattern stop", insertPatternStopStatement); int currentPatternIndex = 0; LOG.info("Storing patterns and pattern stops"); // If using Postgres, load pattern to trips mapping into temp table for quick updating. boolean postgresText = (connection.getMetaData().getDatabaseProductName().equals("PostgreSQL")); if (postgresText) { // NOTE: temp table name must NOT be prefixed with schema because temp tables are prefixed with their own // connection-unique schema. tempPatternForTripsTable = "pattern_for_trips"; tempPatternForTripsTextFile = File.createTempFile(tempPatternForTripsTable, "text"); LOG.info("Loading via temporary text file at {}", tempPatternForTripsTextFile.getAbsolutePath()); // Create temp table for updating trips with pattern IDs to be dropped at the end of the transaction. String createTempSql = String.format("create temp table %s(trip_id varchar, pattern_id varchar) on commit drop", tempPatternForTripsTable); LOG.info(createTempSql); statement.execute(createTempSql); patternForTripsFileStream = new PrintStream(new BufferedOutputStream(new FileOutputStream(tempPatternForTripsTextFile))); } for (Map.Entry<TripPatternKey, Pattern> entry : patterns.entrySet()) { Pattern pattern = entry.getValue(); LOG.debug("Batching pattern {}", pattern.pattern_id); TripPatternKey key = entry.getKey(); pattern.setStatementParameters(insertPatternStatement, true); patternTracker.addBatch(); // Construct pattern stops based on values in trip pattern key. // FIXME: Use pattern stops table here? int lastValidDeparture = key.departureTimes.get(0); for (int i = 0; i < key.stops.size(); i++) { int travelTime = 0; String stopId = key.stops.get(i); int arrival = key.arrivalTimes.get(i); if (i > 0) { int prevDeparture = key.departureTimes.get(i - 1); // Set travel time for all stops except the first. if (prevDeparture != INT_MISSING) { // Update the previous departure if it's not missing. Otherwise, base travel time based on the // most recent valid departure. lastValidDeparture = prevDeparture; } travelTime = arrival == INT_MISSING || lastValidDeparture == INT_MISSING ? INT_MISSING : arrival - lastValidDeparture; } int departure = key.departureTimes.get(i); int dwellTime = arrival == INT_MISSING || departure == INT_MISSING ? INT_MISSING : departure - arrival; insertPatternStopStatement.setString(1, pattern.pattern_id); // Stop sequence is zero-based. setIntParameter(insertPatternStopStatement, 2, i); insertPatternStopStatement.setString(3, stopId); setIntParameter(insertPatternStopStatement,4, travelTime); setIntParameter(insertPatternStopStatement,5, dwellTime); setIntParameter(insertPatternStopStatement,6, key.dropoffTypes.get(i)); setIntParameter(insertPatternStopStatement,7, key.pickupTypes.get(i)); setDoubleParameter(insertPatternStopStatement, 8, key.shapeDistances.get(i)); setIntParameter(insertPatternStopStatement,9, key.timepoints.get(i)); patternStopTracker.addBatch(); } // Finally, update all trips on this pattern to reference this pattern's ID. String questionMarks = String.join(", ", Collections.nCopies(pattern.associatedTrips.size(), "?")); PreparedStatement updateTripStatement = connection.prepareStatement( String.format("update %s set pattern_id = ? where trip_id in (%s)", tripsTableName, questionMarks)); int oneBasedIndex = 1; updateTripStatement.setString(oneBasedIndex++, pattern.pattern_id); // Prepare each trip in pattern to update trips table. for (String tripId : pattern.associatedTrips) { if (postgresText) { // Add line to temp csv file if using postgres. // No need to worry about null trip IDs because the trips have already been processed. String[] strings = new String[]{tripId, pattern.pattern_id}; // Print a new line in the standard postgres text format: // https://www.postgresql.org/docs/9.1/static/sql-copy.html#AEN64380 patternForTripsFileStream.println(String.join("\t", strings)); } else { // Otherwise, set statement parameter. updateTripStatement.setString(oneBasedIndex++, tripId); } } if (!postgresText) { // Execute trip update statement if not using temp text file. LOG.info("Updating {} trips with pattern ID {} (%d/%d)", pattern.associatedTrips.size(), pattern.pattern_id, currentPatternIndex, patterns.size()); updateTripStatement.executeUpdate(); } currentPatternIndex += 1; } // Send any remaining prepared statement calls to the database backend. patternTracker.executeRemaining(); patternStopTracker.executeRemaining(); LOG.info("Done storing patterns and pattern stops."); if (postgresText) { // Finally, copy the pattern for trips text file into a table, create an index on trip IDs, and update // the trips table. LOG.info("Updating trips with pattern IDs"); patternForTripsFileStream.close(); // Copy file contents into temp pattern for trips table. copyFromFile(connection, tempPatternForTripsTextFile, tempPatternForTripsTable); // Before updating the trips with pattern IDs, index the table on trip_id. String patternForTripsIndexSql = String.format("create index temp_trips_pattern_id_idx on %s (trip_id)", tempPatternForTripsTable); LOG.info(patternForTripsIndexSql); statement.execute(patternForTripsIndexSql); // Finally, execute the update statement. String updateTripsSql = String.format("update %s set pattern_id = %s.pattern_id from %s where %s.trip_id = %s.trip_id", tripsTableName, tempPatternForTripsTable, tempPatternForTripsTable, tripsTableName, tempPatternForTripsTable); LOG.info(updateTripsSql); statement.executeUpdate(updateTripsSql); // Delete temp file. Temp table will be dropped after the transaction is committed. tempPatternForTripsTextFile.delete(); LOG.info("Updating trips complete"); } LOG.info("Creating index on patterns"); statement.executeUpdate(String.format("alter table %s add primary key (pattern_id)", patternsTableName)); LOG.info("Creating index on pattern stops"); statement.executeUpdate(String.format("alter table %s add primary key (pattern_id, stop_sequence)", patternStopsTableName)); // Index new pattern_id column on trips. The other tables are already indexed because they have primary keys. LOG.info("Indexing trips on pattern id."); statement.execute(String.format("create index trips_pattern_id_idx on %s (pattern_id)", tripsTableName)); LOG.info("Done indexing."); connection.commit(); } catch (SQLException | IOException e) { // Rollback transaction if failure occurs on creating patterns. DbUtils.rollbackAndCloseQuietly(connection); // This exception will be stored as a validator failure. throw new RuntimeException(e); } finally { // Close transaction finally. DbUtils.closeQuietly(connection); } } }
public class class_name { @Override public EClass getIfcColourOrFactor() { if (ifcColourOrFactorEClass == null) { ifcColourOrFactorEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(1123); } return ifcColourOrFactorEClass; } }
public class class_name { @Override public EClass getIfcColourOrFactor() { if (ifcColourOrFactorEClass == null) { ifcColourOrFactorEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(1123); // depends on control dependency: [if], data = [none] } return ifcColourOrFactorEClass; } }
public class class_name { public String getNumberText(final int digits) { String result = ""; for (int i = 0; i < digits; i++) { result = result + random.nextInt(10); } return result; } }
public class class_name { public String getNumberText(final int digits) { String result = ""; for (int i = 0; i < digits; i++) { result = result + random.nextInt(10); // depends on control dependency: [for], data = [none] } return result; } }
public class class_name { public static Set<InetAddress> getNeighbors(String keyspaceName, Range<Token> toRepair, Collection<String> dataCenters, Collection<String> hosts) { StorageService ss = StorageService.instance; Map<Range<Token>, List<InetAddress>> replicaSets = ss.getRangeToAddressMap(keyspaceName); Range<Token> rangeSuperSet = null; for (Range<Token> range : ss.getLocalRanges(keyspaceName)) { if (range.contains(toRepair)) { rangeSuperSet = range; break; } else if (range.intersects(toRepair)) { throw new IllegalArgumentException("Requested range intersects a local range but is not fully contained in one; this would lead to imprecise repair"); } } if (rangeSuperSet == null || !replicaSets.containsKey(rangeSuperSet)) return Collections.emptySet(); Set<InetAddress> neighbors = new HashSet<>(replicaSets.get(rangeSuperSet)); neighbors.remove(FBUtilities.getBroadcastAddress()); if (dataCenters != null) { TokenMetadata.Topology topology = ss.getTokenMetadata().cloneOnlyTokenMap().getTopology(); Set<InetAddress> dcEndpoints = Sets.newHashSet(); Multimap<String,InetAddress> dcEndpointsMap = topology.getDatacenterEndpoints(); for (String dc : dataCenters) { Collection<InetAddress> c = dcEndpointsMap.get(dc); if (c != null) dcEndpoints.addAll(c); } return Sets.intersection(neighbors, dcEndpoints); } else if (hosts != null) { Set<InetAddress> specifiedHost = new HashSet<>(); for (final String host : hosts) { try { final InetAddress endpoint = InetAddress.getByName(host.trim()); if (endpoint.equals(FBUtilities.getBroadcastAddress()) || neighbors.contains(endpoint)) specifiedHost.add(endpoint); } catch (UnknownHostException e) { throw new IllegalArgumentException("Unknown host specified " + host, e); } } if (!specifiedHost.contains(FBUtilities.getBroadcastAddress())) throw new IllegalArgumentException("The current host must be part of the repair"); if (specifiedHost.size() <= 1) { String msg = "Repair requires at least two endpoints that are neighbours before it can continue, the endpoint used for this repair is %s, " + "other available neighbours are %s but these neighbours were not part of the supplied list of hosts to use during the repair (%s)."; throw new IllegalArgumentException(String.format(msg, specifiedHost, neighbors, hosts)); } specifiedHost.remove(FBUtilities.getBroadcastAddress()); return specifiedHost; } return neighbors; } }
public class class_name { public static Set<InetAddress> getNeighbors(String keyspaceName, Range<Token> toRepair, Collection<String> dataCenters, Collection<String> hosts) { StorageService ss = StorageService.instance; Map<Range<Token>, List<InetAddress>> replicaSets = ss.getRangeToAddressMap(keyspaceName); Range<Token> rangeSuperSet = null; for (Range<Token> range : ss.getLocalRanges(keyspaceName)) { if (range.contains(toRepair)) { rangeSuperSet = range; // depends on control dependency: [if], data = [none] break; } else if (range.intersects(toRepair)) { throw new IllegalArgumentException("Requested range intersects a local range but is not fully contained in one; this would lead to imprecise repair"); } } if (rangeSuperSet == null || !replicaSets.containsKey(rangeSuperSet)) return Collections.emptySet(); Set<InetAddress> neighbors = new HashSet<>(replicaSets.get(rangeSuperSet)); neighbors.remove(FBUtilities.getBroadcastAddress()); if (dataCenters != null) { TokenMetadata.Topology topology = ss.getTokenMetadata().cloneOnlyTokenMap().getTopology(); Set<InetAddress> dcEndpoints = Sets.newHashSet(); Multimap<String,InetAddress> dcEndpointsMap = topology.getDatacenterEndpoints(); for (String dc : dataCenters) { Collection<InetAddress> c = dcEndpointsMap.get(dc); if (c != null) dcEndpoints.addAll(c); } return Sets.intersection(neighbors, dcEndpoints); // depends on control dependency: [if], data = [none] } else if (hosts != null) { Set<InetAddress> specifiedHost = new HashSet<>(); for (final String host : hosts) { try { final InetAddress endpoint = InetAddress.getByName(host.trim()); if (endpoint.equals(FBUtilities.getBroadcastAddress()) || neighbors.contains(endpoint)) specifiedHost.add(endpoint); } catch (UnknownHostException e) { throw new IllegalArgumentException("Unknown host specified " + host, e); } // depends on control dependency: [catch], data = [none] } if (!specifiedHost.contains(FBUtilities.getBroadcastAddress())) throw new IllegalArgumentException("The current host must be part of the repair"); if (specifiedHost.size() <= 1) { String msg = "Repair requires at least two endpoints that are neighbours before it can continue, the endpoint used for this repair is %s, " + "other available neighbours are %s but these neighbours were not part of the supplied list of hosts to use during the repair (%s)."; // depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none] // depends on control dependency: [if], data = [none] throw new IllegalArgumentException(String.format(msg, specifiedHost, neighbors, hosts)); } specifiedHost.remove(FBUtilities.getBroadcastAddress()); // depends on control dependency: [if], data = [none] return specifiedHost; // depends on control dependency: [if], data = [none] } return neighbors; } }
public class class_name { private static String translateEscaping(String pattern, char from, char to) { // if escape characters are the same OR pattern does not contain any // escape characters -> simply return pattern as is. if (from == to || (pattern.indexOf(from) < 0 && pattern.indexOf(to) < 0)) { return pattern; } StringBuilder translated = new StringBuilder(pattern.length()); boolean escaped = false; for (int i = 0; i < pattern.length(); i++) { if (pattern.charAt(i) == from) { if (escaped) { translated.append(from); escaped = false; } else { escaped = true; } } else if (pattern.charAt(i) == to) { if (escaped) { translated.append(to).append(to); escaped = false; } else { translated.append(to).append(to); } } else { if (escaped) { translated.append(to); escaped = false; } translated.append(pattern.charAt(i)); } } return translated.toString(); } }
public class class_name { private static String translateEscaping(String pattern, char from, char to) { // if escape characters are the same OR pattern does not contain any // escape characters -> simply return pattern as is. if (from == to || (pattern.indexOf(from) < 0 && pattern.indexOf(to) < 0)) { return pattern; // depends on control dependency: [if], data = [none] } StringBuilder translated = new StringBuilder(pattern.length()); boolean escaped = false; for (int i = 0; i < pattern.length(); i++) { if (pattern.charAt(i) == from) { if (escaped) { translated.append(from); // depends on control dependency: [if], data = [none] escaped = false; // depends on control dependency: [if], data = [none] } else { escaped = true; // depends on control dependency: [if], data = [none] } } else if (pattern.charAt(i) == to) { if (escaped) { translated.append(to).append(to); // depends on control dependency: [if], data = [none] escaped = false; // depends on control dependency: [if], data = [none] } else { translated.append(to).append(to); // depends on control dependency: [if], data = [none] } } else { if (escaped) { translated.append(to); // depends on control dependency: [if], data = [none] escaped = false; // depends on control dependency: [if], data = [none] } translated.append(pattern.charAt(i)); // depends on control dependency: [if], data = [(pattern.charAt(i)] } } return translated.toString(); } }
public class class_name { public static boolean kill(int processId) { String killCommand = String.format("%s %d", (SystemUtils.isWindows() ? WINDOWS_KILL_COMMAND : UNIX_KILL_COMMAND), processId); try { Process killProcess = Runtime.getRuntime().exec(killCommand); return killProcess.waitFor(KILL_WAIT_TIMEOUT, KILL_WAIT_TIME_UNIT); } catch (Throwable ignore) { return false; } } }
public class class_name { public static boolean kill(int processId) { String killCommand = String.format("%s %d", (SystemUtils.isWindows() ? WINDOWS_KILL_COMMAND : UNIX_KILL_COMMAND), processId); try { Process killProcess = Runtime.getRuntime().exec(killCommand); return killProcess.waitFor(KILL_WAIT_TIMEOUT, KILL_WAIT_TIME_UNIT); // depends on control dependency: [try], data = [none] } catch (Throwable ignore) { return false; } // depends on control dependency: [catch], data = [none] } }
public class class_name { @Override public Boolean call() throws Exception { error.set(null); List<Callable<Boolean>> subtasks = Lists.newArrayList(); // We are iterating the entire ring using an arbitrary number of threads if (this.concurrencyLevel != null || startToken != null|| endToken != null) { List<TokenRange> tokens = partitioner.splitTokenRange( startToken == null ? partitioner.getMinToken() : startToken, endToken == null ? partitioner.getMinToken() : endToken, this.concurrencyLevel == null ? 1 : this.concurrencyLevel); for (TokenRange range : tokens) { subtasks.add(makeTokenRangeTask(range.getStartToken(), range.getEndToken())); } } // We are iterating through each token range else { List<TokenRange> ranges = keyspace.describeRing(dc, rack); for (TokenRange range : ranges) { if (range.getStartToken().equals(range.getEndToken())) subtasks.add(makeTokenRangeTask(range.getStartToken(), range.getEndToken())); else subtasks.add(makeTokenRangeTask(partitioner.getTokenMinusOne(range.getStartToken()), range.getEndToken())); } } try { // Use a local executor if (executor == null) { ExecutorService localExecutor = Executors .newFixedThreadPool(subtasks.size(), new ThreadFactoryBuilder().setDaemon(true) .setNameFormat("AstyanaxAllRowsReader-%d") .build()); try { futures.addAll(startTasks(localExecutor, subtasks)); return waitForTasksToFinish(); } finally { localExecutor.shutdownNow(); } } // Use an externally provided executor else { futures.addAll(startTasks(executor, subtasks)); return waitForTasksToFinish(); } } catch (Exception e) { error.compareAndSet(null, e); LOG.warn("AllRowsReader terminated. " + e.getMessage(), e); cancel(); throw error.get(); } } }
public class class_name { @Override public Boolean call() throws Exception { error.set(null); List<Callable<Boolean>> subtasks = Lists.newArrayList(); // We are iterating the entire ring using an arbitrary number of threads if (this.concurrencyLevel != null || startToken != null|| endToken != null) { List<TokenRange> tokens = partitioner.splitTokenRange( startToken == null ? partitioner.getMinToken() : startToken, endToken == null ? partitioner.getMinToken() : endToken, this.concurrencyLevel == null ? 1 : this.concurrencyLevel); for (TokenRange range : tokens) { subtasks.add(makeTokenRangeTask(range.getStartToken(), range.getEndToken())); // depends on control dependency: [for], data = [range] } } // We are iterating through each token range else { List<TokenRange> ranges = keyspace.describeRing(dc, rack); for (TokenRange range : ranges) { if (range.getStartToken().equals(range.getEndToken())) subtasks.add(makeTokenRangeTask(range.getStartToken(), range.getEndToken())); else subtasks.add(makeTokenRangeTask(partitioner.getTokenMinusOne(range.getStartToken()), range.getEndToken())); } } try { // Use a local executor if (executor == null) { ExecutorService localExecutor = Executors .newFixedThreadPool(subtasks.size(), new ThreadFactoryBuilder().setDaemon(true) .setNameFormat("AstyanaxAllRowsReader-%d") .build()); try { futures.addAll(startTasks(localExecutor, subtasks)); // depends on control dependency: [try], data = [none] return waitForTasksToFinish(); // depends on control dependency: [try], data = [none] } finally { localExecutor.shutdownNow(); } } // Use an externally provided executor else { futures.addAll(startTasks(executor, subtasks)); // depends on control dependency: [if], data = [(executor] return waitForTasksToFinish(); // depends on control dependency: [if], data = [none] } } catch (Exception e) { error.compareAndSet(null, e); LOG.warn("AllRowsReader terminated. " + e.getMessage(), e); cancel(); throw error.get(); } } }
public class class_name { protected static void init(ServletContext context) { TimeInterval interval = new TimeInterval(); servletContext = context; contextPath = context.getContextPath(); handler = new ActionHandler(HuluSetting.actionPackages); String startMsg = null; try { startMsg = FileUtil.readUtf8String("startup.txt"); } catch (IORuntimeException e) { Throwable cause = e.getCause(); if(null != cause){ if(cause instanceof FileNotFoundException){ log.debug("No file [startup.txt] in classpath, use default start messsage."); }else{ log.warn("Read [startup.txt] error, cause by: {}", cause.getMessage()); } }else{ log.warn("Read [startup.txt] error, cause by: {}", e.getMessage()); } } if(StrUtil.isNotBlank(startMsg)){ Dict param = Dict.create().set("spend", interval.intervalMs()).set("contextPath", contextPath); log.info(StrUtil.format("\n" + startMsg, param)); }else{ log.info("\n***** Hulu framwork init finished, context path: [{}], spend {}ms *****", contextPath, interval.intervalMs()); } } }
public class class_name { protected static void init(ServletContext context) { TimeInterval interval = new TimeInterval(); servletContext = context; contextPath = context.getContextPath(); handler = new ActionHandler(HuluSetting.actionPackages); String startMsg = null; try { startMsg = FileUtil.readUtf8String("startup.txt"); // depends on control dependency: [try], data = [none] } catch (IORuntimeException e) { Throwable cause = e.getCause(); if(null != cause){ if(cause instanceof FileNotFoundException){ log.debug("No file [startup.txt] in classpath, use default start messsage."); // depends on control dependency: [if], data = [none] }else{ log.warn("Read [startup.txt] error, cause by: {}", cause.getMessage()); // depends on control dependency: [if], data = [none] } }else{ log.warn("Read [startup.txt] error, cause by: {}", e.getMessage()); // depends on control dependency: [if], data = [none] } } // depends on control dependency: [catch], data = [none] if(StrUtil.isNotBlank(startMsg)){ Dict param = Dict.create().set("spend", interval.intervalMs()).set("contextPath", contextPath); log.info(StrUtil.format("\n" + startMsg, param)); // depends on control dependency: [if], data = [none] }else{ log.info("\n***** Hulu framwork init finished, context path: [{}], spend {}ms *****", contextPath, interval.intervalMs()); // depends on control dependency: [if], data = [none] } } }
public class class_name { void onComplete(TraceRouteThread trace, boolean isError, boolean isArrived, TraceRouteContainer routeContainer) { if (threads != null) { synchronized (mLock) { try { threads.remove(trace); } catch (NullPointerException e) { e.printStackTrace(); } } } if (!isDone) { if (isError) this.errorCount++; this.isArrived = isArrived; if (routeContainers != null && routeContainer != null) routeContainers.add(routeContainer); } if (countDownLatch != null && countDownLatch.getCount() > 0) countDownLatch.countDown(); } }
public class class_name { void onComplete(TraceRouteThread trace, boolean isError, boolean isArrived, TraceRouteContainer routeContainer) { if (threads != null) { synchronized (mLock) { // depends on control dependency: [if], data = [none] try { threads.remove(trace); // depends on control dependency: [try], data = [none] } catch (NullPointerException e) { e.printStackTrace(); } // depends on control dependency: [catch], data = [none] } } if (!isDone) { if (isError) this.errorCount++; this.isArrived = isArrived; // depends on control dependency: [if], data = [none] if (routeContainers != null && routeContainer != null) routeContainers.add(routeContainer); } if (countDownLatch != null && countDownLatch.getCount() > 0) countDownLatch.countDown(); } }
public class class_name { public Object evaluate() { if( !isCompileTimeConstant() ) { return super.evaluate(); } return (Boolean)getCondition().evaluate() ? getFirst().evaluate() : getSecond().evaluate(); } }
public class class_name { public Object evaluate() { if( !isCompileTimeConstant() ) { return super.evaluate(); // depends on control dependency: [if], data = [none] } return (Boolean)getCondition().evaluate() ? getFirst().evaluate() : getSecond().evaluate(); } }
public class class_name { public void setDialogDeleteFileMode(String mode) { CmsResourceDeleteMode deleteMode = CmsResource.DELETE_PRESERVE_SIBLINGS; if (mode.equalsIgnoreCase(DELETEMODE_DELETE)) { deleteMode = CmsResource.DELETE_REMOVE_SIBLINGS; } setDialogDeleteFileMode(deleteMode); } }
public class class_name { public void setDialogDeleteFileMode(String mode) { CmsResourceDeleteMode deleteMode = CmsResource.DELETE_PRESERVE_SIBLINGS; if (mode.equalsIgnoreCase(DELETEMODE_DELETE)) { deleteMode = CmsResource.DELETE_REMOVE_SIBLINGS; // depends on control dependency: [if], data = [none] } setDialogDeleteFileMode(deleteMode); } }
public class class_name { private static Locale strip(Locale locale) { String language = locale.getLanguage(); String country = locale.getCountry(); String variant = locale.getVariant(); if (!variant.isEmpty()) { variant = ""; } else if (!country.isEmpty()) { country = ""; } else if (!language.isEmpty()) { language = ""; } else { return null; } return new Locale(language, country, variant); } }
public class class_name { private static Locale strip(Locale locale) { String language = locale.getLanguage(); String country = locale.getCountry(); String variant = locale.getVariant(); if (!variant.isEmpty()) { variant = ""; // depends on control dependency: [if], data = [none] } else if (!country.isEmpty()) { country = ""; // depends on control dependency: [if], data = [none] } else if (!language.isEmpty()) { language = ""; // depends on control dependency: [if], data = [none] } else { return null; // depends on control dependency: [if], data = [none] } return new Locale(language, country, variant); } }
public class class_name { protected void encodeMandatoryVariableParameters(Map<Integer, ISUPParameter> parameters, ByteArrayOutputStream bos, boolean isOptionalPartPresent) throws ParameterException { try { byte[] pointers = null; // complicated if (!mandatoryVariablePartPossible()) { // we ommit pointer to this part, go straight for optional pointer. if (optionalPartIsPossible()) { if (isOptionalPartPresent) { pointers = new byte[] { 0x01 }; } else { // zeros pointers = new byte[] { 0x00 }; } bos.write(pointers); } else { // do nothing? } } else { if (optionalPartIsPossible()) { pointers = new byte[parameters.size() + 1]; } else { pointers = new byte[parameters.size()]; } ByteArrayOutputStream parametersBodyBOS = new ByteArrayOutputStream(); byte lastParameterLength = 0; byte currentParameterLength = 0; for (int index = 0; index < parameters.size(); index++) { AbstractISUPParameter p = (AbstractISUPParameter) parameters.get(index); byte[] body = p.encode(); currentParameterLength = (byte) body.length; if (body.length > 255) { // FIXME: is this check valid? throw new ParameterException("Length of body must not be greater than one octet - 255 "); } if (index == 0) { lastParameterLength = currentParameterLength; // This creates pointer to first mandatory variable param, // check on optional is required, since if its not defined // by message, pointer is omited. pointers[index] = (byte) (parameters.size() + (optionalPartIsPossible() ? 1 : 0)); } else { pointers[index] = (byte) (pointers[index - 1] + lastParameterLength); lastParameterLength = currentParameterLength; } parametersBodyBOS.write(currentParameterLength); parametersBodyBOS.write(body); } // we ommit pointer to this part, go straight for optional pointer. if (optionalPartIsPossible()) { if (isOptionalPartPresent) { pointers[pointers.length - 1] = (byte) (pointers[pointers.length - 2] + lastParameterLength); } else { // zeros // pointers=new byte[]{0x00}; } } else { // do nothing? } bos.write(pointers); bos.write(parametersBodyBOS.toByteArray()); } } catch (ParameterException pe) { throw pe; } catch (Exception e) { throw new ParameterException(e); } } }
public class class_name { protected void encodeMandatoryVariableParameters(Map<Integer, ISUPParameter> parameters, ByteArrayOutputStream bos, boolean isOptionalPartPresent) throws ParameterException { try { byte[] pointers = null; // complicated if (!mandatoryVariablePartPossible()) { // we ommit pointer to this part, go straight for optional pointer. if (optionalPartIsPossible()) { if (isOptionalPartPresent) { pointers = new byte[] { 0x01 }; // depends on control dependency: [if], data = [none] } else { // zeros pointers = new byte[] { 0x00 }; // depends on control dependency: [if], data = [none] } bos.write(pointers); } else { // do nothing? } } else { if (optionalPartIsPossible()) { pointers = new byte[parameters.size() + 1]; } else { pointers = new byte[parameters.size()]; } ByteArrayOutputStream parametersBodyBOS = new ByteArrayOutputStream(); byte lastParameterLength = 0; byte currentParameterLength = 0; for (int index = 0; index < parameters.size(); index++) { AbstractISUPParameter p = (AbstractISUPParameter) parameters.get(index); byte[] body = p.encode(); currentParameterLength = (byte) body.length; if (body.length > 255) { // FIXME: is this check valid? throw new ParameterException("Length of body must not be greater than one octet - 255 "); } if (index == 0) { lastParameterLength = currentParameterLength; // This creates pointer to first mandatory variable param, // check on optional is required, since if its not defined // by message, pointer is omited. pointers[index] = (byte) (parameters.size() + (optionalPartIsPossible() ? 1 : 0)); } else { pointers[index] = (byte) (pointers[index - 1] + lastParameterLength); lastParameterLength = currentParameterLength; } parametersBodyBOS.write(currentParameterLength); parametersBodyBOS.write(body); } // we ommit pointer to this part, go straight for optional pointer. if (optionalPartIsPossible()) { if (isOptionalPartPresent) { pointers[pointers.length - 1] = (byte) (pointers[pointers.length - 2] + lastParameterLength); } else { // zeros // pointers=new byte[]{0x00}; } } else { // do nothing? } bos.write(pointers); bos.write(parametersBodyBOS.toByteArray()); } } catch (ParameterException pe) { throw pe; } catch (Exception e) { throw new ParameterException(e); } } }
public class class_name { public static void write(ClassificationDataSet data, OutputStream os) { PrintWriter writer = new PrintWriter(os); for(int i = 0; i < data.size(); i++) { int pred = data.getDataPointCategory(i); Vec vals = data.getDataPoint(i).getNumericalValues(); writer.write(pred + " "); for(IndexValue iv : vals) { double val = iv.getValue(); if(Math.rint(val) == val)//cast to long before writting to save space writer.write((iv.getIndex()+1) + ":" + (long)val + " ");//+1 b/c 1 based indexing else writer.write((iv.getIndex()+1) + ":" + val + " ");//+1 b/c 1 based indexing } writer.write("\n"); } writer.flush(); writer.close(); } }
public class class_name { public static void write(ClassificationDataSet data, OutputStream os) { PrintWriter writer = new PrintWriter(os); for(int i = 0; i < data.size(); i++) { int pred = data.getDataPointCategory(i); Vec vals = data.getDataPoint(i).getNumericalValues(); writer.write(pred + " "); // depends on control dependency: [for], data = [none] for(IndexValue iv : vals) { double val = iv.getValue(); if(Math.rint(val) == val)//cast to long before writting to save space writer.write((iv.getIndex()+1) + ":" + (long)val + " ");//+1 b/c 1 based indexing else writer.write((iv.getIndex()+1) + ":" + val + " ");//+1 b/c 1 based indexing } writer.write("\n"); // depends on control dependency: [for], data = [none] } writer.flush(); writer.close(); } }
public class class_name { public static Iterator<String> iterateClassnames(final File parentDirectory, final Iterator<File> classFileIterator) { return new Iterator<String>(){ @Override public boolean hasNext() { return classFileIterator == null ? false : classFileIterator.hasNext(); } @Override public String next() { final File classFile = classFileIterator.next(); try { // possible returns null return extractClassNameFromFile(parentDirectory, classFile); } catch (final IOException e) { throw new RuntimeException(e.getMessage()); } } @Override public void remove() { classFileIterator.remove(); } }; } }
public class class_name { public static Iterator<String> iterateClassnames(final File parentDirectory, final Iterator<File> classFileIterator) { return new Iterator<String>(){ @Override public boolean hasNext() { return classFileIterator == null ? false : classFileIterator.hasNext(); } @Override public String next() { final File classFile = classFileIterator.next(); try { // possible returns null return extractClassNameFromFile(parentDirectory, classFile); // depends on control dependency: [try], data = [none] } catch (final IOException e) { throw new RuntimeException(e.getMessage()); } // depends on control dependency: [catch], data = [none] } @Override public void remove() { classFileIterator.remove(); } }; } }
public class class_name { private static GVRSceneObject loadSceneObjectFromModel(GVRContext context, String modelFile) { final GVRAssetLoader loader = context.getAssetLoader(); final EnumSet<GVRImportSettings> settings = GVRImportSettings.getRecommendedSettings(); try { Log.d(Log.SUBSYSTEM.WIDGET, TAG, "loadSceneObjectFromModel(): attemping to load '%s'", modelFile); return loader.loadModel(modelFile, settings, true, null); } catch (IOException e) { Log.e(TAG, e, "loadSceneObjectFromModel(): failed to load model for Widget: %s", modelFile); throw new RuntimeException("Failed to load Widget model from " + modelFile, e); } } }
public class class_name { private static GVRSceneObject loadSceneObjectFromModel(GVRContext context, String modelFile) { final GVRAssetLoader loader = context.getAssetLoader(); final EnumSet<GVRImportSettings> settings = GVRImportSettings.getRecommendedSettings(); try { Log.d(Log.SUBSYSTEM.WIDGET, TAG, "loadSceneObjectFromModel(): attemping to load '%s'", modelFile); // depends on control dependency: [try], data = [none] return loader.loadModel(modelFile, settings, true, null); // depends on control dependency: [try], data = [none] } catch (IOException e) { Log.e(TAG, e, "loadSceneObjectFromModel(): failed to load model for Widget: %s", modelFile); throw new RuntimeException("Failed to load Widget model from " + modelFile, e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { @Override @SuppressWarnings("unchecked") @ConstantTime(amortized = true) public void meld(MergeableAddressableHeap<K, V> other) { SimpleFibonacciHeap<K, V> h = (SimpleFibonacciHeap<K, V>) other; // check same comparator if (comparator != null) { if (h.comparator == null || !h.comparator.equals(comparator)) { throw new IllegalArgumentException("Cannot meld heaps using different comparators!"); } } else if (h.comparator != null) { throw new IllegalArgumentException("Cannot meld heaps using different comparators!"); } if (h.other != h) { throw new IllegalStateException("A heap cannot be used after a meld."); } // meld if (root == null) { root = h.root; } else if (h.root != null) { if (comparator == null) { if (((Comparable<? super K>) h.root.key).compareTo(root.key) < 0) { root = link(root, h.root); } else { link(h.root, root); } } else { if (comparator.compare(h.root.key, root.key) < 0) { root = link(root, h.root); } else { link(h.root, root); } } } size += h.size; // clear other h.size = 0; h.root = null; // take ownership h.other = this; } }
public class class_name { @Override @SuppressWarnings("unchecked") @ConstantTime(amortized = true) public void meld(MergeableAddressableHeap<K, V> other) { SimpleFibonacciHeap<K, V> h = (SimpleFibonacciHeap<K, V>) other; // check same comparator if (comparator != null) { if (h.comparator == null || !h.comparator.equals(comparator)) { throw new IllegalArgumentException("Cannot meld heaps using different comparators!"); } } else if (h.comparator != null) { throw new IllegalArgumentException("Cannot meld heaps using different comparators!"); } if (h.other != h) { throw new IllegalStateException("A heap cannot be used after a meld."); } // meld if (root == null) { root = h.root; // depends on control dependency: [if], data = [none] } else if (h.root != null) { if (comparator == null) { if (((Comparable<? super K>) h.root.key).compareTo(root.key) < 0) { root = link(root, h.root); // depends on control dependency: [if], data = [none] } else { link(h.root, root); // depends on control dependency: [if], data = [none] } } else { if (comparator.compare(h.root.key, root.key) < 0) { root = link(root, h.root); // depends on control dependency: [if], data = [none] } else { link(h.root, root); // depends on control dependency: [if], data = [none] } } } size += h.size; // clear other h.size = 0; h.root = null; // take ownership h.other = this; } }
public class class_name { protected void ensureNamespacesCapacity() { // int size) { // int namespaceSize = namespacePrefix != null ? namespacePrefix.length // : 0; // assert (namespaceEnd >= namespacePrefix.length); // if(size >= namespaceSize) { // int newSize = size > 7 ? 2 * size : 8; // = lucky 7 + 1 //25 final int newSize = namespaceEnd > 7 ? 2 * namespaceEnd : 8; if (TRACE_SIZING) { System.err.println(getClass().getName() + " namespaceSize " + namespacePrefix.length + " ==> " + newSize); } final String[] newNamespacePrefix = new String[newSize]; final String[] newNamespaceUri = new String[newSize]; if (namespacePrefix != null) { System.arraycopy(namespacePrefix, 0, newNamespacePrefix, 0, namespaceEnd); System.arraycopy(namespaceUri, 0, newNamespaceUri, 0, namespaceEnd); } namespacePrefix = newNamespacePrefix; namespaceUri = newNamespaceUri; // TODO use hashes for quick namespace->prefix lookups // if( ! allStringsInterned ) { // int[] newNamespacePrefixHash = new int[newSize]; // if(namespacePrefixHash != null) { // System.arraycopy( // namespacePrefixHash, 0, newNamespacePrefixHash, 0, namespaceEnd); // } // namespacePrefixHash = newNamespacePrefixHash; // } // prefixesSize = newSize; // ////assert nsPrefixes.length > size && nsPrefixes.length == newSize // } } }
public class class_name { protected void ensureNamespacesCapacity() { // int size) { // int namespaceSize = namespacePrefix != null ? namespacePrefix.length // : 0; // assert (namespaceEnd >= namespacePrefix.length); // if(size >= namespaceSize) { // int newSize = size > 7 ? 2 * size : 8; // = lucky 7 + 1 //25 final int newSize = namespaceEnd > 7 ? 2 * namespaceEnd : 8; if (TRACE_SIZING) { System.err.println(getClass().getName() + " namespaceSize " + namespacePrefix.length + " ==> " + newSize); // depends on control dependency: [if], data = [none] } final String[] newNamespacePrefix = new String[newSize]; final String[] newNamespaceUri = new String[newSize]; if (namespacePrefix != null) { System.arraycopy(namespacePrefix, 0, newNamespacePrefix, 0, namespaceEnd); // depends on control dependency: [if], data = [(namespacePrefix] System.arraycopy(namespaceUri, 0, newNamespaceUri, 0, namespaceEnd); // depends on control dependency: [if], data = [none] } namespacePrefix = newNamespacePrefix; namespaceUri = newNamespaceUri; // TODO use hashes for quick namespace->prefix lookups // if( ! allStringsInterned ) { // int[] newNamespacePrefixHash = new int[newSize]; // if(namespacePrefixHash != null) { // System.arraycopy( // namespacePrefixHash, 0, newNamespacePrefixHash, 0, namespaceEnd); // } // namespacePrefixHash = newNamespacePrefixHash; // } // prefixesSize = newSize; // ////assert nsPrefixes.length > size && nsPrefixes.length == newSize // } } }
public class class_name { private FeatureTableData buildMapClickTableData(LatLng latLng, double zoom, BoundingBox boundingBox, double tolerance, Projection projection) { FeatureTableData tableData = null; // Verify the features are indexed and we are getting information if (isIndexed() && (maxFeaturesInfo || featuresInfo)) { if (isOnAtCurrentZoom(zoom, latLng)) { // Get the number of features in the tile location long tileFeatureCount = tileFeatureCount(latLng, zoom); // If more than a configured max features to draw if (isMoreThanMaxFeatures(tileFeatureCount)) { // Build the max features message if (maxFeaturesInfo) { tableData = new FeatureTableData(featureTiles.getFeatureDao().getTableName(), tileFeatureCount); } } // Else, query for the features near the click else if (featuresInfo) { // Query for results and build the message FeatureIndexResults results = queryFeatures(boundingBox, projection); tableData = featureInfoBuilder.buildTableDataAndClose(results, tolerance, latLng, projection); } } } return tableData; } }
public class class_name { private FeatureTableData buildMapClickTableData(LatLng latLng, double zoom, BoundingBox boundingBox, double tolerance, Projection projection) { FeatureTableData tableData = null; // Verify the features are indexed and we are getting information if (isIndexed() && (maxFeaturesInfo || featuresInfo)) { if (isOnAtCurrentZoom(zoom, latLng)) { // Get the number of features in the tile location long tileFeatureCount = tileFeatureCount(latLng, zoom); // If more than a configured max features to draw if (isMoreThanMaxFeatures(tileFeatureCount)) { // Build the max features message if (maxFeaturesInfo) { tableData = new FeatureTableData(featureTiles.getFeatureDao().getTableName(), tileFeatureCount); // depends on control dependency: [if], data = [none] } } // Else, query for the features near the click else if (featuresInfo) { // Query for results and build the message FeatureIndexResults results = queryFeatures(boundingBox, projection); tableData = featureInfoBuilder.buildTableDataAndClose(results, tolerance, latLng, projection); // depends on control dependency: [if], data = [none] } } } return tableData; } }
public class class_name { public static List<HostAndPort> splitToHostsAndPorts(String hostPortQuorumList) { // split an address hot String[] strings = StringUtils.getStrings(hostPortQuorumList); int len = 0; if (strings != null) { len = strings.length; } List<HostAndPort> list = new ArrayList<HostAndPort>(len); if (strings != null) { for (String s : strings) { list.add(HostAndPort.fromString(s.trim()).withDefaultPort(DEFAULT_PORT)); } } return list; } }
public class class_name { public static List<HostAndPort> splitToHostsAndPorts(String hostPortQuorumList) { // split an address hot String[] strings = StringUtils.getStrings(hostPortQuorumList); int len = 0; if (strings != null) { len = strings.length; // depends on control dependency: [if], data = [none] } List<HostAndPort> list = new ArrayList<HostAndPort>(len); if (strings != null) { for (String s : strings) { list.add(HostAndPort.fromString(s.trim()).withDefaultPort(DEFAULT_PORT)); // depends on control dependency: [for], data = [s] } } return list; } }
public class class_name { public void marshall(City city, ProtocolMarshaller protocolMarshaller) { if (city == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(city.getCityName(), CITYNAME_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(City city, ProtocolMarshaller protocolMarshaller) { if (city == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(city.getCityName(), CITYNAME_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 boolean isNearTo(Double2D location, double distance) { if (this.is2DLocation()) { return this.getLocation2D().distance(location) < distance; } else { return false; } } }
public class class_name { public boolean isNearTo(Double2D location, double distance) { if (this.is2DLocation()) { return this.getLocation2D().distance(location) < distance; // depends on control dependency: [if], data = [none] } else { return false; // depends on control dependency: [if], data = [none] } } }
public class class_name { public static String join (Iterable<?> items, String sep) { Iterator<?> i = items.iterator(); if (!i.hasNext()) { return ""; } StringBuilder buf = new StringBuilder(String.valueOf(i.next())); while (i.hasNext()) { buf.append(sep).append(i.next()); } return buf.toString(); } }
public class class_name { public static String join (Iterable<?> items, String sep) { Iterator<?> i = items.iterator(); if (!i.hasNext()) { return ""; // depends on control dependency: [if], data = [none] } StringBuilder buf = new StringBuilder(String.valueOf(i.next())); while (i.hasNext()) { buf.append(sep).append(i.next()); // depends on control dependency: [while], data = [none] } return buf.toString(); } }
public class class_name { @Override public void applicationStarted(ApplicationInfo appInfo) throws StateChangeException { // If we can't get the J2EEName of the application, then we don't care about this application. String appName = appInfo.getDeploymentName(); if (null == appName) return; // We only care about applications that have had web module metadata created. // The remove operation returns null if we don't find this app in webModulesInStartingApps ConcurrentHashMap<J2EEName,WebModuleMetaData> modules = webModulesInStartingApps.remove(appName); if (null != modules) { // We found the metadata for this app, and it has been removed from webModulesInStartingApps. // Now take the modules we removed from webModulesInStartingApps, and add them to webModulesInStartedApps webModulesInStartedApps.put(appName, modules); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Web application started - " + appName); } } } }
public class class_name { @Override public void applicationStarted(ApplicationInfo appInfo) throws StateChangeException { // If we can't get the J2EEName of the application, then we don't care about this application. String appName = appInfo.getDeploymentName(); if (null == appName) return; // We only care about applications that have had web module metadata created. // The remove operation returns null if we don't find this app in webModulesInStartingApps ConcurrentHashMap<J2EEName,WebModuleMetaData> modules = webModulesInStartingApps.remove(appName); if (null != modules) { // We found the metadata for this app, and it has been removed from webModulesInStartingApps. // Now take the modules we removed from webModulesInStartingApps, and add them to webModulesInStartedApps webModulesInStartedApps.put(appName, modules); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Web application started - " + appName); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public static HttpCarbonMessage createInboundReqCarbonMsg(HttpRequest httpRequestHeaders, ChannelHandlerContext ctx, SourceHandler sourceHandler) { HttpCarbonMessage inboundRequestMsg = new HttpCarbonRequest(httpRequestHeaders, new DefaultListener(ctx)); inboundRequestMsg.setProperty(Constants.POOLED_BYTE_BUFFER_FACTORY, new PooledDataStreamerFactory(ctx.alloc())); inboundRequestMsg.setProperty(Constants.CHNL_HNDLR_CTX, ctx); inboundRequestMsg.setProperty(Constants.SRC_HANDLER, sourceHandler); HttpVersion protocolVersion = httpRequestHeaders.protocolVersion(); inboundRequestMsg.setProperty(Constants.HTTP_VERSION, protocolVersion.majorVersion() + "." + protocolVersion.minorVersion()); inboundRequestMsg.setProperty(Constants.HTTP_METHOD, httpRequestHeaders.method().name()); InetSocketAddress localAddress = null; //This check was added because in case of netty embedded channel, this could be of type 'EmbeddedSocketAddress'. if (ctx.channel().localAddress() instanceof InetSocketAddress) { localAddress = (InetSocketAddress) ctx.channel().localAddress(); } inboundRequestMsg.setProperty(Constants.LISTENER_PORT, localAddress != null ? localAddress.getPort() : null); inboundRequestMsg.setProperty(Constants.LISTENER_INTERFACE_ID, sourceHandler.getInterfaceId()); inboundRequestMsg.setProperty(Constants.PROTOCOL, Constants.HTTP_SCHEME); boolean isSecuredConnection = false; if (ctx.channel().pipeline().get(Constants.SSL_HANDLER) != null) { isSecuredConnection = true; } inboundRequestMsg.setProperty(Constants.IS_SECURED_CONNECTION, isSecuredConnection); inboundRequestMsg.setProperty(Constants.LOCAL_ADDRESS, ctx.channel().localAddress()); inboundRequestMsg.setProperty(Constants.REMOTE_ADDRESS, sourceHandler.getRemoteAddress()); inboundRequestMsg.setProperty(Constants.REQUEST_URL, httpRequestHeaders.uri()); inboundRequestMsg.setProperty(Constants.TO, httpRequestHeaders.uri()); inboundRequestMsg.setProperty(MUTUAL_SSL_HANDSHAKE_RESULT, ctx.channel().attr(Constants.MUTUAL_SSL_RESULT_ATTRIBUTE).get()); return inboundRequestMsg; } }
public class class_name { public static HttpCarbonMessage createInboundReqCarbonMsg(HttpRequest httpRequestHeaders, ChannelHandlerContext ctx, SourceHandler sourceHandler) { HttpCarbonMessage inboundRequestMsg = new HttpCarbonRequest(httpRequestHeaders, new DefaultListener(ctx)); inboundRequestMsg.setProperty(Constants.POOLED_BYTE_BUFFER_FACTORY, new PooledDataStreamerFactory(ctx.alloc())); inboundRequestMsg.setProperty(Constants.CHNL_HNDLR_CTX, ctx); inboundRequestMsg.setProperty(Constants.SRC_HANDLER, sourceHandler); HttpVersion protocolVersion = httpRequestHeaders.protocolVersion(); inboundRequestMsg.setProperty(Constants.HTTP_VERSION, protocolVersion.majorVersion() + "." + protocolVersion.minorVersion()); inboundRequestMsg.setProperty(Constants.HTTP_METHOD, httpRequestHeaders.method().name()); InetSocketAddress localAddress = null; //This check was added because in case of netty embedded channel, this could be of type 'EmbeddedSocketAddress'. if (ctx.channel().localAddress() instanceof InetSocketAddress) { localAddress = (InetSocketAddress) ctx.channel().localAddress(); // depends on control dependency: [if], data = [none] } inboundRequestMsg.setProperty(Constants.LISTENER_PORT, localAddress != null ? localAddress.getPort() : null); inboundRequestMsg.setProperty(Constants.LISTENER_INTERFACE_ID, sourceHandler.getInterfaceId()); inboundRequestMsg.setProperty(Constants.PROTOCOL, Constants.HTTP_SCHEME); boolean isSecuredConnection = false; if (ctx.channel().pipeline().get(Constants.SSL_HANDLER) != null) { isSecuredConnection = true; // depends on control dependency: [if], data = [none] } inboundRequestMsg.setProperty(Constants.IS_SECURED_CONNECTION, isSecuredConnection); inboundRequestMsg.setProperty(Constants.LOCAL_ADDRESS, ctx.channel().localAddress()); inboundRequestMsg.setProperty(Constants.REMOTE_ADDRESS, sourceHandler.getRemoteAddress()); inboundRequestMsg.setProperty(Constants.REQUEST_URL, httpRequestHeaders.uri()); inboundRequestMsg.setProperty(Constants.TO, httpRequestHeaders.uri()); inboundRequestMsg.setProperty(MUTUAL_SSL_HANDSHAKE_RESULT, ctx.channel().attr(Constants.MUTUAL_SSL_RESULT_ATTRIBUTE).get()); return inboundRequestMsg; } }
public class class_name { public static boolean isResolved(Type type) { if (type instanceof GenericArrayType) { return isResolved(((GenericArrayType) type).getGenericComponentType()); } if (type instanceof ParameterizedType) { for (Type t : ((ParameterizedType) type).getActualTypeArguments()) { if (!isResolved(t)) { return false; } } return true; } return type instanceof Class; } }
public class class_name { public static boolean isResolved(Type type) { if (type instanceof GenericArrayType) { return isResolved(((GenericArrayType) type).getGenericComponentType()); // depends on control dependency: [if], data = [none] } if (type instanceof ParameterizedType) { for (Type t : ((ParameterizedType) type).getActualTypeArguments()) { if (!isResolved(t)) { return false; // depends on control dependency: [if], data = [none] } } return true; // depends on control dependency: [if], data = [none] } return type instanceof Class; } }
public class class_name { public UniqueKeyGenerator getUniqueKeyGenerator(String name, int range) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "getUniqueKeyGenerator", new Object[]{"Name="+name, "Range="+range}); UniqueKeyGenerator retval = null; try { retval = _uniqueKeyManager.createUniqueKeyGenerator(name, range); } catch (PersistenceException pe) { com.ibm.ws.ffdc.FFDCFilter.processException(pe, "com.ibm.ws.sib.msgstore.persistence.objectManager.PersistableMessageStoreImpl.getUniqueKeyGenerator", "1:2089:1.81.1.6", this); if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(this, tc, "Exception caught creating new unique key generator!", pe); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "getUniqueKeyGenerator", "return="+retval); return retval; } }
public class class_name { public UniqueKeyGenerator getUniqueKeyGenerator(String name, int range) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "getUniqueKeyGenerator", new Object[]{"Name="+name, "Range="+range}); UniqueKeyGenerator retval = null; try { retval = _uniqueKeyManager.createUniqueKeyGenerator(name, range); // depends on control dependency: [try], data = [none] } catch (PersistenceException pe) { com.ibm.ws.ffdc.FFDCFilter.processException(pe, "com.ibm.ws.sib.msgstore.persistence.objectManager.PersistableMessageStoreImpl.getUniqueKeyGenerator", "1:2089:1.81.1.6", this); if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) SibTr.event(this, tc, "Exception caught creating new unique key generator!", pe); } // depends on control dependency: [catch], data = [none] if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "getUniqueKeyGenerator", "return="+retval); return retval; } }
public class class_name { public static boolean parseWithKeyword(final char[] query, int offset) { if (query.length < (offset + 4)) { return false; } return (query[offset] | 32) == 'w' && (query[offset + 1] | 32) == 'i' && (query[offset + 2] | 32) == 't' && (query[offset + 3] | 32) == 'h'; } }
public class class_name { public static boolean parseWithKeyword(final char[] query, int offset) { if (query.length < (offset + 4)) { return false; // depends on control dependency: [if], data = [none] } return (query[offset] | 32) == 'w' && (query[offset + 1] | 32) == 'i' && (query[offset + 2] | 32) == 't' && (query[offset + 3] | 32) == 'h'; } }
public class class_name { public synchronized TaskMetricStore getTaskMetricStore(String jobID, String taskID) { JobMetricStore job = jobID == null ? null : jobs.get(jobID); if (job == null || taskID == null) { return null; } return TaskMetricStore.unmodifiable(job.getTaskMetricStore(taskID)); } }
public class class_name { public synchronized TaskMetricStore getTaskMetricStore(String jobID, String taskID) { JobMetricStore job = jobID == null ? null : jobs.get(jobID); if (job == null || taskID == null) { return null; // depends on control dependency: [if], data = [none] } return TaskMetricStore.unmodifiable(job.getTaskMetricStore(taskID)); } }
public class class_name { @Override public void shutdown() { ArrayList mbeanSvrs = MBeanServerFactory.findMBeanServer(null); if (mbeanSvrs != null && mbeanSvrs.size() > 0 && _statsModuleObjectName != null) { MBeanServer svr = (MBeanServer) mbeanSvrs.get(0); try { svr.unregisterMBean(_statsModuleObjectName); } catch (InstanceNotFoundException e) { com.ibm.ws.ffdc.FFDCFilter.processException(e, "com.ibm.ws.session.SessionManager.shutdown", "263", this); LoggingUtil.SESSION_LOGGER_CORE.logp(Level.SEVERE, methodClassName, methodNames[SHUTDOWN], "CommonMessage.exception", e); } catch (MBeanRegistrationException e) { com.ibm.ws.ffdc.FFDCFilter.processException(e, "com.ibm.ws.session.SessionManager.shutdown", "265", this); LoggingUtil.SESSION_LOGGER_CORE.logp(Level.SEVERE, methodClassName, methodNames[SHUTDOWN], "CommonMessage.exception", e); } } } }
public class class_name { @Override public void shutdown() { ArrayList mbeanSvrs = MBeanServerFactory.findMBeanServer(null); if (mbeanSvrs != null && mbeanSvrs.size() > 0 && _statsModuleObjectName != null) { MBeanServer svr = (MBeanServer) mbeanSvrs.get(0); try { svr.unregisterMBean(_statsModuleObjectName); // depends on control dependency: [try], data = [none] } catch (InstanceNotFoundException e) { com.ibm.ws.ffdc.FFDCFilter.processException(e, "com.ibm.ws.session.SessionManager.shutdown", "263", this); LoggingUtil.SESSION_LOGGER_CORE.logp(Level.SEVERE, methodClassName, methodNames[SHUTDOWN], "CommonMessage.exception", e); } catch (MBeanRegistrationException e) { // depends on control dependency: [catch], data = [none] com.ibm.ws.ffdc.FFDCFilter.processException(e, "com.ibm.ws.session.SessionManager.shutdown", "265", this); LoggingUtil.SESSION_LOGGER_CORE.logp(Level.SEVERE, methodClassName, methodNames[SHUTDOWN], "CommonMessage.exception", e); } // depends on control dependency: [catch], data = [none] } } }
public class class_name { public void marshall(ListRemoteAccessSessionsRequest listRemoteAccessSessionsRequest, ProtocolMarshaller protocolMarshaller) { if (listRemoteAccessSessionsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(listRemoteAccessSessionsRequest.getArn(), ARN_BINDING); protocolMarshaller.marshall(listRemoteAccessSessionsRequest.getNextToken(), NEXTTOKEN_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(ListRemoteAccessSessionsRequest listRemoteAccessSessionsRequest, ProtocolMarshaller protocolMarshaller) { if (listRemoteAccessSessionsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(listRemoteAccessSessionsRequest.getArn(), ARN_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(listRemoteAccessSessionsRequest.getNextToken(), NEXTTOKEN_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 TableMetadata insertMetadata(String tableName, String version){ TableMetadata result = new TableMetadata(this); result.setId(new Long(tableName.hashCode())); result.setName(tableName); result.setVersion(version); try{ insertStatement.setLong(1, result.getId()); insertStatement.setString(2, result.getName()); insertStatement.setString(3, result.getVersion()); insertStatement.executeUpdate(); }catch(SQLException e){ throw new BackendException("Could not insert new metadata-entry: " + result, e); } return result; } }
public class class_name { public TableMetadata insertMetadata(String tableName, String version){ TableMetadata result = new TableMetadata(this); result.setId(new Long(tableName.hashCode())); result.setName(tableName); result.setVersion(version); try{ insertStatement.setLong(1, result.getId()); // depends on control dependency: [try], data = [none] insertStatement.setString(2, result.getName()); // depends on control dependency: [try], data = [none] insertStatement.setString(3, result.getVersion()); // depends on control dependency: [try], data = [none] insertStatement.executeUpdate(); // depends on control dependency: [try], data = [none] }catch(SQLException e){ throw new BackendException("Could not insert new metadata-entry: " + result, e); } // depends on control dependency: [catch], data = [none] return result; } }
public class class_name { public static void float2rgbe(byte[] rgbe, float red, float green, float blue) { float v; int e; v = red; if (green > v) { v = green; } if (blue > v) { v = blue; } if (v < 1e-32f) { rgbe[0] = rgbe[1] = rgbe[2] = rgbe[3] = 0; } else { FracExp fe = frexp(v); v = (float) (fe.getFraction() * 256.0 / v); rgbe[0] = (byte) (red * v); rgbe[1] = (byte) (green * v); rgbe[2] = (byte) (blue * v); rgbe[3] = (byte) (fe.getExponent() + 128); } } }
public class class_name { public static void float2rgbe(byte[] rgbe, float red, float green, float blue) { float v; int e; v = red; if (green > v) { v = green; // depends on control dependency: [if], data = [none] } if (blue > v) { v = blue; // depends on control dependency: [if], data = [none] } if (v < 1e-32f) { rgbe[0] = rgbe[1] = rgbe[2] = rgbe[3] = 0; // depends on control dependency: [if], data = [none] } else { FracExp fe = frexp(v); v = (float) (fe.getFraction() * 256.0 / v); // depends on control dependency: [if], data = [none] rgbe[0] = (byte) (red * v); // depends on control dependency: [if], data = [none] rgbe[1] = (byte) (green * v); // depends on control dependency: [if], data = [none] rgbe[2] = (byte) (blue * v); // depends on control dependency: [if], data = [none] rgbe[3] = (byte) (fe.getExponent() + 128); // depends on control dependency: [if], data = [none] } } }
public class class_name { private void decodeChunk(InetSocketAddress address, final ByteBuf chunk) { responseContent.writeBytes(chunk); String currentChunk = responseContent.toString(CharsetUtil.UTF_8); int separatorIndex = currentChunk.indexOf("\n\n\n\n"); if (separatorIndex > 0) { String rawConfig = currentChunk .substring(0, separatorIndex) .trim() .replace("$HOST", address.getAddress().getHostAddress()); NetworkAddress origin = NetworkAddress.create(address.getAddress().getHostAddress()); CouchbaseBucketConfig config = (CouchbaseBucketConfig) BucketConfigParser.parse(rawConfig, environment, origin); synchronized (currentBucketConfigRev) { if (config.rev() > currentBucketConfigRev.get()) { LOGGER.trace("Publishing bucket config: {}", RedactableArgument.system(rawConfig)); currentBucketConfigRev.set(config.rev()); configStream.onNext(config); } else { LOGGER.trace("Ignoring config, since rev has not changed."); } } responseContent.clear(); responseContent.writeBytes(currentChunk.substring(separatorIndex + 4).getBytes(CharsetUtil.UTF_8)); } } }
public class class_name { private void decodeChunk(InetSocketAddress address, final ByteBuf chunk) { responseContent.writeBytes(chunk); String currentChunk = responseContent.toString(CharsetUtil.UTF_8); int separatorIndex = currentChunk.indexOf("\n\n\n\n"); if (separatorIndex > 0) { String rawConfig = currentChunk .substring(0, separatorIndex) .trim() .replace("$HOST", address.getAddress().getHostAddress()); NetworkAddress origin = NetworkAddress.create(address.getAddress().getHostAddress()); CouchbaseBucketConfig config = (CouchbaseBucketConfig) BucketConfigParser.parse(rawConfig, environment, origin); synchronized (currentBucketConfigRev) { // depends on control dependency: [if], data = [none] if (config.rev() > currentBucketConfigRev.get()) { LOGGER.trace("Publishing bucket config: {}", RedactableArgument.system(rawConfig)); // depends on control dependency: [if], data = [none] currentBucketConfigRev.set(config.rev()); // depends on control dependency: [if], data = [(config.rev()] configStream.onNext(config); // depends on control dependency: [if], data = [none] } else { LOGGER.trace("Ignoring config, since rev has not changed."); // depends on control dependency: [if], data = [none] } } responseContent.clear(); // depends on control dependency: [if], data = [none] responseContent.writeBytes(currentChunk.substring(separatorIndex + 4).getBytes(CharsetUtil.UTF_8)); // depends on control dependency: [if], data = [(separatorIndex] } } }
public class class_name { public TypedLinkSpecifier withIdentityAttributeValues(AttributeNameAndValue... identityAttributeValues) { if (this.identityAttributeValues == null) { setIdentityAttributeValues(new java.util.ArrayList<AttributeNameAndValue>(identityAttributeValues.length)); } for (AttributeNameAndValue ele : identityAttributeValues) { this.identityAttributeValues.add(ele); } return this; } }
public class class_name { public TypedLinkSpecifier withIdentityAttributeValues(AttributeNameAndValue... identityAttributeValues) { if (this.identityAttributeValues == null) { setIdentityAttributeValues(new java.util.ArrayList<AttributeNameAndValue>(identityAttributeValues.length)); // depends on control dependency: [if], data = [none] } for (AttributeNameAndValue ele : identityAttributeValues) { this.identityAttributeValues.add(ele); // depends on control dependency: [for], data = [ele] } return this; } }
public class class_name { private static long getUUIDTime() { if (_currentMillis != System.currentTimeMillis()) { _currentMillis = System.currentTimeMillis(); _counter = 0; // reset counter } // check to see if we have created too many uuid's for this timestamp if (_counter + 1 >= MILLI_MULT) { // Original algorithm threw exception. Seemed like overkill. // Let's just increment the timestamp instead and start over... _currentMillis++; _counter = 0; } // calculate time as current millis plus offset times 100 ns ticks long currentTime = (_currentMillis + GREG_OFFSET) * MILLI_MULT; // return the uuid time plus the artificial tick counter incremented return currentTime + _counter++; } }
public class class_name { private static long getUUIDTime() { if (_currentMillis != System.currentTimeMillis()) { _currentMillis = System.currentTimeMillis(); // depends on control dependency: [if], data = [none] _counter = 0; // reset counter // depends on control dependency: [if], data = [none] } // check to see if we have created too many uuid's for this timestamp if (_counter + 1 >= MILLI_MULT) { // Original algorithm threw exception. Seemed like overkill. // Let's just increment the timestamp instead and start over... _currentMillis++; // depends on control dependency: [if], data = [none] _counter = 0; // depends on control dependency: [if], data = [none] } // calculate time as current millis plus offset times 100 ns ticks long currentTime = (_currentMillis + GREG_OFFSET) * MILLI_MULT; // return the uuid time plus the artificial tick counter incremented return currentTime + _counter++; } }
public class class_name { protected List<Element> filterChildren(Element parent, String tagName) { List<Element> result = new ArrayList<Element>(); Node current = parent.getFirstChild(); while (current != null) { if (current.getNodeName().equals(tagName)) { result.add((Element) current); } current = current.getNextSibling(); } return result; } }
public class class_name { protected List<Element> filterChildren(Element parent, String tagName) { List<Element> result = new ArrayList<Element>(); Node current = parent.getFirstChild(); while (current != null) { if (current.getNodeName().equals(tagName)) { result.add((Element) current); // depends on control dependency: [if], data = [none] } current = current.getNextSibling(); // depends on control dependency: [while], data = [none] } return result; } }
public class class_name { private void updateDecoration() { if (lastResult != null) { if (lastResult) { setIcon(validIcon); setToolTipText(validText); } else { setIcon(invalidIcon); setToolTipText(invalidText); } } } }
public class class_name { private void updateDecoration() { if (lastResult != null) { if (lastResult) { setIcon(validIcon); // depends on control dependency: [if], data = [none] setToolTipText(validText); // depends on control dependency: [if], data = [none] } else { setIcon(invalidIcon); // depends on control dependency: [if], data = [none] setToolTipText(invalidText); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public static boolean isNearMultipleBorders(@Nonnull final Point point, @Nonnull final Territory territory) { checkDefined("point", point); if (territory != Territory.AAA) { final int territoryNumber = territory.getNumber(); if (territory.getParentTerritory() != null) { // There is a parent! check its borders as well... if (isNearMultipleBorders(point, territory.getParentTerritory())) { return true; } } int nrFound = 0; final int fromTerritoryRecord = DATA_MODEL.getDataFirstRecord(territoryNumber); final int uptoTerritoryRecord = DATA_MODEL.getDataLastRecord(territoryNumber); for (int territoryRecord = uptoTerritoryRecord; territoryRecord >= fromTerritoryRecord; territoryRecord--) { if (!Data.isRestricted(territoryRecord)) { final Boundary boundary = Boundary.createBoundaryForTerritoryRecord(territoryRecord); final int xdiv8 = Common.xDivider(boundary.getLatMicroDegMin(), boundary.getLatMicroDegMax()) / 4; if (boundary.extendBoundary(60, xdiv8).containsPoint(point)) { if (!boundary.extendBoundary(-60, -xdiv8).containsPoint(point)) { nrFound++; if (nrFound > 1) { return true; } } } } } } return false; } }
public class class_name { public static boolean isNearMultipleBorders(@Nonnull final Point point, @Nonnull final Territory territory) { checkDefined("point", point); if (territory != Territory.AAA) { final int territoryNumber = territory.getNumber(); if (territory.getParentTerritory() != null) { // There is a parent! check its borders as well... if (isNearMultipleBorders(point, territory.getParentTerritory())) { return true; // depends on control dependency: [if], data = [none] } } int nrFound = 0; final int fromTerritoryRecord = DATA_MODEL.getDataFirstRecord(territoryNumber); final int uptoTerritoryRecord = DATA_MODEL.getDataLastRecord(territoryNumber); for (int territoryRecord = uptoTerritoryRecord; territoryRecord >= fromTerritoryRecord; territoryRecord--) { if (!Data.isRestricted(territoryRecord)) { final Boundary boundary = Boundary.createBoundaryForTerritoryRecord(territoryRecord); final int xdiv8 = Common.xDivider(boundary.getLatMicroDegMin(), boundary.getLatMicroDegMax()) / 4; if (boundary.extendBoundary(60, xdiv8).containsPoint(point)) { if (!boundary.extendBoundary(-60, -xdiv8).containsPoint(point)) { nrFound++; // depends on control dependency: [if], data = [none] if (nrFound > 1) { return true; // depends on control dependency: [if], data = [none] } } } } } } return false; } }
public class class_name { @SuppressWarnings("unchecked") @Override protected Val<Expression> arg(String field, String op, Val<Expression> arg, int index, int count, QueryExprMeta parent) { Iterable<ExprArgTransformer> transformers = getTransformer(ExprArgTransformer.class); for (ExprArgTransformer transformer : transformers) { Transformed<Val<Expression>> transformed = transformer.transform( field, op, arg, index, count, this, parent ); if (transformed.success()) { return transformed.result(); } } throw new QuerySyntaxException(Messages.get("dsl.transform.err", field, op, String.valueOf(arg))); } }
public class class_name { @SuppressWarnings("unchecked") @Override protected Val<Expression> arg(String field, String op, Val<Expression> arg, int index, int count, QueryExprMeta parent) { Iterable<ExprArgTransformer> transformers = getTransformer(ExprArgTransformer.class); for (ExprArgTransformer transformer : transformers) { Transformed<Val<Expression>> transformed = transformer.transform( field, op, arg, index, count, this, parent ); if (transformed.success()) { return transformed.result(); // depends on control dependency: [if], data = [none] } } throw new QuerySyntaxException(Messages.get("dsl.transform.err", field, op, String.valueOf(arg))); } }
public class class_name { public void marshall(ListQueryExecutionsRequest listQueryExecutionsRequest, ProtocolMarshaller protocolMarshaller) { if (listQueryExecutionsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(listQueryExecutionsRequest.getNextToken(), NEXTTOKEN_BINDING); protocolMarshaller.marshall(listQueryExecutionsRequest.getMaxResults(), MAXRESULTS_BINDING); protocolMarshaller.marshall(listQueryExecutionsRequest.getWorkGroup(), WORKGROUP_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(ListQueryExecutionsRequest listQueryExecutionsRequest, ProtocolMarshaller protocolMarshaller) { if (listQueryExecutionsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(listQueryExecutionsRequest.getNextToken(), NEXTTOKEN_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(listQueryExecutionsRequest.getMaxResults(), MAXRESULTS_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(listQueryExecutionsRequest.getWorkGroup(), WORKGROUP_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { protected void registerMBeans(WebModuleMetaDataImpl webModule, com.ibm.wsspi.adaptable.module.Container container) { String methodName = "registerMBeans"; String appName = webModule.getApplicationMetaData().getName(); String webAppName = webModule.getName(); String debugName; if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { debugName = appName + " " + webAppName; } else { debugName = null; } WebMBeanRuntime mBeanRuntime = webMBeanRuntimeServiceRef.getService(); if (mBeanRuntime == null) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, methodName, "Web Module [ " + debugName + " ]: No MBean Runtime"); } return; } else { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, methodName, "Web Module [ " + debugName + " ]: MBean Runtime"); } } String ddPath = com.ibm.ws.javaee.dd.web.WebApp.DD_NAME; // This should be obtained by an adapt call. Iterator<IServletConfig> servletConfigs = webModule.getConfiguration().getServletInfos(); webModule.mBeanServiceReg = mBeanRuntime.registerModuleMBean(appName, webAppName, container, ddPath, servletConfigs); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, methodName, "Web Module [ " + debugName + " ]: Registration [ " + webModule.mBeanServiceReg + " ]"); } servletConfigs = webModule.getConfiguration().getServletInfos(); while (servletConfigs.hasNext()) { IServletConfig servletConfig = servletConfigs.next(); String servletName = servletConfig.getServletName(); WebComponentMetaDataImpl wcmdi = (WebComponentMetaDataImpl) servletConfig.getMetaData(); wcmdi.mBeanServiceReg = mBeanRuntime.registerServletMBean(appName, webAppName, servletName); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, methodName, "Web Module [ " + debugName + " ] Servlet [ " + servletName + " ]: Registration [ " + wcmdi.mBeanServiceReg + " ]"); } } if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, methodName, "Web Module [ " + debugName + " ]: Completed registrations"); } } }
public class class_name { protected void registerMBeans(WebModuleMetaDataImpl webModule, com.ibm.wsspi.adaptable.module.Container container) { String methodName = "registerMBeans"; String appName = webModule.getApplicationMetaData().getName(); String webAppName = webModule.getName(); String debugName; if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { debugName = appName + " " + webAppName; // depends on control dependency: [if], data = [none] } else { debugName = null; // depends on control dependency: [if], data = [none] } WebMBeanRuntime mBeanRuntime = webMBeanRuntimeServiceRef.getService(); if (mBeanRuntime == null) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, methodName, "Web Module [ " + debugName + " ]: No MBean Runtime"); // depends on control dependency: [if], data = [none] } return; // depends on control dependency: [if], data = [none] } else { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, methodName, "Web Module [ " + debugName + " ]: MBean Runtime"); // depends on control dependency: [if], data = [none] } } String ddPath = com.ibm.ws.javaee.dd.web.WebApp.DD_NAME; // This should be obtained by an adapt call. Iterator<IServletConfig> servletConfigs = webModule.getConfiguration().getServletInfos(); webModule.mBeanServiceReg = mBeanRuntime.registerModuleMBean(appName, webAppName, container, ddPath, servletConfigs); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, methodName, "Web Module [ " + debugName + " ]: Registration [ " + webModule.mBeanServiceReg + " ]"); // depends on control dependency: [if], data = [none] } servletConfigs = webModule.getConfiguration().getServletInfos(); while (servletConfigs.hasNext()) { IServletConfig servletConfig = servletConfigs.next(); String servletName = servletConfig.getServletName(); WebComponentMetaDataImpl wcmdi = (WebComponentMetaDataImpl) servletConfig.getMetaData(); wcmdi.mBeanServiceReg = mBeanRuntime.registerServletMBean(appName, webAppName, servletName); // depends on control dependency: [while], data = [none] if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, methodName, "Web Module [ " + debugName + " ] Servlet [ " + servletName + " ]: Registration [ " + wcmdi.mBeanServiceReg + " ]"); // depends on control dependency: [if], data = [none] } } if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, methodName, "Web Module [ " + debugName + " ]: Completed registrations"); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void marshall(ListEntityRecognizersRequest listEntityRecognizersRequest, ProtocolMarshaller protocolMarshaller) { if (listEntityRecognizersRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(listEntityRecognizersRequest.getFilter(), FILTER_BINDING); protocolMarshaller.marshall(listEntityRecognizersRequest.getNextToken(), NEXTTOKEN_BINDING); protocolMarshaller.marshall(listEntityRecognizersRequest.getMaxResults(), MAXRESULTS_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(ListEntityRecognizersRequest listEntityRecognizersRequest, ProtocolMarshaller protocolMarshaller) { if (listEntityRecognizersRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(listEntityRecognizersRequest.getFilter(), FILTER_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(listEntityRecognizersRequest.getNextToken(), NEXTTOKEN_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(listEntityRecognizersRequest.getMaxResults(), MAXRESULTS_BINDING); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public void buildEnumSummary(XMLNode node, Content packageSummaryContentTree) { String enumTableSummary = configuration.getText("doclet.Member_Table_Summary", configuration.getText("doclet.Enum_Summary"), configuration.getText("doclet.enums")); String[] enumTableHeader = new String[] { configuration.getText("doclet.Enum"), configuration.getText("doclet.Description") }; ClassDoc[] enums = pkg.enums(); if (enums.length > 0) { profileWriter.addClassesSummary( enums, configuration.getText("doclet.Enum_Summary"), enumTableSummary, enumTableHeader, packageSummaryContentTree); } } }
public class class_name { public void buildEnumSummary(XMLNode node, Content packageSummaryContentTree) { String enumTableSummary = configuration.getText("doclet.Member_Table_Summary", configuration.getText("doclet.Enum_Summary"), configuration.getText("doclet.enums")); String[] enumTableHeader = new String[] { configuration.getText("doclet.Enum"), configuration.getText("doclet.Description") }; ClassDoc[] enums = pkg.enums(); if (enums.length > 0) { profileWriter.addClassesSummary( enums, configuration.getText("doclet.Enum_Summary"), enumTableSummary, enumTableHeader, packageSummaryContentTree); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static String extractText(Article article) { StringBuilder sb = new StringBuilder(); // extract abstract List<Abstract> abstracts = article.getFront().getArticleMeta() .getAbstract(); for (Abstract abstrct : abstracts) { for (Sec sec : abstrct.getSec()) { processTextContent(sec.getAddressOrAlternativesOrArray(), sb, true); } } sb.append('\n'); // extract text Body body = article.getBody(); if (body != null) { for (Sec sec : body.getSec()) { Title title = sec.getTitle(); if (title != null && title.getContent() != null) { processTextContent(title.getContent(), sb, true); sb.append('\n'); } processTextContent(sec.getAddressOrAlternativesOrArray(), sb, false); } } return removeNoise(sb.toString()); } }
public class class_name { public static String extractText(Article article) { StringBuilder sb = new StringBuilder(); // extract abstract List<Abstract> abstracts = article.getFront().getArticleMeta() .getAbstract(); for (Abstract abstrct : abstracts) { for (Sec sec : abstrct.getSec()) { processTextContent(sec.getAddressOrAlternativesOrArray(), sb, true); // depends on control dependency: [for], data = [none] } } sb.append('\n'); // extract text Body body = article.getBody(); if (body != null) { for (Sec sec : body.getSec()) { Title title = sec.getTitle(); if (title != null && title.getContent() != null) { processTextContent(title.getContent(), sb, true); // depends on control dependency: [if], data = [(title] sb.append('\n'); // depends on control dependency: [if], data = [none] } processTextContent(sec.getAddressOrAlternativesOrArray(), sb, false); // depends on control dependency: [for], data = [none] } } return removeNoise(sb.toString()); } }
public class class_name { @Override public void setProviderUrl(String providerUrl) { Provider prov = _asset.getProvider(); if (prov == null) { prov = new Provider(); _asset.setProvider(prov); } prov.setUrl(providerUrl); } }
public class class_name { @Override public void setProviderUrl(String providerUrl) { Provider prov = _asset.getProvider(); if (prov == null) { prov = new Provider(); // depends on control dependency: [if], data = [none] _asset.setProvider(prov); // depends on control dependency: [if], data = [(prov] } prov.setUrl(providerUrl); } }
public class class_name { @Override public void stop(){ if (isStarted.compareAndSet(true,false)) { // if you shutdown it, it can not be use anymore super.stop(); ScheduledExecutorService service = this.syncService.getAndSet(newSyncService()); service.shutdown(); LOGGER.info("Cache sync Service is shutdown"); for (Entry<String,ModelServiceClientCache> entry : cache.entrySet()){ removeInstanceChangeListener(entry.getKey(),entry.getValue()); } getCache().clear(); } } }
public class class_name { @Override public void stop(){ if (isStarted.compareAndSet(true,false)) { // if you shutdown it, it can not be use anymore super.stop(); // depends on control dependency: [if], data = [none] ScheduledExecutorService service = this.syncService.getAndSet(newSyncService()); service.shutdown(); // depends on control dependency: [if], data = [none] LOGGER.info("Cache sync Service is shutdown"); // depends on control dependency: [if], data = [none] for (Entry<String,ModelServiceClientCache> entry : cache.entrySet()){ removeInstanceChangeListener(entry.getKey(),entry.getValue()); // depends on control dependency: [for], data = [entry] } getCache().clear(); // depends on control dependency: [if], data = [none] } } }
public class class_name { @Override public final AbstractGauge init(final int WIDTH, final int HEIGHT) { if (WIDTH <= 1 || HEIGHT <= 1) { return this; } int offset = 0; if (isFrameVisible()) { offset = 18; } if (isDigitalFont()) { setLcdValueFont(LCD_DIGITAL_FONT.deriveFont(0.7f * (getHeight() - (2 * offset)))); } else { setLcdValueFont(LCD_STANDARD_FONT.deriveFont(0.625f * (getHeight() - (2 * offset)))); } if (isCustomLcdUnitFontEnabled()) { setLcdUnitFont(getCustomLcdUnitFont().deriveFont(0.25f * (getHeight() - (2 * offset)))); } else { setLcdUnitFont(LCD_STANDARD_FONT.deriveFont(0.25f * (getHeight() - (2 * offset)))); } if (frameImage != null) { frameImage.flush(); } frameImage = create_FRAME_Image(WIDTH, HEIGHT); if (backgroundImage != null) { backgroundImage.flush(); } backgroundImage = create_BACKGROUND_Image(WIDTH, HEIGHT); if (lcdImage != null) { lcdImage.flush(); } if (isFrameVisible()) { lcdImage = create_LCD_Image(WIDTH - (2 * offset), HEIGHT - (2 * offset), getLcdColor(), getCustomLcdBackground()); } else { lcdImage = create_LCD_Image(getWidth(), getHeight(), getLcdColor(), getCustomLcdBackground()); } if (foregroundImage != null) { foregroundImage.flush(); } foregroundImage = create_FOREGROUND_Image(WIDTH, HEIGHT); if (disabledImage != null) { disabledImage.flush(); } disabledImage = create_DISABLED_Image(getWidth(), getHeight()); if (backgroundImage != null) { backgroundImage.flush(); } backgroundImage = create_BACKGROUND_Image(WIDTH, HEIGHT); if (foregroundImage != null) { foregroundImage.flush(); } foregroundImage = create_FOREGROUND_Image(WIDTH, HEIGHT); if (disabledImage != null) { disabledImage.flush(); } disabledImage = create_DISABLED_Image(WIDTH, HEIGHT); return this; } }
public class class_name { @Override public final AbstractGauge init(final int WIDTH, final int HEIGHT) { if (WIDTH <= 1 || HEIGHT <= 1) { return this; // depends on control dependency: [if], data = [none] } int offset = 0; if (isFrameVisible()) { offset = 18; // depends on control dependency: [if], data = [none] } if (isDigitalFont()) { setLcdValueFont(LCD_DIGITAL_FONT.deriveFont(0.7f * (getHeight() - (2 * offset)))); // depends on control dependency: [if], data = [none] } else { setLcdValueFont(LCD_STANDARD_FONT.deriveFont(0.625f * (getHeight() - (2 * offset)))); // depends on control dependency: [if], data = [none] } if (isCustomLcdUnitFontEnabled()) { setLcdUnitFont(getCustomLcdUnitFont().deriveFont(0.25f * (getHeight() - (2 * offset)))); // depends on control dependency: [if], data = [none] } else { setLcdUnitFont(LCD_STANDARD_FONT.deriveFont(0.25f * (getHeight() - (2 * offset)))); // depends on control dependency: [if], data = [none] } if (frameImage != null) { frameImage.flush(); // depends on control dependency: [if], data = [none] } frameImage = create_FRAME_Image(WIDTH, HEIGHT); if (backgroundImage != null) { backgroundImage.flush(); // depends on control dependency: [if], data = [none] } backgroundImage = create_BACKGROUND_Image(WIDTH, HEIGHT); if (lcdImage != null) { lcdImage.flush(); // depends on control dependency: [if], data = [none] } if (isFrameVisible()) { lcdImage = create_LCD_Image(WIDTH - (2 * offset), HEIGHT - (2 * offset), getLcdColor(), getCustomLcdBackground()); // depends on control dependency: [if], data = [none] } else { lcdImage = create_LCD_Image(getWidth(), getHeight(), getLcdColor(), getCustomLcdBackground()); // depends on control dependency: [if], data = [none] } if (foregroundImage != null) { foregroundImage.flush(); // depends on control dependency: [if], data = [none] } foregroundImage = create_FOREGROUND_Image(WIDTH, HEIGHT); if (disabledImage != null) { disabledImage.flush(); // depends on control dependency: [if], data = [none] } disabledImage = create_DISABLED_Image(getWidth(), getHeight()); if (backgroundImage != null) { backgroundImage.flush(); // depends on control dependency: [if], data = [none] } backgroundImage = create_BACKGROUND_Image(WIDTH, HEIGHT); if (foregroundImage != null) { foregroundImage.flush(); // depends on control dependency: [if], data = [none] } foregroundImage = create_FOREGROUND_Image(WIDTH, HEIGHT); if (disabledImage != null) { disabledImage.flush(); // depends on control dependency: [if], data = [none] } disabledImage = create_DISABLED_Image(WIDTH, HEIGHT); return this; } }
public class class_name { public static boolean isSameYearMonth(YearMonth first, YearMonth second) { // If both values are null, return true. if (first == null && second == null) { return true; } // At least one value contains a YearMonth. If the other value is null, then return false. if (first == null || second == null) { return false; } // Both values contain a YearMonth. // Return true if the YearMonth are equal, otherwise return false. return first.equals(second); } }
public class class_name { public static boolean isSameYearMonth(YearMonth first, YearMonth second) { // If both values are null, return true. if (first == null && second == null) { return true; // depends on control dependency: [if], data = [none] } // At least one value contains a YearMonth. If the other value is null, then return false. if (first == null || second == null) { return false; // depends on control dependency: [if], data = [none] } // Both values contain a YearMonth. // Return true if the YearMonth are equal, otherwise return false. return first.equals(second); } }
public class class_name { public String generateEmailConfirmationToken() { if (StringUtils.isBlank(identifier)) { return ""; } Sysprop s = CoreUtils.getInstance().getDao().read(getAppid(), identifier); if (s != null) { String token = Utils.base64encURL(Utils.generateSecurityToken().getBytes()); s.addProperty(Config._EMAIL_TOKEN, token); CoreUtils.getInstance().getDao().update(getAppid(), s); return token; } return ""; } }
public class class_name { public String generateEmailConfirmationToken() { if (StringUtils.isBlank(identifier)) { return ""; // depends on control dependency: [if], data = [none] } Sysprop s = CoreUtils.getInstance().getDao().read(getAppid(), identifier); if (s != null) { String token = Utils.base64encURL(Utils.generateSecurityToken().getBytes()); s.addProperty(Config._EMAIL_TOKEN, token); // depends on control dependency: [if], data = [none] CoreUtils.getInstance().getDao().update(getAppid(), s); // depends on control dependency: [if], data = [none] return token; // depends on control dependency: [if], data = [none] } return ""; } }
public class class_name { public static TreeElement getRoot(TreeElement node) { TreeElement parentNode = node.getParent(); while (parentNode != null) { node = parentNode; parentNode = node.getParent(); } return node; } }
public class class_name { public static TreeElement getRoot(TreeElement node) { TreeElement parentNode = node.getParent(); while (parentNode != null) { node = parentNode; // depends on control dependency: [while], data = [none] parentNode = node.getParent(); // depends on control dependency: [while], data = [none] } return node; } }
public class class_name { public static <T extends Throwable> void printHistoryAndExit(final String message, final T th, final PrintStream stream) { printHistory(new CouldNotPerformException(message, th), new SystemPrinter(stream)); if (JPService.testMode()) { assert false; return; } exit(255); } }
public class class_name { public static <T extends Throwable> void printHistoryAndExit(final String message, final T th, final PrintStream stream) { printHistory(new CouldNotPerformException(message, th), new SystemPrinter(stream)); if (JPService.testMode()) { assert false; return; // depends on control dependency: [if], data = [none] } exit(255); } }
public class class_name { public void onLayoutApplied(final WidgetContainer container, final Vector3Axis viewPortSize) { mContainer = container; mViewPort.setSize(viewPortSize); if (mContainer != null) { mContainer.onLayoutChanged(this); } } }
public class class_name { public void onLayoutApplied(final WidgetContainer container, final Vector3Axis viewPortSize) { mContainer = container; mViewPort.setSize(viewPortSize); if (mContainer != null) { mContainer.onLayoutChanged(this); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static String getResult(Process process, Charset charset) { InputStream in = null; try { in = process.getInputStream(); return IoUtil.read(in, charset); } finally { IoUtil.close(in); destroy(process); } } }
public class class_name { public static String getResult(Process process, Charset charset) { InputStream in = null; try { in = process.getInputStream(); // depends on control dependency: [try], data = [none] return IoUtil.read(in, charset); // depends on control dependency: [try], data = [none] } finally { IoUtil.close(in); destroy(process); } } }
public class class_name { public Observable<List<Attachment>> uploadAttachments(@NonNull List<Attachment> data, @NonNull RxComapiClient c) { if (!data.isEmpty()) { return Observable.concatDelayError(upload(c, data)).toList(); } else { return Observable.fromCallable(() -> null); } } }
public class class_name { public Observable<List<Attachment>> uploadAttachments(@NonNull List<Attachment> data, @NonNull RxComapiClient c) { if (!data.isEmpty()) { return Observable.concatDelayError(upload(c, data)).toList(); // depends on control dependency: [if], data = [none] } else { return Observable.fromCallable(() -> null); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static String normalize(String value) { if (value == null) return value; value = value.trim(); if (value.indexOf(" ") == -1) return value; boolean space = false; int len = value.length(); StringBuffer b = new StringBuffer(len); for (int i = 0; i < len; i++) { char v = value.charAt(i); if (v == ' ') { if (!space) b.append(v); space = true; } else { b.append(v); space = false; } } return b.toString(); } }
public class class_name { public static String normalize(String value) { if (value == null) return value; value = value.trim(); if (value.indexOf(" ") == -1) return value; boolean space = false; int len = value.length(); StringBuffer b = new StringBuffer(len); for (int i = 0; i < len; i++) { char v = value.charAt(i); if (v == ' ') { if (!space) b.append(v); space = true; // depends on control dependency: [if], data = [none] } else { b.append(v); // depends on control dependency: [if], data = [(v] space = false; // depends on control dependency: [if], data = [none] } } return b.toString(); } }
public class class_name { @FFDCIgnore(IOException.class) public static String fixPathString(File absPath) { //on windows.. the path from config can have a different case to the actual filesystem path //and when notifications come back, they'll come back with the actual filsystem casing. //so, so ensure we all agree on what that should be, for windows, we use canonical path. // //getCanonicalPath however, sees 'through' symlinks, which means if we use it on paths //that are symlinked into the app, we'll see the actual paths instead of the symlinked ones. // //getCanonicalPath on windows however just happens not to be able to see through windows //symlinks (which are infrequently used anyways), so we're still safe to use it there, and //non-windows platforms are just fine sticking with the casing of the path supplied via //config. // //A future alternative will be to use File.toPath().getRealPath(LinkOptions.NOFOLLOW_LINKS); //when Liberty is java7 only.. if (isWindows) { try { return absPath.getCanonicalPath(); } catch (IOException e) { // Bad path. Try the simpler normalization (which always works), but this may fail elsewhere. // Note manual FFDC. Apparently injection is not applied here. FFDCFilter.processException(e, PathUtils.class.getName(), "67"); return absPath.getAbsolutePath(); } } else { return absPath.getAbsolutePath(); } } }
public class class_name { @FFDCIgnore(IOException.class) public static String fixPathString(File absPath) { //on windows.. the path from config can have a different case to the actual filesystem path //and when notifications come back, they'll come back with the actual filsystem casing. //so, so ensure we all agree on what that should be, for windows, we use canonical path. // //getCanonicalPath however, sees 'through' symlinks, which means if we use it on paths //that are symlinked into the app, we'll see the actual paths instead of the symlinked ones. // //getCanonicalPath on windows however just happens not to be able to see through windows //symlinks (which are infrequently used anyways), so we're still safe to use it there, and //non-windows platforms are just fine sticking with the casing of the path supplied via //config. // //A future alternative will be to use File.toPath().getRealPath(LinkOptions.NOFOLLOW_LINKS); //when Liberty is java7 only.. if (isWindows) { try { return absPath.getCanonicalPath(); // depends on control dependency: [try], data = [none] } catch (IOException e) { // Bad path. Try the simpler normalization (which always works), but this may fail elsewhere. // Note manual FFDC. Apparently injection is not applied here. FFDCFilter.processException(e, PathUtils.class.getName(), "67"); return absPath.getAbsolutePath(); } // depends on control dependency: [catch], data = [none] } else { return absPath.getAbsolutePath(); // depends on control dependency: [if], data = [none] } } }
public class class_name { public ScreenComponent setupDefaultView(ScreenLoc itsLocation, ComponentParent targetScreen, Convert converter, int iDisplayFieldDesc, Map<String, Object> properties) // Add this view to the list { if (targetScreen instanceof GridScreenParent) return super.setupDefaultView(itsLocation, targetScreen, converter, iDisplayFieldDesc, properties); Record record = this.makeReferenceRecord(); ScreenComponent screenField = null; Map<String,Object> staticMap = new HashMap<String,Object>(); staticMap.put(ScreenModel.DISPLAY_STRING, DBConstants.BLANK); createScreenComponent(ScreenModel.STATIC_STRING, itsLocation, targetScreen, null, 0, staticMap); String strDisplay = converter.getFieldDesc(); if ((strDisplay != null) && (strDisplay.length() > 0)) { ScreenLoc descLocation = targetScreen.getNextLocation(ScreenConstants.FIELD_DESC, ScreenConstants.DONT_SET_ANCHOR); staticMap.put(ScreenModel.DISPLAY_STRING, strDisplay); createScreenComponent(ScreenModel.STATIC_STRING, descLocation, targetScreen, null, 0, staticMap); } try { record.close(); while (record.hasNext()) // 0 = First Day -> 6 = Last Day of Week { record.next(); Converter dayConverter = (Converter)converter; String strWeek = record.getField(record.getDefaultDisplayFieldSeq()).toString(); if (strWeek.length() > 0) dayConverter = new FieldDescConverter(dayConverter, strWeek); int sBitPosition = (int)record.getCounterField().getValue(); m_iBitsToCheck |= 1 << sBitPosition; dayConverter = new BitConverter(dayConverter, sBitPosition, true, true); itsLocation = targetScreen.getNextLocation(ScreenConstants.RIGHT_OF_LAST_CHECKBOX, ScreenConstants.DONT_SET_ANCHOR); screenField = dayConverter.setupDefaultView(itsLocation, targetScreen, iDisplayFieldDesc); } } catch (DBException e) { e.printStackTrace(); } return screenField; } }
public class class_name { public ScreenComponent setupDefaultView(ScreenLoc itsLocation, ComponentParent targetScreen, Convert converter, int iDisplayFieldDesc, Map<String, Object> properties) // Add this view to the list { if (targetScreen instanceof GridScreenParent) return super.setupDefaultView(itsLocation, targetScreen, converter, iDisplayFieldDesc, properties); Record record = this.makeReferenceRecord(); ScreenComponent screenField = null; Map<String,Object> staticMap = new HashMap<String,Object>(); staticMap.put(ScreenModel.DISPLAY_STRING, DBConstants.BLANK); createScreenComponent(ScreenModel.STATIC_STRING, itsLocation, targetScreen, null, 0, staticMap); String strDisplay = converter.getFieldDesc(); if ((strDisplay != null) && (strDisplay.length() > 0)) { ScreenLoc descLocation = targetScreen.getNextLocation(ScreenConstants.FIELD_DESC, ScreenConstants.DONT_SET_ANCHOR); staticMap.put(ScreenModel.DISPLAY_STRING, strDisplay); // depends on control dependency: [if], data = [none] createScreenComponent(ScreenModel.STATIC_STRING, descLocation, targetScreen, null, 0, staticMap); // depends on control dependency: [if], data = [none] } try { record.close(); // depends on control dependency: [try], data = [none] while (record.hasNext()) // 0 = First Day -> 6 = Last Day of Week { record.next(); // depends on control dependency: [while], data = [none] Converter dayConverter = (Converter)converter; String strWeek = record.getField(record.getDefaultDisplayFieldSeq()).toString(); if (strWeek.length() > 0) dayConverter = new FieldDescConverter(dayConverter, strWeek); int sBitPosition = (int)record.getCounterField().getValue(); m_iBitsToCheck |= 1 << sBitPosition; // depends on control dependency: [while], data = [none] dayConverter = new BitConverter(dayConverter, sBitPosition, true, true); // depends on control dependency: [while], data = [none] itsLocation = targetScreen.getNextLocation(ScreenConstants.RIGHT_OF_LAST_CHECKBOX, ScreenConstants.DONT_SET_ANCHOR); // depends on control dependency: [while], data = [none] screenField = dayConverter.setupDefaultView(itsLocation, targetScreen, iDisplayFieldDesc); // depends on control dependency: [while], data = [none] } } catch (DBException e) { e.printStackTrace(); } // depends on control dependency: [catch], data = [none] return screenField; } }
public class class_name { public MultipleDataProviderContext<DPO> read(DataProvider<DPO> dataProvider) { if (dataProvider != null) { addedDataProviders.add(dataProvider); } // Change context return new MultipleDataProviderContext<DPO>(addedTriggers, addedDataProviders); } }
public class class_name { public MultipleDataProviderContext<DPO> read(DataProvider<DPO> dataProvider) { if (dataProvider != null) { addedDataProviders.add(dataProvider); // depends on control dependency: [if], data = [(dataProvider] } // Change context return new MultipleDataProviderContext<DPO>(addedTriggers, addedDataProviders); } }
public class class_name { @Override public String asString(final String format) { try { return asString(EnglishEnums.valueOf(Format.class, format), null); } catch (final IllegalArgumentException ex) { return asString(); } } }
public class class_name { @Override public String asString(final String format) { try { return asString(EnglishEnums.valueOf(Format.class, format), null); // depends on control dependency: [try], data = [none] } catch (final IllegalArgumentException ex) { return asString(); } // depends on control dependency: [catch], data = [none] } }
public class class_name { void validate(Schema schema, ImmutableList<ProfileFileElement> profileFiles) { List<String> errors = new ArrayList<>(); for (ProfileFileElement profileFile : profileFiles) { for (TypeConfigElement typeConfig : profileFile.getTypeConfigs()) { ProtoType type = importedType(ProtoType.get(typeConfig.getType())); if (type == null) continue; Type resolvedType = schema.getType(type); if (resolvedType == null) { errors.add(String.format("unable to resolve %s (%s)", type, typeConfig.getLocation())); continue; } String requiredImport = resolvedType.location().getPath(); if (!profileFile.getImports().contains(requiredImport)) { errors.add(String.format("%s needs to import %s (%s)", typeConfig.getLocation().getPath(), requiredImport, typeConfig.getLocation())); } } } if (!errors.isEmpty()) { throw new SchemaException(errors); } } }
public class class_name { void validate(Schema schema, ImmutableList<ProfileFileElement> profileFiles) { List<String> errors = new ArrayList<>(); for (ProfileFileElement profileFile : profileFiles) { for (TypeConfigElement typeConfig : profileFile.getTypeConfigs()) { ProtoType type = importedType(ProtoType.get(typeConfig.getType())); if (type == null) continue; Type resolvedType = schema.getType(type); if (resolvedType == null) { errors.add(String.format("unable to resolve %s (%s)", type, typeConfig.getLocation())); // depends on control dependency: [if], data = [none] continue; } String requiredImport = resolvedType.location().getPath(); if (!profileFile.getImports().contains(requiredImport)) { errors.add(String.format("%s needs to import %s (%s)", typeConfig.getLocation().getPath(), requiredImport, typeConfig.getLocation())); // depends on control dependency: [if], data = [none] } } } if (!errors.isEmpty()) { throw new SchemaException(errors); } } }
public class class_name { public DevState[] extractDevStateArray() throws DevFailed { manageExceptions("extractDevStateArray()"); try { if (isArray()) { return DevVarStateArrayHelper.extract(attrval.value); } else { // It is used for state attribute return new DevState[] { DevStateHelper.extract(attrval.value) }; } } catch (final org.omg.CORBA.BAD_PARAM e) { Except .throw_wrong_data_exception( e.toString(), "Exception catched : " + e.toString() + "\n" + "Maybe the attribute value has not been initialized", "DeviceAttribute.extractDevStateArray()"); } return new DevState[0];// never used } }
public class class_name { public DevState[] extractDevStateArray() throws DevFailed { manageExceptions("extractDevStateArray()"); try { if (isArray()) { return DevVarStateArrayHelper.extract(attrval.value); // depends on control dependency: [if], data = [none] } else { // It is used for state attribute return new DevState[] { DevStateHelper.extract(attrval.value) }; // depends on control dependency: [if], data = [none] } } catch (final org.omg.CORBA.BAD_PARAM e) { Except .throw_wrong_data_exception( e.toString(), "Exception catched : " + e.toString() + "\n" + "Maybe the attribute value has not been initialized", "DeviceAttribute.extractDevStateArray()"); } return new DevState[0];// never used } }
public class class_name { protected void initPaths() { // Hand-rolled String.join(), for java 6 String[] split = getSplitDirPath(); String[] obsolete = getObsoleteDirPath(); //URLs are joined with '/' StringBuilder splitURL = new StringBuilder("/pub/pdb"); for(int i=0;i<split.length;i++) { splitURL.append("/"); splitURL.append(split[i]); } StringBuilder obsoleteURL = new StringBuilder("/pub/pdb"); for(int i=0;i<obsolete.length;i++) { obsoleteURL.append("/"); obsoleteURL.append(obsolete[i]); } splitDirURL = splitURL.toString(); obsoleteDirURL = obsoleteURL.toString(); //Files join themselves iteratively splitDirPath = path; for(int i=0;i<split.length;i++) { splitDirPath = new File(splitDirPath,split[i]); } obsoleteDirPath = path; for(int i=0;i<obsolete.length;i++) { obsoleteDirPath = new File(obsoleteDirPath,obsolete[i]); } } }
public class class_name { protected void initPaths() { // Hand-rolled String.join(), for java 6 String[] split = getSplitDirPath(); String[] obsolete = getObsoleteDirPath(); //URLs are joined with '/' StringBuilder splitURL = new StringBuilder("/pub/pdb"); for(int i=0;i<split.length;i++) { splitURL.append("/"); // depends on control dependency: [for], data = [none] splitURL.append(split[i]); // depends on control dependency: [for], data = [i] } StringBuilder obsoleteURL = new StringBuilder("/pub/pdb"); for(int i=0;i<obsolete.length;i++) { obsoleteURL.append("/"); // depends on control dependency: [for], data = [none] obsoleteURL.append(obsolete[i]); // depends on control dependency: [for], data = [i] } splitDirURL = splitURL.toString(); obsoleteDirURL = obsoleteURL.toString(); //Files join themselves iteratively splitDirPath = path; for(int i=0;i<split.length;i++) { splitDirPath = new File(splitDirPath,split[i]); // depends on control dependency: [for], data = [i] } obsoleteDirPath = path; for(int i=0;i<obsolete.length;i++) { obsoleteDirPath = new File(obsoleteDirPath,obsolete[i]); // depends on control dependency: [for], data = [i] } } }
public class class_name { protected boolean isGetterMethod(ExecutableElement executableElement) { // must have a return value TypeMirror returnTypeMirror = executableElement.getReturnType(); if (returnTypeMirror.getKind().equals(TypeKind.VOID)) { error(executableElement, "method %s must have a non void return type", executableElement.getSimpleName().toString()); return false; } // check if method takes no parameters List parameters = executableElement.getParameters(); if (parameters != null && parameters.size() > 0) { error(executableElement, "method %s must have no parameters ", executableElement.getSimpleName().toString()); return false; } return true; } }
public class class_name { protected boolean isGetterMethod(ExecutableElement executableElement) { // must have a return value TypeMirror returnTypeMirror = executableElement.getReturnType(); if (returnTypeMirror.getKind().equals(TypeKind.VOID)) { error(executableElement, "method %s must have a non void return type", executableElement.getSimpleName().toString()); // depends on control dependency: [if], data = [none] return false; // depends on control dependency: [if], data = [none] } // check if method takes no parameters List parameters = executableElement.getParameters(); if (parameters != null && parameters.size() > 0) { error(executableElement, "method %s must have no parameters ", executableElement.getSimpleName().toString()); // depends on control dependency: [if], data = [none] return false; // depends on control dependency: [if], data = [none] } return true; } }
public class class_name { public float getMetallic() { Property p = getProperty(PropertyKey.METALLIC.m_key); if (null == p || null == p.getData()) { throw new IllegalArgumentException("Metallic property not found"); } Object rawValue = p.getData(); if (rawValue instanceof java.nio.ByteBuffer) { java.nio.FloatBuffer fbuf = ((java.nio.ByteBuffer) rawValue).asFloatBuffer(); return fbuf.get(); } else { return (Float) rawValue; } } }
public class class_name { public float getMetallic() { Property p = getProperty(PropertyKey.METALLIC.m_key); if (null == p || null == p.getData()) { throw new IllegalArgumentException("Metallic property not found"); } Object rawValue = p.getData(); if (rawValue instanceof java.nio.ByteBuffer) { java.nio.FloatBuffer fbuf = ((java.nio.ByteBuffer) rawValue).asFloatBuffer(); return fbuf.get(); // depends on control dependency: [if], data = [none] } else { return (Float) rawValue; // depends on control dependency: [if], data = [none] } } }
public class class_name { public SelectableStringList selectablePersonsProperty() { if (selectablePersons == null) { selectablePersons = new SelectableItemList<>( FXCollections.observableArrayList(repository.getPersons()), person -> person.getFirstName() + " " + person.getLastName()); } return selectablePersons; } }
public class class_name { public SelectableStringList selectablePersonsProperty() { if (selectablePersons == null) { selectablePersons = new SelectableItemList<>( FXCollections.observableArrayList(repository.getPersons()), person -> person.getFirstName() + " " + person.getLastName()); // depends on control dependency: [if], data = [none] } return selectablePersons; } }
public class class_name { @Override public void stopScan() { lock.lock(); try { if (!State.NOT_STARTED.equals(state) && !State.FINISHED.equals(state)) { spiderThread.stopScan(); state = State.FINISHED; SpiderEventPublisher.publishScanEvent( ScanEventPublisher.SCAN_STOPPED_EVENT, this.scanId); } } finally { lock.unlock(); } } }
public class class_name { @Override public void stopScan() { lock.lock(); try { if (!State.NOT_STARTED.equals(state) && !State.FINISHED.equals(state)) { spiderThread.stopScan(); // depends on control dependency: [if], data = [none] state = State.FINISHED; // depends on control dependency: [if], data = [none] SpiderEventPublisher.publishScanEvent( ScanEventPublisher.SCAN_STOPPED_EVENT, this.scanId); // depends on control dependency: [if], data = [none] } } finally { lock.unlock(); } } }
public class class_name { public ResourceList filter(final ResourceFilter filter) { final ResourceList resourcesFiltered = new ResourceList(); for (final Resource resource : this) { if (filter.accept(resource)) { resourcesFiltered.add(resource); } } return resourcesFiltered; } }
public class class_name { public ResourceList filter(final ResourceFilter filter) { final ResourceList resourcesFiltered = new ResourceList(); for (final Resource resource : this) { if (filter.accept(resource)) { resourcesFiltered.add(resource); // depends on control dependency: [if], data = [none] } } return resourcesFiltered; } }
public class class_name { public Expression<Byte> in(Byte[] value) { String listNumberString = ""; Boolean firstNumber = true; for (Byte v : value) { if (firstNumber) { listNumberString = listNumberString.concat("('").concat(v.toString()).concat("'"); firstNumber = false; } else { listNumberString = listNumberString.concat(", '").concat(v.toString()).concat("'"); } } listNumberString = listNumberString.concat(")"); return new Expression<Byte>(this, Operation.in, listNumberString); } }
public class class_name { public Expression<Byte> in(Byte[] value) { String listNumberString = ""; Boolean firstNumber = true; for (Byte v : value) { if (firstNumber) { listNumberString = listNumberString.concat("('").concat(v.toString()).concat("'"); firstNumber = false; // depends on control dependency: [if], data = [none] } else { listNumberString = listNumberString.concat(", '").concat(v.toString()).concat("'"); // depends on control dependency: [if], data = [none] } } listNumberString = listNumberString.concat(")"); return new Expression<Byte>(this, Operation.in, listNumberString); } }
public class class_name { void add(EventQueue source) { while (true) { EventChannelsTuple entry = source.poll(); if (entry == null) { break; } entry.event.processedBy(this); queue.add(entry); } synchronized (this) { if (!isExecuting) { GeneratorRegistry.instance().add(this); isExecuting = true; executorService.execute(this); } } } }
public class class_name { void add(EventQueue source) { while (true) { EventChannelsTuple entry = source.poll(); if (entry == null) { break; } entry.event.processedBy(this); // depends on control dependency: [while], data = [none] queue.add(entry); // depends on control dependency: [while], data = [none] } synchronized (this) { if (!isExecuting) { GeneratorRegistry.instance().add(this); // depends on control dependency: [if], data = [none] isExecuting = true; // depends on control dependency: [if], data = [none] executorService.execute(this); // depends on control dependency: [if], data = [none] } } } }
public class class_name { public static RangeInclusiveI checkRangeIncludedInInteger( final RangeInclusiveI inner, final String inner_name, final RangeInclusiveI outer, final String outer_name) { Objects.requireNonNull(inner, "Inner range"); Objects.requireNonNull(inner_name, "Inner range name"); Objects.requireNonNull(outer, "Outer range"); Objects.requireNonNull(outer_name, "Outer range name"); if (inner.isIncludedIn(outer)) { return inner; } final var message = String.format( "Inner range %s (%s) not included in outer range %s (%s)", inner_name, inner, outer_name, outer); throw new RangeCheckException(message); } }
public class class_name { public static RangeInclusiveI checkRangeIncludedInInteger( final RangeInclusiveI inner, final String inner_name, final RangeInclusiveI outer, final String outer_name) { Objects.requireNonNull(inner, "Inner range"); Objects.requireNonNull(inner_name, "Inner range name"); Objects.requireNonNull(outer, "Outer range"); Objects.requireNonNull(outer_name, "Outer range name"); if (inner.isIncludedIn(outer)) { return inner; // depends on control dependency: [if], data = [none] } final var message = String.format( "Inner range %s (%s) not included in outer range %s (%s)", inner_name, inner, outer_name, outer); throw new RangeCheckException(message); } }
public class class_name { protected void generateScriptBuilderImpl() { final List<StringConcatenationClient> topElements = generateTopElements(false, false); final TypeReference script = getScriptBuilderImpl(); final TypeReference scriptInterface = getScriptBuilderInterface(); final StringConcatenationClient content = new StringConcatenationClient() { @Override protected void appendTo(TargetStringConcatenation it) { it.append("@SuppressWarnings(\"all\")"); //$NON-NLS-1$ it.newLine(); it.append("public class "); //$NON-NLS-1$ it.append(script.getSimpleName()); it.append(" extends "); //$NON-NLS-1$ it.append(getAbstractBuilderImpl()); it.append(" implements "); //$NON-NLS-1$ it.append(scriptInterface); it.append(" {"); //$NON-NLS-1$ it.newLineIfNotEmpty(); it.newLine(); it.append(generateFieldsAndMethods(false, false)); for (final StringConcatenationClient element : topElements) { it.append(element); } it.append("}"); //$NON-NLS-1$ it.newLineIfNotEmpty(); } }; final JavaFileAccess javaFile = getFileAccessFactory().createJavaFile(script, content); javaFile.writeTo(getSrcGen()); } }
public class class_name { protected void generateScriptBuilderImpl() { final List<StringConcatenationClient> topElements = generateTopElements(false, false); final TypeReference script = getScriptBuilderImpl(); final TypeReference scriptInterface = getScriptBuilderInterface(); final StringConcatenationClient content = new StringConcatenationClient() { @Override protected void appendTo(TargetStringConcatenation it) { it.append("@SuppressWarnings(\"all\")"); //$NON-NLS-1$ it.newLine(); it.append("public class "); //$NON-NLS-1$ it.append(script.getSimpleName()); it.append(" extends "); //$NON-NLS-1$ it.append(getAbstractBuilderImpl()); it.append(" implements "); //$NON-NLS-1$ it.append(scriptInterface); it.append(" {"); //$NON-NLS-1$ it.newLineIfNotEmpty(); it.newLine(); it.append(generateFieldsAndMethods(false, false)); for (final StringConcatenationClient element : topElements) { it.append(element); // depends on control dependency: [for], data = [element] } it.append("}"); //$NON-NLS-1$ it.newLineIfNotEmpty(); } }; final JavaFileAccess javaFile = getFileAccessFactory().createJavaFile(script, content); javaFile.writeTo(getSrcGen()); } }
public class class_name { public static void setSpinnerDraggingEnabled( final JSpinner spinner, boolean enabled) { SpinnerModel spinnerModel = spinner.getModel(); if (!(spinnerModel instanceof SpinnerNumberModel)) { throw new IllegalArgumentException( "Dragging is only possible for spinners with a " + "SpinnerNumberModel, found "+spinnerModel.getClass()); } if (enabled) { disableSpinnerDragging(spinner); enableSpinnerDragging(spinner); } else { disableSpinnerDragging(spinner); } } }
public class class_name { public static void setSpinnerDraggingEnabled( final JSpinner spinner, boolean enabled) { SpinnerModel spinnerModel = spinner.getModel(); if (!(spinnerModel instanceof SpinnerNumberModel)) { throw new IllegalArgumentException( "Dragging is only possible for spinners with a " + "SpinnerNumberModel, found "+spinnerModel.getClass()); } if (enabled) { disableSpinnerDragging(spinner); // depends on control dependency: [if], data = [none] enableSpinnerDragging(spinner); // depends on control dependency: [if], data = [none] } else { disableSpinnerDragging(spinner); // depends on control dependency: [if], data = [none] } } }
public class class_name { public Stream<String> lines() { Iterator<String> iter = new Iterator<String>() { String nextLine = null; @Override public boolean hasNext() { if (nextLine != null) { return true; } else { try { nextLine = readLine(true); return (nextLine != null); } catch (IOException e) { throw new UncheckedIOException(e); } } } @Override public String next() { if (nextLine != null || hasNext()) { String line = nextLine; nextLine = null; return line; } else { throw new NoSuchElementException(); } } }; return StreamSupport.stream(Spliterators.spliteratorUnknownSize( iter, Spliterator.ORDERED | Spliterator.NONNULL), false); } }
public class class_name { public Stream<String> lines() { Iterator<String> iter = new Iterator<String>() { String nextLine = null; @Override public boolean hasNext() { if (nextLine != null) { return true; // depends on control dependency: [if], data = [none] } else { try { nextLine = readLine(true); // depends on control dependency: [try], data = [none] return (nextLine != null); // depends on control dependency: [try], data = [none] } catch (IOException e) { throw new UncheckedIOException(e); } // depends on control dependency: [catch], data = [none] } } @Override public String next() { if (nextLine != null || hasNext()) { String line = nextLine; nextLine = null; // depends on control dependency: [if], data = [none] return line; // depends on control dependency: [if], data = [none] } else { throw new NoSuchElementException(); } } }; return StreamSupport.stream(Spliterators.spliteratorUnknownSize( iter, Spliterator.ORDERED | Spliterator.NONNULL), false); } }
public class class_name { public void register(Region region, String prefix) { // validate the method arguments if (region == null || prefix == null) { throw new IllegalArgumentException("Neither Region nor Prefix may be null"); } // Add a LazyStyle for this region/prefix to styleMap. List<LazyStyle> styles = styleMap.get(region); if (styles == null) { styles = new LinkedList<LazyStyle>(); styles.add(new LazyStyle(prefix)); styleMap.put(region, styles); } else { // iterate over all the current styles and see if this prefix has // already been registered. If not, then register it. for (LazyStyle s : styles) { if (prefix.equals(s.prefix)) { return; } } styles.add(new LazyStyle(prefix)); } // add this region to the map of registered regions registeredRegions.put(region.getName(), region); } }
public class class_name { public void register(Region region, String prefix) { // validate the method arguments if (region == null || prefix == null) { throw new IllegalArgumentException("Neither Region nor Prefix may be null"); } // Add a LazyStyle for this region/prefix to styleMap. List<LazyStyle> styles = styleMap.get(region); if (styles == null) { styles = new LinkedList<LazyStyle>(); // depends on control dependency: [if], data = [none] styles.add(new LazyStyle(prefix)); // depends on control dependency: [if], data = [none] styleMap.put(region, styles); // depends on control dependency: [if], data = [none] } else { // iterate over all the current styles and see if this prefix has // already been registered. If not, then register it. for (LazyStyle s : styles) { if (prefix.equals(s.prefix)) { return; // depends on control dependency: [if], data = [none] } } styles.add(new LazyStyle(prefix)); // depends on control dependency: [if], data = [none] } // add this region to the map of registered regions registeredRegions.put(region.getName(), region); } }
public class class_name { public FireableEventType getEventId(EventLookupFacility eventLookupFacility, Response response) { String statusCodeName = null; final int responseStatus = response.getStatusCode(); if (responseStatus == 100) { statusCodeName = "TRYING"; } else if (100 < responseStatus && responseStatus < 200) { statusCodeName = "PROVISIONAL"; } else if (responseStatus < 300) { statusCodeName = "SUCCESS"; } else if (responseStatus < 400) { statusCodeName = "REDIRECT"; } else if (responseStatus < 500) { statusCodeName = "CLIENT_ERROR"; } else if (responseStatus < 600) { statusCodeName = "SERVER_ERROR"; } else { statusCodeName = "GLOBAL_FAILURE"; } // in dialog responses use the 1.1 event id prefix return getEventId(eventLookupFacility, new StringBuilder(RESPONSE_EVENT_PREFIX).append(statusCodeName).toString()); } }
public class class_name { public FireableEventType getEventId(EventLookupFacility eventLookupFacility, Response response) { String statusCodeName = null; final int responseStatus = response.getStatusCode(); if (responseStatus == 100) { statusCodeName = "TRYING"; // depends on control dependency: [if], data = [none] } else if (100 < responseStatus && responseStatus < 200) { statusCodeName = "PROVISIONAL"; // depends on control dependency: [if], data = [none] } else if (responseStatus < 300) { statusCodeName = "SUCCESS"; // depends on control dependency: [if], data = [none] } else if (responseStatus < 400) { statusCodeName = "REDIRECT"; // depends on control dependency: [if], data = [none] } else if (responseStatus < 500) { statusCodeName = "CLIENT_ERROR"; // depends on control dependency: [if], data = [none] } else if (responseStatus < 600) { statusCodeName = "SERVER_ERROR"; // depends on control dependency: [if], data = [none] } else { statusCodeName = "GLOBAL_FAILURE"; // depends on control dependency: [if], data = [none] } // in dialog responses use the 1.1 event id prefix return getEventId(eventLookupFacility, new StringBuilder(RESPONSE_EVENT_PREFIX).append(statusCodeName).toString()); } }
public class class_name { private void readPropertySourceFromLoader(String fileName, String filePath, PropertySourceLoader propertySourceLoader, List<PropertySource> propertySources) throws ConfigurationException { ResourceResolver resourceResolver = new ResourceResolver(); Optional<ResourceLoader> resourceLoader = resourceResolver.getSupportingLoader(filePath); ResourceLoader loader = resourceLoader.orElse(FileSystemResourceLoader.defaultLoader()); try { Optional<InputStream> inputStream = loader.getResourceAsStream(filePath); if (inputStream.isPresent()) { Map<String, Object> properties = propertySourceLoader.read(fileName, inputStream.get()); propertySources.add(PropertySource.of(properties)); } } catch (IOException e) { throw new ConfigurationException("Unsupported properties file: " + fileName); } } }
public class class_name { private void readPropertySourceFromLoader(String fileName, String filePath, PropertySourceLoader propertySourceLoader, List<PropertySource> propertySources) throws ConfigurationException { ResourceResolver resourceResolver = new ResourceResolver(); Optional<ResourceLoader> resourceLoader = resourceResolver.getSupportingLoader(filePath); ResourceLoader loader = resourceLoader.orElse(FileSystemResourceLoader.defaultLoader()); try { Optional<InputStream> inputStream = loader.getResourceAsStream(filePath); if (inputStream.isPresent()) { Map<String, Object> properties = propertySourceLoader.read(fileName, inputStream.get()); propertySources.add(PropertySource.of(properties)); // depends on control dependency: [if], data = [none] } } catch (IOException e) { throw new ConfigurationException("Unsupported properties file: " + fileName); } } }
public class class_name { @NonNull public static <T> ObjectAnimator ofFloat(@Nullable T target, @NonNull Property<T, Float> xProperty, @NonNull Property<T, Float> yProperty, @NonNull Path path) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { return ObjectAnimatorCompatLollipop.ofFloat(target, xProperty, yProperty, path); } else { return ObjectAnimatorCompatBase.ofFloat(target, xProperty, yProperty, path); } } }
public class class_name { @NonNull public static <T> ObjectAnimator ofFloat(@Nullable T target, @NonNull Property<T, Float> xProperty, @NonNull Property<T, Float> yProperty, @NonNull Path path) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { return ObjectAnimatorCompatLollipop.ofFloat(target, xProperty, yProperty, path); // depends on control dependency: [if], data = [none] } else { return ObjectAnimatorCompatBase.ofFloat(target, xProperty, yProperty, path); // depends on control dependency: [if], data = [none] } } }
public class class_name { @Override public ListenableFuture<List<SampleRowKeysResponse>> sampleRowKeysAsync( SampleRowKeysRequest request) { if (shouldOverrideAppProfile(request.getAppProfileId())) { request = request.toBuilder().setAppProfileId(clientDefaultAppProfileId).build(); } return createStreamingListener(request, sampleRowKeysAsync, request.getTableName()) .getAsyncResult(); } }
public class class_name { @Override public ListenableFuture<List<SampleRowKeysResponse>> sampleRowKeysAsync( SampleRowKeysRequest request) { if (shouldOverrideAppProfile(request.getAppProfileId())) { request = request.toBuilder().setAppProfileId(clientDefaultAppProfileId).build(); // depends on control dependency: [if], data = [none] } return createStreamingListener(request, sampleRowKeysAsync, request.getTableName()) .getAsyncResult(); } }
public class class_name { public void setTaskSetsInfo(java.util.Collection<ECSTaskSet> taskSetsInfo) { if (taskSetsInfo == null) { this.taskSetsInfo = null; return; } this.taskSetsInfo = new com.amazonaws.internal.SdkInternalList<ECSTaskSet>(taskSetsInfo); } }
public class class_name { public void setTaskSetsInfo(java.util.Collection<ECSTaskSet> taskSetsInfo) { if (taskSetsInfo == null) { this.taskSetsInfo = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.taskSetsInfo = new com.amazonaws.internal.SdkInternalList<ECSTaskSet>(taskSetsInfo); } }
public class class_name { public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { LOG.debug("In retry request"); if (exception == null) { throw new IllegalArgumentException("Exception parameter may not be null"); } else if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } if (executionCount > this.retryCount) { return checkPolicy(executionCount); } else if (exception instanceof NoHttpResponseException) { // Retry if the server dropped connection on us return checkPolicy(executionCount); } else if (exception instanceof InterruptedIOException) { // Timeout return false; } else if (exception instanceof UnknownHostException) { // Unknown host return false; } else if (exception instanceof ConnectException) { // Connection refused return false; } else if (exception instanceof SSLException) { // SSL handshake exception return false; } else if (exception instanceof ProtocolException) { // protocol exception return false; } else if (exception instanceof SaslException) { // Sasl exception return false; } HttpRequest request = (HttpRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST); boolean idempotent = !(request instanceof HttpEntityEnclosingRequest); if (idempotent) { // Retry if the request is considered idempotent return checkPolicy(executionCount); } Boolean b = (Boolean) context.getAttribute(HttpCoreContext.HTTP_REQ_SENT); boolean sent = (b != null && b.booleanValue()); // if (!sent || this.requestSentRetryEnabled) { // Retry if the request has not been sent fully or // if it's OK to retry methods that have been sent if (!sent) { return checkPolicy(executionCount); } // otherwise do not retry return false; } }
public class class_name { public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { LOG.debug("In retry request"); if (exception == null) { throw new IllegalArgumentException("Exception parameter may not be null"); } else if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } if (executionCount > this.retryCount) { return checkPolicy(executionCount); // depends on control dependency: [if], data = [(executionCount] } else if (exception instanceof NoHttpResponseException) { // Retry if the server dropped connection on us return checkPolicy(executionCount); // depends on control dependency: [if], data = [none] } else if (exception instanceof InterruptedIOException) { // Timeout return false; // depends on control dependency: [if], data = [none] } else if (exception instanceof UnknownHostException) { // Unknown host return false; // depends on control dependency: [if], data = [none] } else if (exception instanceof ConnectException) { // Connection refused return false; // depends on control dependency: [if], data = [none] } else if (exception instanceof SSLException) { // SSL handshake exception return false; // depends on control dependency: [if], data = [none] } else if (exception instanceof ProtocolException) { // protocol exception return false; // depends on control dependency: [if], data = [none] } else if (exception instanceof SaslException) { // Sasl exception return false; // depends on control dependency: [if], data = [none] } HttpRequest request = (HttpRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST); boolean idempotent = !(request instanceof HttpEntityEnclosingRequest); if (idempotent) { // Retry if the request is considered idempotent return checkPolicy(executionCount); // depends on control dependency: [if], data = [none] } Boolean b = (Boolean) context.getAttribute(HttpCoreContext.HTTP_REQ_SENT); boolean sent = (b != null && b.booleanValue()); // if (!sent || this.requestSentRetryEnabled) { // Retry if the request has not been sent fully or // if it's OK to retry methods that have been sent if (!sent) { return checkPolicy(executionCount); // depends on control dependency: [if], data = [none] } // otherwise do not retry return false; } }
public class class_name { public static double nextAfter(double d, double direction) { // handling of some important special cases if (Double.isNaN(d) || Double.isNaN(direction)) { return Double.NaN; } else if (d == direction) { return direction; } else if (Double.isInfinite(d)) { return (d < 0) ? -Double.MAX_VALUE : Double.MAX_VALUE; } else if (d == 0) { return (direction < 0) ? -Double.MIN_VALUE : Double.MIN_VALUE; } // special cases MAX_VALUE to infinity and MIN_VALUE to 0 // are handled just as normal numbers final long bits = Double.doubleToLongBits(d); final long sign = bits & 0x8000000000000000L; if ((direction < d) ^ (sign == 0L)) { return Double.longBitsToDouble(sign | ((bits & 0x7fffffffffffffffL) + 1)); } else { return Double.longBitsToDouble(sign | ((bits & 0x7fffffffffffffffL) - 1)); } } }
public class class_name { public static double nextAfter(double d, double direction) { // handling of some important special cases if (Double.isNaN(d) || Double.isNaN(direction)) { return Double.NaN; // depends on control dependency: [if], data = [none] } else if (d == direction) { return direction; // depends on control dependency: [if], data = [none] } else if (Double.isInfinite(d)) { return (d < 0) ? -Double.MAX_VALUE : Double.MAX_VALUE; // depends on control dependency: [if], data = [none] } else if (d == 0) { return (direction < 0) ? -Double.MIN_VALUE : Double.MIN_VALUE; // depends on control dependency: [if], data = [(d] } // special cases MAX_VALUE to infinity and MIN_VALUE to 0 // are handled just as normal numbers final long bits = Double.doubleToLongBits(d); final long sign = bits & 0x8000000000000000L; if ((direction < d) ^ (sign == 0L)) { return Double.longBitsToDouble(sign | ((bits & 0x7fffffffffffffffL) + 1)); // depends on control dependency: [if], data = [none] } else { return Double.longBitsToDouble(sign | ((bits & 0x7fffffffffffffffL) - 1)); // depends on control dependency: [if], data = [none] } } }
public class class_name { public SIBUuid8 updateLocalisationSet(SIBUuid8 newLocalisingMEUuid, SIBUuid8 newRoutingMEUuid) throws SIResourceException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "updateLocalisationSet", new Object[] {newLocalisingMEUuid, newRoutingMEUuid}); // Create a local UOW LocalTransaction transaction = _baseDestinationHandler. getTransactionManager(). createLocalTransaction(false); Transaction msTran = _messageProcessor.resolveAndEnlistMsgStoreTransaction(transaction); boolean rollback = true; // Assume the worse SIBUuid8 existingUuid = null; try { synchronized(_localisationManager.getAllXmitQueuePoints()) { HashMap validXmits = new HashMap(); Iterator it = _localisationManager.getAllXmitQueuePoints().values().iterator(); while (it.hasNext()) { PtoPXmitMsgsItemStream xmit = (PtoPXmitMsgsItemStream)it.next(); if (xmit.isToBeDeleted()) _deletedQueuePoints.put(xmit.getLocalizingMEUuid(), xmit); else validXmits.put(xmit.getLocalizingMEUuid(), xmit); } //Validity check - there should only by one existing localisation if (validXmits.size() > 1 || (validXmits.size() > 0) && (_pToPLocalMsgsItemStream != null)) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "updateLocalisationSet"); SibTr.error(tc, "INTERNAL_MESSAGING_ERROR_CWSIP0001", new Object[] { "com.ibm.ws.sib.processor.impl.LinkHandler", "1:302:1.21"}); throw new SIErrorException(nls.getFormattedMessage( "INTERNAL_MESSAGING_ERROR_CWSIP0001", new Object[] { "com.ibm.ws.sib.processor.impl.destination.LinkState", "1:308:1.21"}, null)); } //Is there a localisation for the new MEUuid that is in the process of //being deleted? PtoPMessageItemStream deletingItemStream = (PtoPMessageItemStream) _deletedQueuePoints.get(newLocalisingMEUuid); if ((deletingItemStream != null) && (!(deletingItemStream.isInStore()))) { //There was an old queuepoint but its no longer in the messagestore, so it //has been deleted and we can create a new one instead deletingItemStream = null; } if (validXmits.size() == 0 && _pToPLocalMsgsItemStream == null) { //There are no live localisations. Is there one in deleting state? if (deletingItemStream != null) { deletingItemStream.unmarkAsToBeDeleted(msTran); _deletedQueuePoints.remove(newLocalisingMEUuid); _localisationManager. attachRemotePtoPLocalisation(deletingItemStream, _remoteSupport); assignQueuePointOutputHandler(deletingItemStream.getOutputHandler(), newLocalisingMEUuid); } else { // No localisations existed. Create the new one PtoPMessageItemStream newStream = _localisationManager.addNewRemotePtoPLocalization(transaction, newLocalisingMEUuid, null, true, _remoteSupport); ((PtoPOutputHandler)newStream .getOutputHandler()) .updateRoutingCellule(newRoutingMEUuid); } } else { //Get the existing uuid PtoPMessageItemStream ptoPMessageItemStream = null; // If a local itemstream exists then we are an MQLink that is localised on this ME // Therefore dont bother to update state. if (_pToPLocalMsgsItemStream == null) { Iterator transmitQueueIterator = validXmits.values().iterator(); ptoPMessageItemStream = (PtoPMessageItemStream) transmitQueueIterator.next(); PtoPOutputHandler outputHandler = (PtoPOutputHandler)ptoPMessageItemStream.getOutputHandler(); existingUuid = ptoPMessageItemStream.getLocalizingMEUuid(); //Its possible that we dont know the uuid of the localising ME at the other //end of the link, as its in another bus so we rely on TRM to get it for us. //In this case, the UUID constant UNKNOWN_UUID is used. if (newLocalisingMEUuid.toString().equals(SIMPConstants.UNKNOWN_UUID)) { // localisingMe is unknown - dont do anything } else if (existingUuid.equals(newLocalisingMEUuid) || existingUuid.equals(new SIBUuid8(SIMPConstants.UNKNOWN_UUID))) { //The existing localisation has the UNKNOWN_UUID constant, but the //localisation being passed in has a real uuid, so the existing //localisation should be updated to use the real uuid. ptoPMessageItemStream.replaceUuid(newLocalisingMEUuid, msTran); //Update the localisation in the hashSets _localisationManager.removeXmitQueuePoint(existingUuid); _localisationManager.addXmitQueuePoint( newLocalisingMEUuid, ptoPMessageItemStream); outputHandler.updateTargetCellule(newLocalisingMEUuid); //Update the outputhandler lookup _localisationManager. updateQueuePointOutputHandler(newLocalisingMEUuid, outputHandler, existingUuid); } else { // The localisation of the link has moved. Add in the new localisation // and delete the old one. //Is there an instance of the localisation in deleting state? if (deletingItemStream != null) { deletingItemStream.unmarkAsToBeDeleted(msTran); _deletedQueuePoints.remove(newLocalisingMEUuid); _localisationManager.addXmitQueuePoint( deletingItemStream.getLocalizingMEUuid(), deletingItemStream); assignQueuePointOutputHandler(deletingItemStream.getOutputHandler(), newLocalisingMEUuid); } else { PtoPMessageItemStream newStream = _localisationManager.addNewRemotePtoPLocalization(transaction, newLocalisingMEUuid, null, true, _remoteSupport); ((PtoPOutputHandler)newStream .getOutputHandler()) .updateRoutingCellule(newRoutingMEUuid); } // 176658.3.3 transaction.registerCallback( _localisationManager.new LocalizationRemoveTransactionCallback(ptoPMessageItemStream)); // Mark the localisation for deletion ptoPMessageItemStream.markAsToBeDeleted(msTran); //Remember the deleted localisation incase we need to reincarnate it. //This is a behaviuor reserved for links. Because the other end of the //link is in another bus and wont know if this end of the link is deleted, //it will still be using the stream state associated with this link, //so if at a future point the link is recreated to the same ME, we should //use the same stream state if we can. _deletedQueuePoints.put(existingUuid, ptoPMessageItemStream); //Get the background clean-up thread to reallocate the messages and //clean up the localisation if possible. _destinationManager.markDestinationAsCleanUpPending(_baseDestinationHandler); // If the old link is localised to this ME then it'll have a proxy // pubsub neighbour setup, so we need to delete that. The easiest way to // check is to see if a neighbour actually exists or not. if(_messageProcessor.getProxyHandler().getNeighbour(existingUuid, true) != null) { try { //Cleanup the neighbours _messageProcessor.getProxyHandler().deleteNeighbourForced(existingUuid, _baseDestinationHandler.getBus() , (Transaction)transaction); } catch (Exception e) { // As the neighbours aren't locked down there's a chance of a problem, // but we'll report the error and carry on. // FFDC FFDCFilter.processException(e, "com.ibm.ws.sib.processor.impl.destination.LinkState.updateLocalisationSet", "1:473:1.21", this); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "Caught exception when deleting neighbour, however this is not always an issue as it might have already been removed: " + e); } } } // Set the new routingCellule. Take into account the sending MEs that do not have // the link localised on their ME if(newRoutingMEUuid != null) { // If link is localised here if (newRoutingMEUuid.equals(_messageProcessor.getMessagingEngineUuid())) newRoutingMEUuid = newLocalisingMEUuid; outputHandler.updateRoutingCellule(newRoutingMEUuid); } } } } // We got through it without failing! rollback = false; } finally { //Commit the transaction outside of synchronisation of the linkHandler try { if(rollback) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "Update failed, transaction rolling back"); transaction.rollback(); } else transaction.commit(); } catch (SIIncorrectCallException e) { // No FFDC code needed if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "updateLocalisationSet", e); throw new SIResourceException(e); } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "updateLocalisationSet", existingUuid); return existingUuid; } }
public class class_name { public SIBUuid8 updateLocalisationSet(SIBUuid8 newLocalisingMEUuid, SIBUuid8 newRoutingMEUuid) throws SIResourceException { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(tc, "updateLocalisationSet", new Object[] {newLocalisingMEUuid, newRoutingMEUuid}); // Create a local UOW LocalTransaction transaction = _baseDestinationHandler. getTransactionManager(). createLocalTransaction(false); Transaction msTran = _messageProcessor.resolveAndEnlistMsgStoreTransaction(transaction); boolean rollback = true; // Assume the worse SIBUuid8 existingUuid = null; try { synchronized(_localisationManager.getAllXmitQueuePoints()) // depends on control dependency: [try], data = [none] { HashMap validXmits = new HashMap(); Iterator it = _localisationManager.getAllXmitQueuePoints().values().iterator(); while (it.hasNext()) { PtoPXmitMsgsItemStream xmit = (PtoPXmitMsgsItemStream)it.next(); if (xmit.isToBeDeleted()) _deletedQueuePoints.put(xmit.getLocalizingMEUuid(), xmit); else validXmits.put(xmit.getLocalizingMEUuid(), xmit); } //Validity check - there should only by one existing localisation if (validXmits.size() > 1 || (validXmits.size() > 0) && (_pToPLocalMsgsItemStream != null)) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "updateLocalisationSet"); SibTr.error(tc, "INTERNAL_MESSAGING_ERROR_CWSIP0001", new Object[] { "com.ibm.ws.sib.processor.impl.LinkHandler", "1:302:1.21"}); // depends on control dependency: [if], data = [none] throw new SIErrorException(nls.getFormattedMessage( "INTERNAL_MESSAGING_ERROR_CWSIP0001", new Object[] { "com.ibm.ws.sib.processor.impl.destination.LinkState", "1:308:1.21"}, null)); } //Is there a localisation for the new MEUuid that is in the process of //being deleted? PtoPMessageItemStream deletingItemStream = (PtoPMessageItemStream) _deletedQueuePoints.get(newLocalisingMEUuid); if ((deletingItemStream != null) && (!(deletingItemStream.isInStore()))) { //There was an old queuepoint but its no longer in the messagestore, so it //has been deleted and we can create a new one instead deletingItemStream = null; // depends on control dependency: [if], data = [none] } if (validXmits.size() == 0 && _pToPLocalMsgsItemStream == null) { //There are no live localisations. Is there one in deleting state? if (deletingItemStream != null) { deletingItemStream.unmarkAsToBeDeleted(msTran); // depends on control dependency: [if], data = [none] _deletedQueuePoints.remove(newLocalisingMEUuid); // depends on control dependency: [if], data = [none] _localisationManager. attachRemotePtoPLocalisation(deletingItemStream, _remoteSupport); // depends on control dependency: [if], data = [none] assignQueuePointOutputHandler(deletingItemStream.getOutputHandler(), newLocalisingMEUuid); // depends on control dependency: [if], data = [(deletingItemStream] } else { // No localisations existed. Create the new one PtoPMessageItemStream newStream = _localisationManager.addNewRemotePtoPLocalization(transaction, newLocalisingMEUuid, null, true, _remoteSupport); ((PtoPOutputHandler)newStream .getOutputHandler()) .updateRoutingCellule(newRoutingMEUuid); // depends on control dependency: [if], data = [none] } } else { //Get the existing uuid PtoPMessageItemStream ptoPMessageItemStream = null; // If a local itemstream exists then we are an MQLink that is localised on this ME // Therefore dont bother to update state. if (_pToPLocalMsgsItemStream == null) { Iterator transmitQueueIterator = validXmits.values().iterator(); ptoPMessageItemStream = (PtoPMessageItemStream) transmitQueueIterator.next(); // depends on control dependency: [if], data = [none] PtoPOutputHandler outputHandler = (PtoPOutputHandler)ptoPMessageItemStream.getOutputHandler(); existingUuid = ptoPMessageItemStream.getLocalizingMEUuid(); // depends on control dependency: [if], data = [none] //Its possible that we dont know the uuid of the localising ME at the other //end of the link, as its in another bus so we rely on TRM to get it for us. //In this case, the UUID constant UNKNOWN_UUID is used. if (newLocalisingMEUuid.toString().equals(SIMPConstants.UNKNOWN_UUID)) { // localisingMe is unknown - dont do anything } else if (existingUuid.equals(newLocalisingMEUuid) || existingUuid.equals(new SIBUuid8(SIMPConstants.UNKNOWN_UUID))) { //The existing localisation has the UNKNOWN_UUID constant, but the //localisation being passed in has a real uuid, so the existing //localisation should be updated to use the real uuid. ptoPMessageItemStream.replaceUuid(newLocalisingMEUuid, msTran); // depends on control dependency: [if], data = [none] //Update the localisation in the hashSets _localisationManager.removeXmitQueuePoint(existingUuid); // depends on control dependency: [if], data = [none] _localisationManager.addXmitQueuePoint( newLocalisingMEUuid, ptoPMessageItemStream); // depends on control dependency: [if], data = [none] outputHandler.updateTargetCellule(newLocalisingMEUuid); // depends on control dependency: [if], data = [none] //Update the outputhandler lookup _localisationManager. updateQueuePointOutputHandler(newLocalisingMEUuid, outputHandler, existingUuid); // depends on control dependency: [if], data = [none] } else { // The localisation of the link has moved. Add in the new localisation // and delete the old one. //Is there an instance of the localisation in deleting state? if (deletingItemStream != null) { deletingItemStream.unmarkAsToBeDeleted(msTran); // depends on control dependency: [if], data = [none] _deletedQueuePoints.remove(newLocalisingMEUuid); // depends on control dependency: [if], data = [none] _localisationManager.addXmitQueuePoint( deletingItemStream.getLocalizingMEUuid(), deletingItemStream); // depends on control dependency: [if], data = [none] assignQueuePointOutputHandler(deletingItemStream.getOutputHandler(), newLocalisingMEUuid); // depends on control dependency: [if], data = [(deletingItemStream] } else { PtoPMessageItemStream newStream = _localisationManager.addNewRemotePtoPLocalization(transaction, newLocalisingMEUuid, null, true, _remoteSupport); ((PtoPOutputHandler)newStream .getOutputHandler()) .updateRoutingCellule(newRoutingMEUuid); // depends on control dependency: [if], data = [none] } // 176658.3.3 transaction.registerCallback( _localisationManager.new LocalizationRemoveTransactionCallback(ptoPMessageItemStream)); // depends on control dependency: [if], data = [none] // Mark the localisation for deletion ptoPMessageItemStream.markAsToBeDeleted(msTran); // depends on control dependency: [if], data = [none] //Remember the deleted localisation incase we need to reincarnate it. //This is a behaviuor reserved for links. Because the other end of the //link is in another bus and wont know if this end of the link is deleted, //it will still be using the stream state associated with this link, //so if at a future point the link is recreated to the same ME, we should //use the same stream state if we can. _deletedQueuePoints.put(existingUuid, ptoPMessageItemStream); // depends on control dependency: [if], data = [none] //Get the background clean-up thread to reallocate the messages and //clean up the localisation if possible. _destinationManager.markDestinationAsCleanUpPending(_baseDestinationHandler); // depends on control dependency: [if], data = [none] // If the old link is localised to this ME then it'll have a proxy // pubsub neighbour setup, so we need to delete that. The easiest way to // check is to see if a neighbour actually exists or not. if(_messageProcessor.getProxyHandler().getNeighbour(existingUuid, true) != null) { try { //Cleanup the neighbours _messageProcessor.getProxyHandler().deleteNeighbourForced(existingUuid, _baseDestinationHandler.getBus() , (Transaction)transaction); // depends on control dependency: [try], data = [none] } catch (Exception e) { // As the neighbours aren't locked down there's a chance of a problem, // but we'll report the error and carry on. // FFDC FFDCFilter.processException(e, "com.ibm.ws.sib.processor.impl.destination.LinkState.updateLocalisationSet", "1:473:1.21", this); if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "Caught exception when deleting neighbour, however this is not always an issue as it might have already been removed: " + e); } // depends on control dependency: [catch], data = [none] } } // Set the new routingCellule. Take into account the sending MEs that do not have // the link localised on their ME if(newRoutingMEUuid != null) { // If link is localised here if (newRoutingMEUuid.equals(_messageProcessor.getMessagingEngineUuid())) newRoutingMEUuid = newLocalisingMEUuid; outputHandler.updateRoutingCellule(newRoutingMEUuid); // depends on control dependency: [if], data = [(newRoutingMEUuid] } } } } // We got through it without failing! rollback = false; // depends on control dependency: [try], data = [none] } finally { //Commit the transaction outside of synchronisation of the linkHandler try { if(rollback) { if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) SibTr.debug(tc, "Update failed, transaction rolling back"); transaction.rollback(); // depends on control dependency: [if], data = [none] } else transaction.commit(); } catch (SIIncorrectCallException e) { // No FFDC code needed if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "updateLocalisationSet", e); throw new SIResourceException(e); } // depends on control dependency: [catch], data = [none] } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "updateLocalisationSet", existingUuid); return existingUuid; } }
public class class_name { public static String getAsString(Object value) { String result = null; if (value == null) { result = ""; } else if (value instanceof Double) { double n = (Double) value; result = n == (long) n ? String.format("%d",(long) n) : String.format("%s", n); } else if (value instanceof Date) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); String date = df.format((Date) value); result = date.substring(0, date.length() - 2) + ":" + date.substring(date.length() - 2, date.length()); } else { result = value.toString(); } return result; } }
public class class_name { public static String getAsString(Object value) { String result = null; if (value == null) { result = ""; // depends on control dependency: [if], data = [none] } else if (value instanceof Double) { double n = (Double) value; result = n == (long) n ? String.format("%d",(long) n) : String.format("%s", n); // depends on control dependency: [if], data = [none] } else if (value instanceof Date) { SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); String date = df.format((Date) value); result = date.substring(0, date.length() - 2) + ":" + date.substring(date.length() - 2, date.length()); // depends on control dependency: [if], data = [none] } else { result = value.toString(); // depends on control dependency: [if], data = [none] } return result; } }
public class class_name { public int getInMemoryDataSize() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "getInMemoryDataSize"); int dataSize; // If tuning has requested return the size of the message we reference, // then delegate to the message. Otherwise call our parent to get a // (small) default size. if (_sizeRefsByMsgSize) { try { dataSize = getReferredItem().getInMemoryDataSize(); } catch (SevereMessageStoreException e) { com.ibm.ws.ffdc.FFDCFilter.processException(e,"com.ibm.ws.sib.msgstore.ItemReference.getInMemoryDataSize","244",this); // After FFDCing anything nasty, fall back to the standard answer dataSize = super.getInMemoryDataSize(); } } else { dataSize = super.getInMemoryDataSize(); } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "getInMemoryDataSize", dataSize); return dataSize; } }
public class class_name { public int getInMemoryDataSize() { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "getInMemoryDataSize"); int dataSize; // If tuning has requested return the size of the message we reference, // then delegate to the message. Otherwise call our parent to get a // (small) default size. if (_sizeRefsByMsgSize) { try { dataSize = getReferredItem().getInMemoryDataSize(); // depends on control dependency: [try], data = [none] } catch (SevereMessageStoreException e) { com.ibm.ws.ffdc.FFDCFilter.processException(e,"com.ibm.ws.sib.msgstore.ItemReference.getInMemoryDataSize","244",this); // After FFDCing anything nasty, fall back to the standard answer dataSize = super.getInMemoryDataSize(); } // depends on control dependency: [catch], data = [none] } else { dataSize = super.getInMemoryDataSize(); // depends on control dependency: [if], data = [none] } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "getInMemoryDataSize", dataSize); return dataSize; } }
public class class_name { public boolean canRewriteHudsonWar() { // if we don't know where jenkins.war is, it's impossible to replace. File f = getHudsonWar(); if (f == null || !f.canWrite()) { return false; } File parent = f.getParentFile(); if (parent == null || !parent.canWrite()) { return false; } return true; } }
public class class_name { public boolean canRewriteHudsonWar() { // if we don't know where jenkins.war is, it's impossible to replace. File f = getHudsonWar(); if (f == null || !f.canWrite()) { return false; // depends on control dependency: [if], data = [none] } File parent = f.getParentFile(); if (parent == null || !parent.canWrite()) { return false; // depends on control dependency: [if], data = [none] } return true; } }
public class class_name { private boolean computeQuery(final ElkClassExpression classExpression, final boolean computeInstanceTaxonomy) throws ElkInconsistentOntologyException, ElkException { // Load the query classExpressionQueryState_.registerQuery(classExpression); ensureLoading(); // Complete all stages if (computeInstanceTaxonomy) { restoreInstanceTaxonomy(); } else { restoreTaxonomy(); } if (!classExpressionQueryState_.isIndexed(classExpression)) { return false; } /* * If query result is cashed, but there were some changes to the * ontology, it may not be up to date. Whether it is is checked during * stages that clean contexts. These are run, if necessary, by the call * above. */ if (classExpressionQueryState_.isComputed(classExpression)) { return true; } stageManager.classExpressionQueryStage.invalidateRecursive(); try { complete(stageManager.classExpressionQueryStage); } catch (final ElkInterruptedException e) { if (classExpressionQueryState_.isComputed(classExpression)) { /* * If the stage was interrupted, but the query is already * computed, completing the stage will not be attempted during * the next call. We need to call postExecute() manually, so * that the stage wouldn't stay initialized with computation * that already processed all its inputs (or at least the * queried class). */ stageManager.classExpressionQueryStage.postExecute(); } else { throw e; } } return true; } }
public class class_name { private boolean computeQuery(final ElkClassExpression classExpression, final boolean computeInstanceTaxonomy) throws ElkInconsistentOntologyException, ElkException { // Load the query classExpressionQueryState_.registerQuery(classExpression); ensureLoading(); // Complete all stages if (computeInstanceTaxonomy) { restoreInstanceTaxonomy(); } else { restoreTaxonomy(); } if (!classExpressionQueryState_.isIndexed(classExpression)) { return false; } /* * If query result is cashed, but there were some changes to the * ontology, it may not be up to date. Whether it is is checked during * stages that clean contexts. These are run, if necessary, by the call * above. */ if (classExpressionQueryState_.isComputed(classExpression)) { return true; } stageManager.classExpressionQueryStage.invalidateRecursive(); try { complete(stageManager.classExpressionQueryStage); } catch (final ElkInterruptedException e) { if (classExpressionQueryState_.isComputed(classExpression)) { /* * If the stage was interrupted, but the query is already * computed, completing the stage will not be attempted during * the next call. We need to call postExecute() manually, so * that the stage wouldn't stay initialized with computation * that already processed all its inputs (or at least the * queried class). */ stageManager.classExpressionQueryStage.postExecute(); // depends on control dependency: [if], data = [none] } else { throw e; } } return true; } }
public class class_name { public ImmutableSet<ClassInfo> getTopLevelClassesRecursive(String packageName) { checkNotNull(packageName); String packagePrefix = packageName + '.'; ImmutableSet.Builder<ClassInfo> builder = ImmutableSet.builder(); for (ClassInfo classInfo : getTopLevelClasses()) { if (classInfo.getName().startsWith(packagePrefix)) { builder.add(classInfo); } } return builder.build(); } }
public class class_name { public ImmutableSet<ClassInfo> getTopLevelClassesRecursive(String packageName) { checkNotNull(packageName); String packagePrefix = packageName + '.'; ImmutableSet.Builder<ClassInfo> builder = ImmutableSet.builder(); for (ClassInfo classInfo : getTopLevelClasses()) { if (classInfo.getName().startsWith(packagePrefix)) { builder.add(classInfo); // depends on control dependency: [if], data = [none] } } return builder.build(); } }
public class class_name { public ConcatVector newWeightsVector(boolean presize) { ConcatVector vector = new ConcatVector(featureToIndex.size()); if (presize) { for (ObjectCursor<String> s : sparseFeatureIndex.keys()) { int size = sparseFeatureIndex.get(s.value).size(); vector.setDenseComponent(ensureFeature(s.value), new double[size]); } } setAlwaysOneFeature(vector, 1); return vector; } }
public class class_name { public ConcatVector newWeightsVector(boolean presize) { ConcatVector vector = new ConcatVector(featureToIndex.size()); if (presize) { for (ObjectCursor<String> s : sparseFeatureIndex.keys()) { int size = sparseFeatureIndex.get(s.value).size(); vector.setDenseComponent(ensureFeature(s.value), new double[size]); // depends on control dependency: [for], data = [s] } } setAlwaysOneFeature(vector, 1); return vector; } }
public class class_name { public void buildProject(File projectRoot) { if (projectRoot == null) { throw new NullPointerException("projectRoot"); } if (mainClass == null) { throw new IllegalArgumentException("No main class specified"); } mainClassName = mainClass.substring(mainClass.lastIndexOf('.') + 1); if (executable == null || executable.length() == 0) { executable = mainClassName; } if (appName == null || appName.length() == 0) { appName = mainClassName; } if (packageName == null || packageName.length() == 0) { int index = mainClass.lastIndexOf('.'); if (index == -1) { packageName = ""; } else { packageName = mainClass.substring(0, index); } } packageDirName = packageName.replace('.', '/'); if (appId == null || appId.length() == 0) { appId = packageName; if (appId == null || appId.length() == 0) { appId = mainClassName; } } try { File targetFile = new File(projectRoot, FilenameUtils.getBaseName(templateURL.getPath())); FileUtils.copyURLToFile(templateURL, targetFile); extractArchive(targetFile, targetFile.getParentFile()); targetFile.delete(); } catch (IOException e) { throw new Error(e); } } }
public class class_name { public void buildProject(File projectRoot) { if (projectRoot == null) { throw new NullPointerException("projectRoot"); } if (mainClass == null) { throw new IllegalArgumentException("No main class specified"); } mainClassName = mainClass.substring(mainClass.lastIndexOf('.') + 1); if (executable == null || executable.length() == 0) { executable = mainClassName; // depends on control dependency: [if], data = [none] } if (appName == null || appName.length() == 0) { appName = mainClassName; // depends on control dependency: [if], data = [none] } if (packageName == null || packageName.length() == 0) { int index = mainClass.lastIndexOf('.'); if (index == -1) { packageName = ""; // depends on control dependency: [if], data = [none] } else { packageName = mainClass.substring(0, index); // depends on control dependency: [if], data = [none] } } packageDirName = packageName.replace('.', '/'); if (appId == null || appId.length() == 0) { appId = packageName; // depends on control dependency: [if], data = [none] if (appId == null || appId.length() == 0) { appId = mainClassName; // depends on control dependency: [if], data = [none] } } try { File targetFile = new File(projectRoot, FilenameUtils.getBaseName(templateURL.getPath())); FileUtils.copyURLToFile(templateURL, targetFile); // depends on control dependency: [try], data = [none] extractArchive(targetFile, targetFile.getParentFile()); // depends on control dependency: [try], data = [none] targetFile.delete(); // depends on control dependency: [try], data = [none] } catch (IOException e) { throw new Error(e); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public final void addRow(final Integer sourceRowNum, final Row targetRow) { List<SerialRow> mapRowList = rowsMap.get(sourceRowNum); if (mapRowList == null) { mapRowList = new ArrayList<>(); } SerialRow serialTarget = new SerialRow(targetRow, -1); if (!mapRowList.contains(serialTarget)) { mapRowList.add(serialTarget); rowsMap.put(sourceRowNum, mapRowList); } } }
public class class_name { public final void addRow(final Integer sourceRowNum, final Row targetRow) { List<SerialRow> mapRowList = rowsMap.get(sourceRowNum); if (mapRowList == null) { mapRowList = new ArrayList<>(); // depends on control dependency: [if], data = [none] } SerialRow serialTarget = new SerialRow(targetRow, -1); if (!mapRowList.contains(serialTarget)) { mapRowList.add(serialTarget); // depends on control dependency: [if], data = [none] rowsMap.put(sourceRowNum, mapRowList); // depends on control dependency: [if], data = [none] } } }
public class class_name { public EClass getIfcStyledItem() { if (ifcStyledItemEClass == null) { ifcStyledItemEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(570); } return ifcStyledItemEClass; } }
public class class_name { public EClass getIfcStyledItem() { if (ifcStyledItemEClass == null) { ifcStyledItemEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI) .getEClassifiers().get(570); // depends on control dependency: [if], data = [none] } return ifcStyledItemEClass; } }
public class class_name { public List<Float> getFloats(String name, String delimiter) { List<String> strings = getStrings(name, delimiter); List<Float> floats = new ArrayList<>(strings.size()); for (String value : strings) { try { float i = Float.parseFloat(value); floats.add(i); } catch (NumberFormatException e) { } } return Collections.unmodifiableList(floats); } }
public class class_name { public List<Float> getFloats(String name, String delimiter) { List<String> strings = getStrings(name, delimiter); List<Float> floats = new ArrayList<>(strings.size()); for (String value : strings) { try { float i = Float.parseFloat(value); floats.add(i); // depends on control dependency: [try], data = [none] } catch (NumberFormatException e) { } // depends on control dependency: [catch], data = [none] } return Collections.unmodifiableList(floats); } }
public class class_name { public ValueSet readTemplatesByRange(int index, int length) { Result result = htod.readTemplatesByRange(index, length); if (result.returnCode == HTODDynacache.DISK_EXCEPTION) { stopOnError(result.diskException); this.htod.returnToResultPool(result); return HTODDynacache.EMPTY_VS; } ValueSet valueSet = (ValueSet) result.data; if (valueSet == null) { valueSet = HTODDynacache.EMPTY_VS; } this.htod.returnToResultPool(result); return valueSet; } }
public class class_name { public ValueSet readTemplatesByRange(int index, int length) { Result result = htod.readTemplatesByRange(index, length); if (result.returnCode == HTODDynacache.DISK_EXCEPTION) { stopOnError(result.diskException); // depends on control dependency: [if], data = [none] this.htod.returnToResultPool(result); // depends on control dependency: [if], data = [none] return HTODDynacache.EMPTY_VS; // depends on control dependency: [if], data = [none] } ValueSet valueSet = (ValueSet) result.data; if (valueSet == null) { valueSet = HTODDynacache.EMPTY_VS; // depends on control dependency: [if], data = [none] } this.htod.returnToResultPool(result); return valueSet; } }
public class class_name { public static int lastIndexOfAny(String str, String[] searchStrs) { if ((str == null) || (searchStrs == null)) { return -1; } int sz = searchStrs.length; int ret = -1; int tmp = 0; for (int i = 0; i < sz; i++) { String search = searchStrs[i]; if (search == null) { continue; } tmp = str.lastIndexOf(search); if (tmp > ret) { ret = tmp; } } return ret; } }
public class class_name { public static int lastIndexOfAny(String str, String[] searchStrs) { if ((str == null) || (searchStrs == null)) { return -1; // depends on control dependency: [if], data = [none] } int sz = searchStrs.length; int ret = -1; int tmp = 0; for (int i = 0; i < sz; i++) { String search = searchStrs[i]; if (search == null) { continue; } tmp = str.lastIndexOf(search); // depends on control dependency: [for], data = [none] if (tmp > ret) { ret = tmp; // depends on control dependency: [if], data = [none] } } return ret; } }
public class class_name { private void setOpBend() throws Exception { List data = new Vector(); st.nextToken(); String sid1 = st.nextToken(); String sid2 = st.nextToken(); String value1 = st.nextToken(); try { double va1 = new Double(value1).doubleValue(); data.add(new Double(va1)); key = "opbend" + sid1 + ";" + sid2; if (parameterSet.containsKey(key)) { //logger.debug("KeyError: hasKey "+key); data = (Vector) parameterSet.get(key); data.add(new Double(va1)); } parameterSet.put(key, data); } catch (NumberFormatException nfe) { throw new IOException("setOpBend: Malformed Number"); } } }
public class class_name { private void setOpBend() throws Exception { List data = new Vector(); st.nextToken(); String sid1 = st.nextToken(); String sid2 = st.nextToken(); String value1 = st.nextToken(); try { double va1 = new Double(value1).doubleValue(); data.add(new Double(va1)); key = "opbend" + sid1 + ";" + sid2; if (parameterSet.containsKey(key)) { //logger.debug("KeyError: hasKey "+key); data = (Vector) parameterSet.get(key); // depends on control dependency: [if], data = [none] data.add(new Double(va1)); // depends on control dependency: [if], data = [none] } parameterSet.put(key, data); } catch (NumberFormatException nfe) { throw new IOException("setOpBend: Malformed Number"); } } }