code
stringlengths
130
281k
code_dependency
stringlengths
182
306k
public class class_name { public void notifyNewMessage(Plugin plugin) { if (plugin == null) { throw new IllegalArgumentException("Parameter plugin must not be null."); } PluginStats pluginStats = mapPluginStats.get(plugin.getId()); if (pluginStats != null) { pluginStats.incMessageCount(); } } }
public class class_name { public void notifyNewMessage(Plugin plugin) { if (plugin == null) { throw new IllegalArgumentException("Parameter plugin must not be null."); } PluginStats pluginStats = mapPluginStats.get(plugin.getId()); if (pluginStats != null) { pluginStats.incMessageCount(); // depends on control dependency: [if], data = [none] } } }
public class class_name { private String escapeAndJoin(String[] commandline) { // TODO: we should try to escape special characters here, depending on the OS. StringBuilder b = new StringBuilder(); Pattern specials = Pattern.compile("[\\ ]"); for (String arg : commandline) { if (b.length() > 0) { b.append(" "); } if (specials.matcher(arg).find()) { b.append('"').append(arg).append('"'); } else { b.append(arg); } } return b.toString(); } }
public class class_name { private String escapeAndJoin(String[] commandline) { // TODO: we should try to escape special characters here, depending on the OS. StringBuilder b = new StringBuilder(); Pattern specials = Pattern.compile("[\\ ]"); for (String arg : commandline) { if (b.length() > 0) { b.append(" "); // depends on control dependency: [if], data = [none] } if (specials.matcher(arg).find()) { b.append('"').append(arg).append('"'); // depends on control dependency: [if], data = [none] } else { b.append(arg); // depends on control dependency: [if], data = [none] } } return b.toString(); } }
public class class_name { @Override public Number readNumber() { if (buf.hasRemaining()) { int remaining = buf.remaining(); if (log.isTraceEnabled()) { log.trace("Remaining bytes for Number: {}", remaining); } Number v; if (currentDataType == AMF3.TYPE_NUMBER) { // prevent buffer underrun if we dont have 8 bytes for the expected double if (remaining >= 8) { v = buf.getDouble(); } else { v = buf.getInt(); } } else { // we are decoding an int v = readInteger(); } if (log.isTraceEnabled()) { log.trace("readNumber - value: {}", v); } return v; } else { log.warn("No remaining bytes for buffer readNumber"); } return null; } }
public class class_name { @Override public Number readNumber() { if (buf.hasRemaining()) { int remaining = buf.remaining(); if (log.isTraceEnabled()) { log.trace("Remaining bytes for Number: {}", remaining); // depends on control dependency: [if], data = [none] } Number v; if (currentDataType == AMF3.TYPE_NUMBER) { // prevent buffer underrun if we dont have 8 bytes for the expected double if (remaining >= 8) { v = buf.getDouble(); // depends on control dependency: [if], data = [none] } else { v = buf.getInt(); // depends on control dependency: [if], data = [none] } } else { // we are decoding an int v = readInteger(); // depends on control dependency: [if], data = [none] } if (log.isTraceEnabled()) { log.trace("readNumber - value: {}", v); // depends on control dependency: [if], data = [none] } return v; // depends on control dependency: [if], data = [none] } else { log.warn("No remaining bytes for buffer readNumber"); // depends on control dependency: [if], data = [none] } return null; } }
public class class_name { public String getScriptUsage() { StringBuffer scriptUsage = new StringBuffer(NL); scriptUsage.append(getMessage("usage", scriptName)); scriptUsage.append(" {"); for (int i = 0; i < tasks.size(); i++) { SecurityUtilityTask task = tasks.get(i); scriptUsage.append(task.getTaskName()); if (i != (tasks.size() - 1)) { scriptUsage.append("|"); } } scriptUsage.append("} [options]"); scriptUsage.append(NL); return scriptUsage.toString(); } }
public class class_name { public String getScriptUsage() { StringBuffer scriptUsage = new StringBuffer(NL); scriptUsage.append(getMessage("usage", scriptName)); scriptUsage.append(" {"); for (int i = 0; i < tasks.size(); i++) { SecurityUtilityTask task = tasks.get(i); scriptUsage.append(task.getTaskName()); // depends on control dependency: [for], data = [none] if (i != (tasks.size() - 1)) { scriptUsage.append("|"); // depends on control dependency: [if], data = [none] } } scriptUsage.append("} [options]"); scriptUsage.append(NL); return scriptUsage.toString(); } }
public class class_name { public static Collection<? extends PersistenceUnitInfo> parse(URL persistenceXml) { InputStream is = null; try { // Buffer the InputStream so we can mark it, though we'll be in // trouble if we have to read more than 8192 characters before finding // the schema! is = new BufferedInputStream(persistenceXml.openStream()); JPAVersion jpaVersion = getSchemaVersion(is); Schema schema = getSchema(jpaVersion); if (schema == null) { throw new PersistenceException("Schema is unknown"); } // Get back to the beginning of the stream is = new BufferedInputStream(persistenceXml.openStream()); parserFactory.setNamespaceAware(true); int endIndex = persistenceXml.getPath().length() - PERSISTENCE_XML_BASE_NAME.length(); URL persistenceXmlRoot = new URL("file://" + persistenceXml.getFile().substring(0, endIndex)); return getPersistenceUnits(is, persistenceXmlRoot, jpaVersion); } catch (Exception e) { throw new PersistenceException("Something goes wrong while parsing persistence.xml", e); } finally { if (is != null) try { is.close(); } catch (IOException e) { // No logging necessary, just consume } } } }
public class class_name { public static Collection<? extends PersistenceUnitInfo> parse(URL persistenceXml) { InputStream is = null; try { // Buffer the InputStream so we can mark it, though we'll be in // trouble if we have to read more than 8192 characters before finding // the schema! is = new BufferedInputStream(persistenceXml.openStream()); // depends on control dependency: [try], data = [none] JPAVersion jpaVersion = getSchemaVersion(is); Schema schema = getSchema(jpaVersion); if (schema == null) { throw new PersistenceException("Schema is unknown"); } // Get back to the beginning of the stream is = new BufferedInputStream(persistenceXml.openStream()); // depends on control dependency: [try], data = [none] parserFactory.setNamespaceAware(true); // depends on control dependency: [try], data = [none] int endIndex = persistenceXml.getPath().length() - PERSISTENCE_XML_BASE_NAME.length(); URL persistenceXmlRoot = new URL("file://" + persistenceXml.getFile().substring(0, endIndex)); return getPersistenceUnits(is, persistenceXmlRoot, jpaVersion); } catch (Exception e) { throw new PersistenceException("Something goes wrong while parsing persistence.xml", e); } finally { // depends on control dependency: [catch], data = [none] if (is != null) try { is.close(); // depends on control dependency: [try], data = [none] } catch (IOException e) { // No logging necessary, just consume } // depends on control dependency: [catch], data = [none] } } }
public class class_name { public ValueIOChannel getApplicableChannel(PropertyData property, int valueOrderNumer) throws IOException { Iterator<ValueStoragePlugin> plugins = iterator(); while (plugins.hasNext()) { ValueStoragePlugin plugin = plugins.next(); List<ValuePluginFilter> filters = plugin.getFilters(); for (ValuePluginFilter filter : filters) { if (filter.match(property, valueOrderNumer)) { return plugin.openIOChannel(); } } } return null; } }
public class class_name { public ValueIOChannel getApplicableChannel(PropertyData property, int valueOrderNumer) throws IOException { Iterator<ValueStoragePlugin> plugins = iterator(); while (plugins.hasNext()) { ValueStoragePlugin plugin = plugins.next(); List<ValuePluginFilter> filters = plugin.getFilters(); for (ValuePluginFilter filter : filters) { if (filter.match(property, valueOrderNumer)) { return plugin.openIOChannel(); // depends on control dependency: [if], data = [none] } } } return null; } }
public class class_name { public int getChunkId(byte[] key) { int idx = Arrays.binarySearch(maxKeyPerChunk, 0, filledUpTo + 1, key, comparator); idx = idx < 0 ? -idx - 1 : idx; if (idx > filledUpTo) { return -1; } else { return idx; } } }
public class class_name { public int getChunkId(byte[] key) { int idx = Arrays.binarySearch(maxKeyPerChunk, 0, filledUpTo + 1, key, comparator); idx = idx < 0 ? -idx - 1 : idx; if (idx > filledUpTo) { return -1; // depends on control dependency: [if], data = [none] } else { return idx; // depends on control dependency: [if], data = [none] } } }
public class class_name { public Deferred<Boolean> syncToStorage(final TSDB tsdb, final Boolean overwrite) { if (start_time < 1) { throw new IllegalArgumentException("The start timestamp has not been set"); } boolean has_changes = false; for (Map.Entry<String, Boolean> entry : changed.entrySet()) { if (entry.getValue()) { has_changes = true; break; } } if (!has_changes) { LOG.debug(this + " does not have changes, skipping sync to storage"); throw new IllegalStateException("No changes detected in Annotation data"); } final class StoreCB implements Callback<Deferred<Boolean>, Annotation> { @Override public Deferred<Boolean> call(final Annotation stored_note) throws Exception { final byte[] original_note = stored_note == null ? new byte[0] : stored_note.getStorageJSON(); if (stored_note != null) { Annotation.this.syncNote(stored_note, overwrite); } final byte[] tsuid_byte = tsuid != null && !tsuid.isEmpty() ? UniqueId.stringToUid(tsuid) : null; final PutRequest put = RequestBuilder.buildPutRequest(tsdb.getConfig(), tsdb.dataTable(), getRowKey(start_time, tsuid_byte), FAMILY, getQualifier(start_time), Annotation.this.getStorageJSON(), start_time); return tsdb.getClient().compareAndSet(put, original_note); } } if (tsuid != null && !tsuid.isEmpty()) { return getAnnotation(tsdb, UniqueId.stringToUid(tsuid), start_time) .addCallbackDeferring(new StoreCB()); } return getAnnotation(tsdb, start_time).addCallbackDeferring(new StoreCB()); } }
public class class_name { public Deferred<Boolean> syncToStorage(final TSDB tsdb, final Boolean overwrite) { if (start_time < 1) { throw new IllegalArgumentException("The start timestamp has not been set"); } boolean has_changes = false; for (Map.Entry<String, Boolean> entry : changed.entrySet()) { if (entry.getValue()) { has_changes = true; // depends on control dependency: [if], data = [none] break; } } if (!has_changes) { LOG.debug(this + " does not have changes, skipping sync to storage"); // depends on control dependency: [if], data = [none] throw new IllegalStateException("No changes detected in Annotation data"); } final class StoreCB implements Callback<Deferred<Boolean>, Annotation> { @Override public Deferred<Boolean> call(final Annotation stored_note) throws Exception { final byte[] original_note = stored_note == null ? new byte[0] : stored_note.getStorageJSON(); if (stored_note != null) { Annotation.this.syncNote(stored_note, overwrite); } final byte[] tsuid_byte = tsuid != null && !tsuid.isEmpty() ? UniqueId.stringToUid(tsuid) : null; final PutRequest put = RequestBuilder.buildPutRequest(tsdb.getConfig(), tsdb.dataTable(), getRowKey(start_time, tsuid_byte), FAMILY, getQualifier(start_time), Annotation.this.getStorageJSON(), start_time); return tsdb.getClient().compareAndSet(put, original_note); } } if (tsuid != null && !tsuid.isEmpty()) { return getAnnotation(tsdb, UniqueId.stringToUid(tsuid), start_time) .addCallbackDeferring(new StoreCB()); } return getAnnotation(tsdb, start_time).addCallbackDeferring(new StoreCB()); } }
public class class_name { public String performTask(String taskParameters) { EnableStreamingTaskParameters taskParams = EnableStreamingTaskParameters.deserialize(taskParameters); String spaceId = taskParams.getSpaceId(); boolean secure = taskParams.isSecure(); log.info("Performing " + TASK_NAME + " task on space " + spaceId + ". Secure streaming set to " + secure); // Will throw if bucket does not exist String bucketName = unwrappedS3Provider.getBucketName(spaceId); String domainName = null; String distId = null; String oaIdentityId = getOriginAccessId(); EnableStreamingTaskResult taskResult = new EnableStreamingTaskResult(); StreamingDistributionSummary existingDist = getExistingDistribution(bucketName); if (existingDist != null) { // There is an existing distribution // Ensure that this is not an attempt to change the security type // of this existing distribution boolean existingSecure = !existingDist.getTrustedSigners().getItems().isEmpty(); if ((secure && !existingSecure) || (!secure && existingSecure)) { throw new UnsupportedTaskException(TASK_NAME, "The space " + spaceId + " is already configured to stream as " + (secure ? "OPEN" : "SECURE") + " and cannot be updated to stream as " + (secure ? "SECURE" : "OPEN") + ". To do this, you must first execute the " + StorageTaskConstants.DELETE_STREAMING_TASK_NAME + " task."); } distId = existingDist.getId(); if (!existingDist.isEnabled()) { // Distribution is disabled, enable it setDistributionState(distId, true); } domainName = existingDist.getDomainName(); } else { // No existing distribution, need to create one S3Origin origin = new S3Origin(bucketName + S3_ORIGIN_SUFFIX, S3_ORIGIN_OAI_PREFIX + oaIdentityId); // Only include trusted signers on secure distributions TrustedSigners signers = new TrustedSigners(); if (secure) { signers.setItems(Collections.singletonList(cfAccountId)); signers.setEnabled(true); signers.setQuantity(1); } else { signers.setEnabled(false); signers.setQuantity(0); } StreamingDistribution dist = cfClient.createStreamingDistribution( new CreateStreamingDistributionRequest( new StreamingDistributionConfig() .withCallerReference("" + System.currentTimeMillis()) .withS3Origin(origin) .withEnabled(true) .withComment("Streaming space: " + spaceId) .withTrustedSigners(signers))) .getStreamingDistribution(); domainName = dist.getDomainName(); } // Set bucket policy to accept origin access identity setBucketAccessPolicy(bucketName, oaIdentityId); // Update bucket tags to include streaming host Map<String, String> spaceProps = s3Provider.getSpaceProperties(spaceId); spaceProps.put(STREAMING_HOST_PROP, domainName); spaceProps.put(STREAMING_TYPE_PROP, secure ? STREAMING_TYPE.SECURE.name() : STREAMING_TYPE.OPEN.name()); unwrappedS3Provider.setNewSpaceProperties(spaceId, spaceProps); taskResult.setResult("Enable Streaming Task completed successfully"); // Return results taskResult.setStreamingHost(domainName); String toReturn = taskResult.serialize(); log.info("Result of " + TASK_NAME + " task: " + toReturn); return toReturn; } }
public class class_name { public String performTask(String taskParameters) { EnableStreamingTaskParameters taskParams = EnableStreamingTaskParameters.deserialize(taskParameters); String spaceId = taskParams.getSpaceId(); boolean secure = taskParams.isSecure(); log.info("Performing " + TASK_NAME + " task on space " + spaceId + ". Secure streaming set to " + secure); // Will throw if bucket does not exist String bucketName = unwrappedS3Provider.getBucketName(spaceId); String domainName = null; String distId = null; String oaIdentityId = getOriginAccessId(); EnableStreamingTaskResult taskResult = new EnableStreamingTaskResult(); StreamingDistributionSummary existingDist = getExistingDistribution(bucketName); if (existingDist != null) { // There is an existing distribution // Ensure that this is not an attempt to change the security type // of this existing distribution boolean existingSecure = !existingDist.getTrustedSigners().getItems().isEmpty(); if ((secure && !existingSecure) || (!secure && existingSecure)) { throw new UnsupportedTaskException(TASK_NAME, "The space " + spaceId + " is already configured to stream as " + (secure ? "OPEN" : "SECURE") + " and cannot be updated to stream as " + (secure ? "SECURE" : "OPEN") + ". To do this, you must first execute the " + StorageTaskConstants.DELETE_STREAMING_TASK_NAME + " task."); } distId = existingDist.getId(); // depends on control dependency: [if], data = [none] if (!existingDist.isEnabled()) { // Distribution is disabled, enable it setDistributionState(distId, true); // depends on control dependency: [if], data = [none] } domainName = existingDist.getDomainName(); // depends on control dependency: [if], data = [none] } else { // No existing distribution, need to create one S3Origin origin = new S3Origin(bucketName + S3_ORIGIN_SUFFIX, S3_ORIGIN_OAI_PREFIX + oaIdentityId); // Only include trusted signers on secure distributions TrustedSigners signers = new TrustedSigners(); if (secure) { signers.setItems(Collections.singletonList(cfAccountId)); // depends on control dependency: [if], data = [none] signers.setEnabled(true); // depends on control dependency: [if], data = [none] signers.setQuantity(1); // depends on control dependency: [if], data = [none] } else { signers.setEnabled(false); // depends on control dependency: [if], data = [none] signers.setQuantity(0); // depends on control dependency: [if], data = [none] } StreamingDistribution dist = cfClient.createStreamingDistribution( new CreateStreamingDistributionRequest( new StreamingDistributionConfig() .withCallerReference("" + System.currentTimeMillis()) .withS3Origin(origin) .withEnabled(true) .withComment("Streaming space: " + spaceId) .withTrustedSigners(signers))) .getStreamingDistribution(); domainName = dist.getDomainName(); // depends on control dependency: [if], data = [none] } // Set bucket policy to accept origin access identity setBucketAccessPolicy(bucketName, oaIdentityId); // Update bucket tags to include streaming host Map<String, String> spaceProps = s3Provider.getSpaceProperties(spaceId); spaceProps.put(STREAMING_HOST_PROP, domainName); spaceProps.put(STREAMING_TYPE_PROP, secure ? STREAMING_TYPE.SECURE.name() : STREAMING_TYPE.OPEN.name()); unwrappedS3Provider.setNewSpaceProperties(spaceId, spaceProps); taskResult.setResult("Enable Streaming Task completed successfully"); // Return results taskResult.setStreamingHost(domainName); String toReturn = taskResult.serialize(); log.info("Result of " + TASK_NAME + " task: " + toReturn); return toReturn; } }
public class class_name { @Override public String getMethodNameForReference(final ForeignKey foreignKey) { final Column c = foreignKey.getColumnReferences().get(0).getForeignKeyColumn(); // check if only one-column fk if (foreignKey.getColumnReferences().size() == 1) { return getMethodNameForColumn(c) + getClassNameForTable(c.getReferencedColumn().getParent()); } final StringBuilder nameBuilder = new StringBuilder(); final List<String> words = new ArrayList<>(Arrays.asList(foreignKey.getName() .toLowerCase() .replaceAll("(^[0-9]+|[^a-z0-9_-])", "") // Delete every not-alphanumeric or _/- character and numbers at beginning .split("_"))); words.removeAll(Arrays.asList("fk", "", null)); // removes FK_ prefix and empty entries final List<String> tableWords = new ArrayList<>(Arrays.asList(c.getParent().getName() .toLowerCase() .replaceAll("(^[0-9]+|[^a-z0-9_-])", "") // Delete every not-alphanumeric or _/- character and numbers at beginning .split("_"))); words.removeAll(tableWords); nameBuilder.append(words.get(0)); for (int i = 1; i < words.size(); i++) { String word = words.get(i); nameBuilder.append(word.substring(0, 1).toUpperCase()); nameBuilder.append(word.substring(1)); } return nameBuilder.toString(); } }
public class class_name { @Override public String getMethodNameForReference(final ForeignKey foreignKey) { final Column c = foreignKey.getColumnReferences().get(0).getForeignKeyColumn(); // check if only one-column fk if (foreignKey.getColumnReferences().size() == 1) { return getMethodNameForColumn(c) + getClassNameForTable(c.getReferencedColumn().getParent()); // depends on control dependency: [if], data = [none] } final StringBuilder nameBuilder = new StringBuilder(); final List<String> words = new ArrayList<>(Arrays.asList(foreignKey.getName() .toLowerCase() .replaceAll("(^[0-9]+|[^a-z0-9_-])", "") // Delete every not-alphanumeric or _/- character and numbers at beginning .split("_"))); words.removeAll(Arrays.asList("fk", "", null)); // removes FK_ prefix and empty entries final List<String> tableWords = new ArrayList<>(Arrays.asList(c.getParent().getName() .toLowerCase() .replaceAll("(^[0-9]+|[^a-z0-9_-])", "") // Delete every not-alphanumeric or _/- character and numbers at beginning .split("_"))); words.removeAll(tableWords); nameBuilder.append(words.get(0)); for (int i = 1; i < words.size(); i++) { String word = words.get(i); nameBuilder.append(word.substring(0, 1).toUpperCase()); // depends on control dependency: [for], data = [none] nameBuilder.append(word.substring(1)); // depends on control dependency: [for], data = [none] } return nameBuilder.toString(); } }
public class class_name { public static Deferred<Map<String, String>> getTagsAsync(final TSDB tsdb, final ByteMap<byte[]> tags) { if (tags == null || tags.isEmpty()) { return Deferred.fromResult(Collections.<String, String>emptyMap()); } final ArrayList<Deferred<String>> deferreds = new ArrayList<Deferred<String>>(); for (final Map.Entry<byte[], byte[]> pair : tags) { deferreds.add(tsdb.tag_names.getNameAsync(pair.getKey())); deferreds.add(tsdb.tag_values.getNameAsync(pair.getValue())); } class NameCB implements Callback<Map<String, String>, ArrayList<String>> { public Map<String, String> call(final ArrayList<String> names) throws Exception { final HashMap<String, String> result = new HashMap<String, String>(); String tagk = ""; for (String name : names) { if (tagk.isEmpty()) { tagk = name; } else { result.put(tagk, name); tagk = ""; } } return result; } } return Deferred.groupInOrder(deferreds).addCallback(new NameCB()); } }
public class class_name { public static Deferred<Map<String, String>> getTagsAsync(final TSDB tsdb, final ByteMap<byte[]> tags) { if (tags == null || tags.isEmpty()) { return Deferred.fromResult(Collections.<String, String>emptyMap()); // depends on control dependency: [if], data = [none] } final ArrayList<Deferred<String>> deferreds = new ArrayList<Deferred<String>>(); for (final Map.Entry<byte[], byte[]> pair : tags) { deferreds.add(tsdb.tag_names.getNameAsync(pair.getKey())); // depends on control dependency: [for], data = [pair] deferreds.add(tsdb.tag_values.getNameAsync(pair.getValue())); // depends on control dependency: [for], data = [pair] } class NameCB implements Callback<Map<String, String>, ArrayList<String>> { public Map<String, String> call(final ArrayList<String> names) throws Exception { final HashMap<String, String> result = new HashMap<String, String>(); String tagk = ""; for (String name : names) { if (tagk.isEmpty()) { tagk = name; // depends on control dependency: [if], data = [none] } else { result.put(tagk, name); // depends on control dependency: [if], data = [none] tagk = ""; // depends on control dependency: [if], data = [none] } } return result; } } return Deferred.groupInOrder(deferreds).addCallback(new NameCB()); } }
public class class_name { @Override public void onEvent(EventIterator events) { try { // this resolver should be the only one (for this handling thread) ResourceResolver resolver = getResolver(); if (resolver != null) { try { Session session = resolver.adaptTo(Session.class); String serviceUserId = getServiceUserId(); // collect changed nodes ChangeCollection changedNodes = new ChangeCollection(); while (events.hasNext()) { Event event = events.nextEvent(); if (ignoreEvent(event)) continue; try { String path = event.getPath(); String user = event.getUserID(); // if the service user is the initiator this is a self initiated event - ignore it if (!serviceUserId.equals(user)) { Calendar time = Calendar.getInstance(); time.setTime(new Date(event.getDate())); int type = event.getType(); if (isPropertyEvent(type)) { if (getPropertyPathFilter().accept(path)) { changedNodes.registerChange(session, resolver, path, time, user); } } else { if (getNodePathFilter().accept(path)) { changedNodes.registerChange(session, resolver, path, time, user); } } } } catch (RepositoryException rex) { LOG.error(rex.getMessage(), rex); } } // handle change actions on the detected nodes if (changedNodes.size() > 0) { for (ChangedResource change : changedNodes.values()) { try { doOnChange(resolver, change); } catch (RepositoryException ex) { LOG.error(ex.getMessage(), ex); } } changedNodes.clear(); resolver.commit(); } } catch (PersistenceException ex) { LOG.error(ex.getMessage(), ex); } finally { resolver.close(); } } } catch (LoginException ex) { LOG.error(ex.getMessage(), ex); } } }
public class class_name { @Override public void onEvent(EventIterator events) { try { // this resolver should be the only one (for this handling thread) ResourceResolver resolver = getResolver(); if (resolver != null) { try { Session session = resolver.adaptTo(Session.class); String serviceUserId = getServiceUserId(); // collect changed nodes ChangeCollection changedNodes = new ChangeCollection(); while (events.hasNext()) { Event event = events.nextEvent(); if (ignoreEvent(event)) continue; try { String path = event.getPath(); String user = event.getUserID(); // if the service user is the initiator this is a self initiated event - ignore it if (!serviceUserId.equals(user)) { Calendar time = Calendar.getInstance(); time.setTime(new Date(event.getDate())); // depends on control dependency: [if], data = [none] int type = event.getType(); if (isPropertyEvent(type)) { if (getPropertyPathFilter().accept(path)) { changedNodes.registerChange(session, resolver, path, time, user); // depends on control dependency: [if], data = [none] } } else { if (getNodePathFilter().accept(path)) { changedNodes.registerChange(session, resolver, path, time, user); // depends on control dependency: [if], data = [none] } } } } catch (RepositoryException rex) { LOG.error(rex.getMessage(), rex); } // depends on control dependency: [catch], data = [none] } // handle change actions on the detected nodes if (changedNodes.size() > 0) { for (ChangedResource change : changedNodes.values()) { try { doOnChange(resolver, change); // depends on control dependency: [try], data = [none] } catch (RepositoryException ex) { LOG.error(ex.getMessage(), ex); } // depends on control dependency: [catch], data = [none] } changedNodes.clear(); // depends on control dependency: [if], data = [none] resolver.commit(); // depends on control dependency: [if], data = [none] } } catch (PersistenceException ex) { LOG.error(ex.getMessage(), ex); } finally { // depends on control dependency: [catch], data = [none] resolver.close(); } } } catch (LoginException ex) { LOG.error(ex.getMessage(), ex); } // depends on control dependency: [catch], data = [none] } }
public class class_name { public static void printMiddleResults(ArrayList<ArrayList<TextPiece>> wordsByPage, ArrayList<ArrayList<TextPiece>> linesByPage, String outputDirPath, File pdfFile) { try { /** * Creates the middle-result directory if it does not exist */ File middleDir = new File(outputDirPath, "middleResults-Seersuite"); //"middleResults-Seersuite" if (!middleDir.exists()) { middleDir.mkdirs(); } /** * Generates the names with the directory path of files to store the middle-stage results */ File pieceResultFile = new File(middleDir, pdfFile.getName() + ".piece"); File lineResultFile = new File(middleDir, pdfFile.getName() + ".line"); BufferedWriter bw0 = new BufferedWriter(new FileWriter(pieceResultFile)); BufferedWriter bw = new BufferedWriter(new FileWriter(lineResultFile)); /** * Loops over PDF document pages. */ for (int i = 0; i < linesByPage.size(); i++) { bw0.write("************ PAGE " + i + "***************\n"); bw.write("************ PAGE " + i + "***************\n"); ArrayList<TextPiece> wordsOfAPage = wordsByPage.get(i); ArrayList<TextPiece> linesOfAPage = linesByPage.get(i); /** * Loops over text pieces within a page */ for (int j = 0; j < wordsOfAPage.size(); j++) { TextPiece word = wordsOfAPage.get(j); String wordStr = String.format("WORD %d %s\n", j, word.toString()); bw0.write(wordStr); } /** * Loops over lines within a page */ for (int j = 0; j < linesOfAPage.size(); j++) { TextPiece line = linesOfAPage.get(j); String lineStr = String.format( "LINE %d %s\n", j, line.toString()); bw.write(lineStr); } bw0.write("\n"); bw.write("\n"); } bw0.close(); bw.close(); } catch (IOException e){ System.out.printf("[Debug Error] IOException\n"); } } }
public class class_name { public static void printMiddleResults(ArrayList<ArrayList<TextPiece>> wordsByPage, ArrayList<ArrayList<TextPiece>> linesByPage, String outputDirPath, File pdfFile) { try { /** * Creates the middle-result directory if it does not exist */ File middleDir = new File(outputDirPath, "middleResults-Seersuite"); //"middleResults-Seersuite" if (!middleDir.exists()) { middleDir.mkdirs(); // depends on control dependency: [if], data = [none] } /** * Generates the names with the directory path of files to store the middle-stage results */ File pieceResultFile = new File(middleDir, pdfFile.getName() + ".piece"); File lineResultFile = new File(middleDir, pdfFile.getName() + ".line"); BufferedWriter bw0 = new BufferedWriter(new FileWriter(pieceResultFile)); BufferedWriter bw = new BufferedWriter(new FileWriter(lineResultFile)); /** * Loops over PDF document pages. */ for (int i = 0; i < linesByPage.size(); i++) { bw0.write("************ PAGE " + i + "***************\n"); // depends on control dependency: [for], data = [i] bw.write("************ PAGE " + i + "***************\n"); // depends on control dependency: [for], data = [i] ArrayList<TextPiece> wordsOfAPage = wordsByPage.get(i); ArrayList<TextPiece> linesOfAPage = linesByPage.get(i); /** * Loops over text pieces within a page */ for (int j = 0; j < wordsOfAPage.size(); j++) { TextPiece word = wordsOfAPage.get(j); String wordStr = String.format("WORD %d %s\n", j, word.toString()); bw0.write(wordStr); // depends on control dependency: [for], data = [none] } /** * Loops over lines within a page */ for (int j = 0; j < linesOfAPage.size(); j++) { TextPiece line = linesOfAPage.get(j); String lineStr = String.format( "LINE %d %s\n", j, line.toString()); bw.write(lineStr); // depends on control dependency: [for], data = [none] } bw0.write("\n"); // depends on control dependency: [for], data = [none] bw.write("\n"); // depends on control dependency: [for], data = [none] } bw0.close(); // depends on control dependency: [try], data = [none] bw.close(); // depends on control dependency: [try], data = [none] } catch (IOException e){ System.out.printf("[Debug Error] IOException\n"); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private JButton getBtnCancel() { if (btnCancel == null) { btnCancel = new JButton(); btnCancel.setText(Constant.messages.getString("all.button.cancel")); btnCancel.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { getTxtPattern().discardAllEdits(); FilterReplaceDialog.this.dispose(); exitCode = JOptionPane.CANCEL_OPTION; } }); } return btnCancel; } }
public class class_name { private JButton getBtnCancel() { if (btnCancel == null) { btnCancel = new JButton(); // depends on control dependency: [if], data = [none] btnCancel.setText(Constant.messages.getString("all.button.cancel")); // depends on control dependency: [if], data = [none] btnCancel.addActionListener(new java.awt.event.ActionListener() { @Override public void actionPerformed(java.awt.event.ActionEvent e) { getTxtPattern().discardAllEdits(); FilterReplaceDialog.this.dispose(); exitCode = JOptionPane.CANCEL_OPTION; } }); // depends on control dependency: [if], data = [none] } return btnCancel; } }
public class class_name { public static <E> int search(List<E> list, E value, int occurrence) { if(occurrence <= 0 || occurrence > list.size()) { throw new IllegalArgumentException("Occurrence must be greater or equal to 1 and less than " + "the list length: " + occurrence); } int valuesSeen = 0; for(int i = 0; i < list.size(); i++) { if(list.get(i) == value) { valuesSeen++; if(valuesSeen == occurrence) { return i; } } } return -1; } }
public class class_name { public static <E> int search(List<E> list, E value, int occurrence) { if(occurrence <= 0 || occurrence > list.size()) { throw new IllegalArgumentException("Occurrence must be greater or equal to 1 and less than " + "the list length: " + occurrence); } int valuesSeen = 0; for(int i = 0; i < list.size(); i++) { if(list.get(i) == value) { valuesSeen++; // depends on control dependency: [if], data = [none] if(valuesSeen == occurrence) { return i; // depends on control dependency: [if], data = [none] } } } return -1; } }
public class class_name { private void processFromWeb(URL source, ListeFilme listeFilme) { Request.Builder builder = new Request.Builder().url(source); builder.addHeader("User-Agent", Config.getUserAgent()); //our progress monitor callback InputStreamProgressMonitor monitor = new InputStreamProgressMonitor() { private int oldProgress = 0; @Override public void progress(long bytesRead, long size) { final int iProgress = (int) (bytesRead * 100 / size); if (iProgress != oldProgress) { oldProgress = iProgress; notifyProgress(source.toString(), iProgress); } } }; try (Response response = MVHttpClient.getInstance().getHttpClient().newCall(builder.build()).execute(); ResponseBody body = response.body()) { if (response.isSuccessful()) { try (InputStream input = new ProgressMonitorInputStream(body.byteStream(), body.contentLength(), monitor)) { try (InputStream is = selectDecompressor(source.toString(), input); JsonParser jp = new JsonFactory().createParser(is)) { readData(jp, listeFilme); } } } } catch (Exception ex) { Log.errorLog(945123641, ex, "FilmListe: " + source); listeFilme.clear(); } } }
public class class_name { private void processFromWeb(URL source, ListeFilme listeFilme) { Request.Builder builder = new Request.Builder().url(source); builder.addHeader("User-Agent", Config.getUserAgent()); //our progress monitor callback InputStreamProgressMonitor monitor = new InputStreamProgressMonitor() { private int oldProgress = 0; @Override public void progress(long bytesRead, long size) { final int iProgress = (int) (bytesRead * 100 / size); if (iProgress != oldProgress) { oldProgress = iProgress; // depends on control dependency: [if], data = [none] notifyProgress(source.toString(), iProgress); // depends on control dependency: [if], data = [none] } } }; try (Response response = MVHttpClient.getInstance().getHttpClient().newCall(builder.build()).execute(); ResponseBody body = response.body()) { if (response.isSuccessful()) { try (InputStream input = new ProgressMonitorInputStream(body.byteStream(), body.contentLength(), monitor)) { try (InputStream is = selectDecompressor(source.toString(), input); JsonParser jp = new JsonFactory().createParser(is)) { readData(jp, listeFilme); } } } } catch (Exception ex) { Log.errorLog(945123641, ex, "FilmListe: " + source); listeFilme.clear(); } } }
public class class_name { public void add(int index, Double value) { if (value == null) { stateList.add(index, Type.NULL); } else { stateList.add(index, Type.DOUBLE); } super.add(index, value); } }
public class class_name { public void add(int index, Double value) { if (value == null) { stateList.add(index, Type.NULL); // depends on control dependency: [if], data = [none] } else { stateList.add(index, Type.DOUBLE); // depends on control dependency: [if], data = [none] } super.add(index, value); } }
public class class_name { public void setEditMode(EditMode currentMode) { super.setEditMode(currentMode); if (controller != null) { controller.setEditMode(currentMode); } } }
public class class_name { public void setEditMode(EditMode currentMode) { super.setEditMode(currentMode); if (controller != null) { controller.setEditMode(currentMode); // depends on control dependency: [if], data = [none] } } }
public class class_name { public void processResponse(Object results, Object status) { ElevationStatus pStatus = ElevationStatus.UNKNOWN_ERROR; if (status instanceof String && results instanceof JSObject) { pStatus = ElevationStatus.valueOf((String) status); if (ElevationStatus.OK.equals(pStatus)) { JSObject jsres = (JSObject) results; Object len = jsres.getMember("length"); if (len instanceof Number) { int n = ((Number)len).intValue(); ElevationResult[] ers = new ElevationResult[n]; for (int i = 0; i < n; i++) { Object obj = jsres.getSlot(i); if (obj instanceof JSObject) { ers[i] = new ElevationResult((JSObject) obj); } } callback.elevationsReceived(ers, pStatus); return; } } } callback.elevationsReceived(new ElevationResult[]{}, pStatus); } }
public class class_name { public void processResponse(Object results, Object status) { ElevationStatus pStatus = ElevationStatus.UNKNOWN_ERROR; if (status instanceof String && results instanceof JSObject) { pStatus = ElevationStatus.valueOf((String) status); // depends on control dependency: [if], data = [none] if (ElevationStatus.OK.equals(pStatus)) { JSObject jsres = (JSObject) results; Object len = jsres.getMember("length"); if (len instanceof Number) { int n = ((Number)len).intValue(); ElevationResult[] ers = new ElevationResult[n]; for (int i = 0; i < n; i++) { Object obj = jsres.getSlot(i); if (obj instanceof JSObject) { ers[i] = new ElevationResult((JSObject) obj); // depends on control dependency: [if], data = [none] } } callback.elevationsReceived(ers, pStatus); // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } } } callback.elevationsReceived(new ElevationResult[]{}, pStatus); } }
public class class_name { public static long getElapsed(final String taskTitle) { final long currentTimeMillis = System.currentTimeMillis(); if (StringUtils.isBlank(taskTitle)) { return -1; } final Stopwatch root = STOPWATCH.get(); if (null == root) { return -1; } final Stopwatch stopwatch = get(root, taskTitle); if (null == stopwatch) { return -1; } if (stopwatch.isEnded()) { return stopwatch.getElapsedTime(); } return currentTimeMillis - stopwatch.getStartTime(); } }
public class class_name { public static long getElapsed(final String taskTitle) { final long currentTimeMillis = System.currentTimeMillis(); if (StringUtils.isBlank(taskTitle)) { return -1; // depends on control dependency: [if], data = [none] } final Stopwatch root = STOPWATCH.get(); if (null == root) { return -1; // depends on control dependency: [if], data = [none] } final Stopwatch stopwatch = get(root, taskTitle); if (null == stopwatch) { return -1; // depends on control dependency: [if], data = [none] } if (stopwatch.isEnded()) { return stopwatch.getElapsedTime(); // depends on control dependency: [if], data = [none] } return currentTimeMillis - stopwatch.getStartTime(); } }
public class class_name { private void releaseAssignedResource(@Nullable Throwable cause) { assertRunningInJobMasterMainThread(); final LogicalSlot slot = assignedResource; if (slot != null) { ComponentMainThreadExecutor jobMasterMainThreadExecutor = getVertex().getExecutionGraph().getJobMasterMainThreadExecutor(); slot.releaseSlot(cause) .whenComplete((Object ignored, Throwable throwable) -> { jobMasterMainThreadExecutor.assertRunningInMainThread(); if (throwable != null) { releaseFuture.completeExceptionally(throwable); } else { releaseFuture.complete(null); } }); } else { // no assigned resource --> we can directly complete the release future releaseFuture.complete(null); } } }
public class class_name { private void releaseAssignedResource(@Nullable Throwable cause) { assertRunningInJobMasterMainThread(); final LogicalSlot slot = assignedResource; if (slot != null) { ComponentMainThreadExecutor jobMasterMainThreadExecutor = getVertex().getExecutionGraph().getJobMasterMainThreadExecutor(); slot.releaseSlot(cause) .whenComplete((Object ignored, Throwable throwable) -> { jobMasterMainThreadExecutor.assertRunningInMainThread(); // depends on control dependency: [if], data = [none] if (throwable != null) { releaseFuture.completeExceptionally(throwable); // depends on control dependency: [if], data = [(throwable] } else { releaseFuture.complete(null); // depends on control dependency: [if], data = [null)] } }); } else { // no assigned resource --> we can directly complete the release future releaseFuture.complete(null); } } }
public class class_name { public FieldDescriptor[] getLockingFields() { if (m_lockingFieldDescriptors == null) { // 1. collect all Primary Key fields from Field list Vector vec = new Vector(); for (int i = 0; i < m_FieldDescriptions.length; i++) { FieldDescriptor fd = m_FieldDescriptions[i]; if (fd.isLocking()) { vec.add(fd); } } // 2. Sort fields according to their getOrder() Property Collections.sort(vec, FieldDescriptor.getComparator()); m_lockingFieldDescriptors = (FieldDescriptor[]) vec.toArray(new FieldDescriptor[vec.size()]); } return m_lockingFieldDescriptors; } }
public class class_name { public FieldDescriptor[] getLockingFields() { if (m_lockingFieldDescriptors == null) { // 1. collect all Primary Key fields from Field list Vector vec = new Vector(); for (int i = 0; i < m_FieldDescriptions.length; i++) { FieldDescriptor fd = m_FieldDescriptions[i]; if (fd.isLocking()) { vec.add(fd); // depends on control dependency: [if], data = [none] } } // 2. Sort fields according to their getOrder() Property Collections.sort(vec, FieldDescriptor.getComparator()); // depends on control dependency: [if], data = [none] m_lockingFieldDescriptors = (FieldDescriptor[]) vec.toArray(new FieldDescriptor[vec.size()]); // depends on control dependency: [if], data = [none] } return m_lockingFieldDescriptors; } }
public class class_name { public static int parseLocalPort(final Channel channel) { if (null == channel) { return -1; } final InetSocketAddress local = (InetSocketAddress) channel.localAddress(); if (local != null) { return local.getPort(); } return -1; } }
public class class_name { public static int parseLocalPort(final Channel channel) { if (null == channel) { return -1; // depends on control dependency: [if], data = [none] } final InetSocketAddress local = (InetSocketAddress) channel.localAddress(); if (local != null) { return local.getPort(); // depends on control dependency: [if], data = [none] } return -1; } }
public class class_name { public static void removeDuplicateLineBreaks(final File f) { final String sep = StringUtil.getNewLine(); if (!f.exists()) { System.err.println("FileUtil.removeDuplicateLineBreak(File f): " + f.getAbsolutePath() + " does not exist!"); } else { if (f.isDirectory()) { System.err.println("FileUtil.removeDuplicateLineBreak(File f): " + f.getAbsolutePath() + " is a directory!"); } else { // real file FileInputStream inStream = null; BufferedInputStream in = null; FileWriter out = null; try { inStream = new FileInputStream(f); in = new BufferedInputStream(inStream, 1024); StringBuffer result = new StringBuffer(); int tmpread; while ((tmpread = in.read()) != -1) { result.append((char) tmpread); } String tmpstring; final StringTokenizer toke = new StringTokenizer(result.toString(), sep, true); result = new StringBuffer(); int breaks = 0; while (toke.hasMoreTokens()) { tmpstring = toke.nextToken().trim(); if (tmpstring.equals("") && (breaks > 0)) { breaks++; // if(breaks<=2)result.append(sep); continue; } if (tmpstring.equals("")) { tmpstring = sep; breaks++; } else { breaks = 0; } result.append(tmpstring); } // delete original file and write it new from tmpfile. f.delete(); f.createNewFile(); out = new FileWriter(f); out.write(result.toString()); } catch (final FileNotFoundException e) { // does never happen. } catch (final IOException g) { g.printStackTrace(System.err); } finally { if (in != null) { try { in.close(); } catch (final IOException e) { e.printStackTrace(); } } if (out != null) { try { out.flush(); out.close(); } catch (final IOException e) { e.printStackTrace(); } } } } } } }
public class class_name { public static void removeDuplicateLineBreaks(final File f) { final String sep = StringUtil.getNewLine(); if (!f.exists()) { System.err.println("FileUtil.removeDuplicateLineBreak(File f): " + f.getAbsolutePath() + " does not exist!"); // depends on control dependency: [if], data = [none] } else { if (f.isDirectory()) { System.err.println("FileUtil.removeDuplicateLineBreak(File f): " + f.getAbsolutePath() + " is a directory!"); // depends on control dependency: [if], data = [none] } else { // real file FileInputStream inStream = null; BufferedInputStream in = null; FileWriter out = null; try { inStream = new FileInputStream(f); // depends on control dependency: [try], data = [none] in = new BufferedInputStream(inStream, 1024); // depends on control dependency: [try], data = [none] StringBuffer result = new StringBuffer(); int tmpread; while ((tmpread = in.read()) != -1) { result.append((char) tmpread); // depends on control dependency: [while], data = [none] } String tmpstring; final StringTokenizer toke = new StringTokenizer(result.toString(), sep, true); result = new StringBuffer(); // depends on control dependency: [try], data = [none] int breaks = 0; while (toke.hasMoreTokens()) { tmpstring = toke.nextToken().trim(); // depends on control dependency: [while], data = [none] if (tmpstring.equals("") && (breaks > 0)) { breaks++; // depends on control dependency: [if], data = [none] // if(breaks<=2)result.append(sep); continue; } if (tmpstring.equals("")) { tmpstring = sep; // depends on control dependency: [if], data = [none] breaks++; // depends on control dependency: [if], data = [none] } else { breaks = 0; // depends on control dependency: [if], data = [none] } result.append(tmpstring); // depends on control dependency: [while], data = [none] } // delete original file and write it new from tmpfile. f.delete(); // depends on control dependency: [try], data = [none] f.createNewFile(); // depends on control dependency: [try], data = [none] out = new FileWriter(f); // depends on control dependency: [try], data = [none] out.write(result.toString()); // depends on control dependency: [try], data = [none] } catch (final FileNotFoundException e) { // does never happen. } catch (final IOException g) { // depends on control dependency: [catch], data = [none] g.printStackTrace(System.err); } finally { // depends on control dependency: [catch], data = [none] if (in != null) { try { in.close(); // depends on control dependency: [try], data = [none] } catch (final IOException e) { e.printStackTrace(); } // depends on control dependency: [catch], data = [none] } if (out != null) { try { out.flush(); // depends on control dependency: [try], data = [none] out.close(); // depends on control dependency: [try], data = [none] } catch (final IOException e) { e.printStackTrace(); } // depends on control dependency: [catch], data = [none] } } } } } }
public class class_name { public CreateCloudFormationStackRequest withInstances(InstanceEntry... instances) { if (this.instances == null) { setInstances(new java.util.ArrayList<InstanceEntry>(instances.length)); } for (InstanceEntry ele : instances) { this.instances.add(ele); } return this; } }
public class class_name { public CreateCloudFormationStackRequest withInstances(InstanceEntry... instances) { if (this.instances == null) { setInstances(new java.util.ArrayList<InstanceEntry>(instances.length)); // depends on control dependency: [if], data = [none] } for (InstanceEntry ele : instances) { this.instances.add(ele); // depends on control dependency: [for], data = [ele] } return this; } }
public class class_name { public void cleanEmptyDirectories(final Set<Path> possiblyEmptyDirectories, final FileSystemDataset fsDataset) throws IOException { if (this.deleteEmptyDirectories && !this.simulate) { for (Path parentDirectory : possiblyEmptyDirectories) { PathUtils.deleteEmptyParentDirectories(fs, fsDataset.datasetRoot(), parentDirectory); } } } }
public class class_name { public void cleanEmptyDirectories(final Set<Path> possiblyEmptyDirectories, final FileSystemDataset fsDataset) throws IOException { if (this.deleteEmptyDirectories && !this.simulate) { for (Path parentDirectory : possiblyEmptyDirectories) { PathUtils.deleteEmptyParentDirectories(fs, fsDataset.datasetRoot(), parentDirectory); // depends on control dependency: [for], data = [parentDirectory] } } } }
public class class_name { @Override public EEnum getIfcChimneyTypeEnum() { if (ifcChimneyTypeEnumEEnum == null) { ifcChimneyTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(934); } return ifcChimneyTypeEnumEEnum; } }
public class class_name { @Override public EEnum getIfcChimneyTypeEnum() { if (ifcChimneyTypeEnumEEnum == null) { ifcChimneyTypeEnumEEnum = (EEnum) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI) .getEClassifiers().get(934); // depends on control dependency: [if], data = [none] } return ifcChimneyTypeEnumEEnum; } }
public class class_name { @Pure public static ServiceLoader<SREBootstrap> getServiceLoader(boolean onlyInstalledInJRE) { synchronized (SRE.class) { ServiceLoader<SREBootstrap> sl = loader == null ? null : loader.get(); if (sl == null) { if (onlyInstalledInJRE) { sl = ServiceLoader.loadInstalled(SREBootstrap.class); } else { sl = ServiceLoader.load(SREBootstrap.class); } loader = new SoftReference<>(sl); } return sl; } } }
public class class_name { @Pure public static ServiceLoader<SREBootstrap> getServiceLoader(boolean onlyInstalledInJRE) { synchronized (SRE.class) { ServiceLoader<SREBootstrap> sl = loader == null ? null : loader.get(); if (sl == null) { if (onlyInstalledInJRE) { sl = ServiceLoader.loadInstalled(SREBootstrap.class); // depends on control dependency: [if], data = [none] } else { sl = ServiceLoader.load(SREBootstrap.class); // depends on control dependency: [if], data = [none] } loader = new SoftReference<>(sl); // depends on control dependency: [if], data = [(sl] } return sl; } } }
public class class_name { public void close(VirtualConnection inVC, Exception e) { // when the channel above calls close() on the outbound connection then // we are done... no need to purge anything off the socket like we do // on the inbound side (purge request body if they never read it) // pass the close down the chain. if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Closing this outbound link: " + this + " " + getVirtualConnection()); } setAllowReconnect(false); if (!this.earlyReconnectDestroy) { super.close(inVC, e); } else { destroy(e); } } }
public class class_name { public void close(VirtualConnection inVC, Exception e) { // when the channel above calls close() on the outbound connection then // we are done... no need to purge anything off the socket like we do // on the inbound side (purge request body if they never read it) // pass the close down the chain. if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Closing this outbound link: " + this + " " + getVirtualConnection()); // depends on control dependency: [if], data = [none] } setAllowReconnect(false); if (!this.earlyReconnectDestroy) { super.close(inVC, e); // depends on control dependency: [if], data = [none] } else { destroy(e); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static String getLibInfo() { String info = libInfo.get(); if (info == null) { info = String.format(Locale.ENGLISH, LIB_INFO, C4.getVersion()); libInfo.compareAndSet(null, info); } return info; } }
public class class_name { public static String getLibInfo() { String info = libInfo.get(); if (info == null) { info = String.format(Locale.ENGLISH, LIB_INFO, C4.getVersion()); // depends on control dependency: [if], data = [none] libInfo.compareAndSet(null, info); // depends on control dependency: [if], data = [none] } return info; } }
public class class_name { public static <T> T last(Iterable<T> iterable) { if (iterable instanceof List<?>) { List<T> list = (List<T>) iterable; if (list.isEmpty()) return null; return list.get(list.size() - 1); } else if (iterable instanceof SortedSet) { SortedSet<T> sortedSet = (SortedSet<T>) iterable; if (sortedSet.isEmpty()) return null; return sortedSet.last(); } else { return IteratorExtensions.last(iterable.iterator()); } } }
public class class_name { public static <T> T last(Iterable<T> iterable) { if (iterable instanceof List<?>) { List<T> list = (List<T>) iterable; if (list.isEmpty()) return null; return list.get(list.size() - 1); // depends on control dependency: [if], data = [)] } else if (iterable instanceof SortedSet) { SortedSet<T> sortedSet = (SortedSet<T>) iterable; if (sortedSet.isEmpty()) return null; return sortedSet.last(); // depends on control dependency: [if], data = [none] } else { return IteratorExtensions.last(iterable.iterator()); // depends on control dependency: [if], data = [none] } } }
public class class_name { public MethodDescriptor getMethodDescriptor(final String name) { final MethodDescriptor[] methodDescriptors = methodsMap.get(name); if (methodDescriptors == null) { return null; } if (methodDescriptors.length != 1) { throw new IllegalArgumentException("Method name not unique: " + name); } return methodDescriptors[0]; } }
public class class_name { public MethodDescriptor getMethodDescriptor(final String name) { final MethodDescriptor[] methodDescriptors = methodsMap.get(name); if (methodDescriptors == null) { return null; // depends on control dependency: [if], data = [none] } if (methodDescriptors.length != 1) { throw new IllegalArgumentException("Method name not unique: " + name); } return methodDescriptors[0]; } }
public class class_name { public void setRestoreLastValid (boolean restoreLastValid) { if (hasSelection) throw new IllegalStateException("Last valid text restore can't be changed while filed has selection"); this.restoreLastValid = restoreLastValid; if (restoreLastValid) { if (restoreFocusListener == null) restoreFocusListener = new LastValidFocusListener(); addListener(restoreFocusListener); } else { removeListener(restoreFocusListener); } } }
public class class_name { public void setRestoreLastValid (boolean restoreLastValid) { if (hasSelection) throw new IllegalStateException("Last valid text restore can't be changed while filed has selection"); this.restoreLastValid = restoreLastValid; if (restoreLastValid) { if (restoreFocusListener == null) restoreFocusListener = new LastValidFocusListener(); addListener(restoreFocusListener); // depends on control dependency: [if], data = [none] } else { removeListener(restoreFocusListener); // depends on control dependency: [if], data = [none] } } }
public class class_name { protected void closeConnection(ThriftConnectionHandle<T> connection) { if (connection != null) { try { connection.internalClose(); } catch (Throwable t) { logger.error("Destroy connection exception", t); } finally { this.thriftConnectionPool.postDestroyConnection(connection); } } } }
public class class_name { protected void closeConnection(ThriftConnectionHandle<T> connection) { if (connection != null) { try { connection.internalClose(); // depends on control dependency: [try], data = [none] } catch (Throwable t) { logger.error("Destroy connection exception", t); } finally { // depends on control dependency: [catch], data = [none] this.thriftConnectionPool.postDestroyConnection(connection); } } } }
public class class_name { @Override public ODocument toStream() { internalAcquireExclusiveLock(); try { document.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING); try { final OTrackedSet<ODocument> indexes = new OTrackedSet<>(document); for (final OIndex<?> i : this.indexes.values()) { indexes.add(((OIndexInternal<?>) i).updateConfiguration()); } document.field(CONFIG_INDEXES, indexes, OType.EMBEDDEDSET); } finally { document.setInternalStatus(ORecordElement.STATUS.LOADED); } document.setDirty(); return document; } finally { internalReleaseExclusiveLock(); } } }
public class class_name { @Override public ODocument toStream() { internalAcquireExclusiveLock(); try { document.setInternalStatus(ORecordElement.STATUS.UNMARSHALLING); // depends on control dependency: [try], data = [none] try { final OTrackedSet<ODocument> indexes = new OTrackedSet<>(document); for (final OIndex<?> i : this.indexes.values()) { indexes.add(((OIndexInternal<?>) i).updateConfiguration()); // depends on control dependency: [for], data = [i] } document.field(CONFIG_INDEXES, indexes, OType.EMBEDDEDSET); // depends on control dependency: [try], data = [none] } finally { document.setInternalStatus(ORecordElement.STATUS.LOADED); } document.setDirty(); // depends on control dependency: [try], data = [none] return document; // depends on control dependency: [try], data = [none] } finally { internalReleaseExclusiveLock(); } } }
public class class_name { public String replaceAll(String content, Map<String, String> replacements) { Element body = parseContent(content); boolean modified = false; for (Entry<String, String> replacementEntry : replacements.entrySet()) { String selector = replacementEntry.getKey(); String replacement = replacementEntry.getValue(); List<Element> elements = body.select(selector); if (elements.size() > 0) { // take the first child Element replacementElem = parseContent(replacement).child(0); if (replacementElem != null) { for (Element element : elements) { element.replaceWith(replacementElem.clone()); } modified = true; } } } if (modified) { return body.html(); } else { // nothing changed return content; } } }
public class class_name { public String replaceAll(String content, Map<String, String> replacements) { Element body = parseContent(content); boolean modified = false; for (Entry<String, String> replacementEntry : replacements.entrySet()) { String selector = replacementEntry.getKey(); String replacement = replacementEntry.getValue(); List<Element> elements = body.select(selector); if (elements.size() > 0) { // take the first child Element replacementElem = parseContent(replacement).child(0); if (replacementElem != null) { for (Element element : elements) { element.replaceWith(replacementElem.clone()); // depends on control dependency: [for], data = [element] } modified = true; // depends on control dependency: [if], data = [none] } } } if (modified) { return body.html(); // depends on control dependency: [if], data = [none] } else { // nothing changed return content; // depends on control dependency: [if], data = [none] } } }
public class class_name { @SuppressWarnings("deprecation") static final void xalanExtensionAware(XPath xpath) { // Load xalan extensions thread-safely for all of jOOX if (!xalanExtensionLoaded) { synchronized (Util.class) { if (!xalanExtensionLoaded) { xalanExtensionLoaded = true; try { xalanNamespaceContext = (NamespaceContext) Class.forName("org.apache.xalan.extensions.ExtensionNamespaceContext").newInstance(); xalanFunctionResolver = (XPathFunctionResolver) Class.forName("org.apache.xalan.extensions.XPathFunctionResolverImpl").newInstance(); } catch (Exception ignore) { } } } } if (xalanNamespaceContext != null && xalanFunctionResolver != null) { xpath.setNamespaceContext(xalanNamespaceContext); xpath.setXPathFunctionResolver(xalanFunctionResolver); } } }
public class class_name { @SuppressWarnings("deprecation") static final void xalanExtensionAware(XPath xpath) { // Load xalan extensions thread-safely for all of jOOX if (!xalanExtensionLoaded) { synchronized (Util.class) { // depends on control dependency: [if], data = [none] if (!xalanExtensionLoaded) { xalanExtensionLoaded = true; // depends on control dependency: [if], data = [none] try { xalanNamespaceContext = (NamespaceContext) Class.forName("org.apache.xalan.extensions.ExtensionNamespaceContext").newInstance(); // depends on control dependency: [try], data = [none] xalanFunctionResolver = (XPathFunctionResolver) Class.forName("org.apache.xalan.extensions.XPathFunctionResolverImpl").newInstance(); // depends on control dependency: [try], data = [none] } catch (Exception ignore) { } // depends on control dependency: [catch], data = [none] } } } if (xalanNamespaceContext != null && xalanFunctionResolver != null) { xpath.setNamespaceContext(xalanNamespaceContext); // depends on control dependency: [if], data = [(xalanNamespaceContext] xpath.setXPathFunctionResolver(xalanFunctionResolver); // depends on control dependency: [if], data = [none] } } }
public class class_name { private void provisionWithWait(DockerComputerSingle computer, TaskListener listener) throws Exception { final PrintStream logger = listener.getLogger(); final Run run = computer.getRun(); final DockerSlaveSingle slave = computer.getNode(); if (isNull(slave)) { throw new IllegalStateException("Can't get slave for " + computer.getNode()); } final DockerClient client = slave.getConnector().getClient(); final DockerContainerLifecycle containerLifecycle = slave.getConfig().getDockerContainerLifecycle(); final String imageId = containerLifecycle.getImage(); //pull image logger.println("Pulling image " + imageId + "..."); containerLifecycle.getPullImage().exec(client, imageId, listener); logger.println("Trying to create container for " + imageId); LOG.info("Trying to create container for {}", imageId); final DockerCreateContainer createContainer = containerLifecycle.getCreateContainer(); CreateContainerCmd containerConfig = client.createContainerCmd(imageId); // template specific options createContainer.fillContainerConfig(containerConfig, null); // cloud specific options appendContainerConfig(containerConfig); // create CreateContainerResponse createResp = containerConfig.exec(); String cId = createResp.getId(); setContainerId(cId); logger.println("Created container " + cId + ", for " + run.getDisplayName()); LOG.debug("Created container {}, for {}", cId, run.getDisplayName()); // start StartContainerCmd startCommand = client.startContainerCmd(cId); startCommand.exec(); logger.println("Started container " + cId); LOG.debug("Started container '{}', for '{}'.", cId, run.getDisplayName()); boolean running = false; long launchTime = System.currentTimeMillis(); while (!running && TimeUnit2.SECONDS.toMillis(launchTimeout) > System.currentTimeMillis() - launchTime) { try { InspectContainerResponse inspectResp = client.inspectContainerCmd(cId).exec(); if (isTrue(inspectResp.getState().getRunning())) { logger.println("Container is running."); LOG.debug("Container '{}' is running.", cId); running = true; } else { logger.println("Container is not running..."); } } catch (ProcessingException ignore) { } Thread.sleep(1000); } if (!running) { listener.error("Failed to run container for %s, clean-up container", imageId); LOG.error("Failed to run container for {}, clean-up container", imageId); printLog(client, listener, cId); throw new IllegalStateException("Container is not running!"); } // now real launch final String rootUrl = getJenkinsUrl(Jenkins.getInstance().getRootUrl()); // Objects.requireNonNull(rootUrl, "Jenkins root url is not specified!"); if (isNull(rootUrl)) { listener.fatalError("Jenkins root url is not specified!"); containerLifecycle.getRemoveContainer().exec(client, cId); throw new IllegalStateException("Jenkins root url is not specified!"); } final DockerSlaveSingle node = computer.getNode(); if (isNull(node)) { listener.error("Failed to run container for %s", imageId); printLog(client, listener, containerId); throw new IllegalStateException("Node for computer: '" + computer.getName() + "' can't be null, probably remote node disappeared."); } // exec jnlp connection in running container // TODO implement PID 1 replacement String startCmd = "cat << EOF > /tmp/config.sh.tmp && cd /tmp && mv config.sh.tmp config.sh\n" + "JENKINS_URL=\"" + rootUrl + NL + "JENKINS_USER=\"" + getUser() + NL + "JENKINS_HOME=\"" + node.getRemoteFS() + NL + "COMPUTER_URL=\"" + computer.getUrl() + NL + "COMPUTER_SECRET=\"" + computer.getJnlpMac() + NL + "JAVA_OPTS=\"" + getJvmOpts() + NL + "SLAVE_OPTS=\"" + getSlaveOpts() + NL + "NO_CERTIFICATE_CHECK=\"" + isNoCertificateCheck() + NL + "NO_RECONNECT_SLAVE=\"" + isNoReconnect() + NL + "EOF" + "\n"; try { final ExecCreateCmdResponse createCmdResponse = client.execCreateCmd(cId) .withTty(true) .withAttachStdin(false) .withAttachStderr(true) .withAttachStdout(true) .withCmd("/bin/sh", "-cxe", startCmd.replace("$", "\\$")) .exec(); logger.println("Starting connection command for " + cId); LOG.info("Starting connection command for {}", cId); try (ExecStartResultCallback exec = client.execStartCmd(createCmdResponse.getId()) .withDetach(true) .withTty(true) .exec(new ExecStartResultCallback()) ) { exec.awaitCompletion(10, SECONDS); } catch (NotFoundException ex) { listener.error("Can't execute command: " + ex.getMessage().trim()); LOG.error("Can't execute jnlp connection command: '{}'", ex.getMessage().trim()); throw ex; } } catch (Throwable ex) { listener.error("Can't execute command: " + ex.getMessage().trim()); LOG.error("Can't execute jnlp connection command: '{}'", ex.getMessage().trim()); throw ex; } LOG.info("Successfully executed jnlp connection for '{}'", cId); logger.println("Successfully executed jnlp connection for " + cId); // TODO better strategy launchTime = System.currentTimeMillis(); while (computer.isReallyOffline() && TimeUnit2.SECONDS.toMillis(launchTimeout) > System.currentTimeMillis() - launchTime) { logger.println("Waiting slave connection..."); Thread.sleep(1000); } if (computer.isReallyOffline()) { LOG.info("Launch timeout, terminating slave based on '{}'", cId); logger.println("Launch timeout, terminating slave."); printLog(client, listener, cId); throw new IllegalStateException("Agent didn't connect after timeout."); } LOG.info("Launched slave '{}' '{}' based on '{}'", computer.getSlaveVersion(), computer.getName(), cId); logger.println("Launched slave for " + cId); } }
public class class_name { private void provisionWithWait(DockerComputerSingle computer, TaskListener listener) throws Exception { final PrintStream logger = listener.getLogger(); final Run run = computer.getRun(); final DockerSlaveSingle slave = computer.getNode(); if (isNull(slave)) { throw new IllegalStateException("Can't get slave for " + computer.getNode()); } final DockerClient client = slave.getConnector().getClient(); final DockerContainerLifecycle containerLifecycle = slave.getConfig().getDockerContainerLifecycle(); final String imageId = containerLifecycle.getImage(); //pull image logger.println("Pulling image " + imageId + "..."); containerLifecycle.getPullImage().exec(client, imageId, listener); logger.println("Trying to create container for " + imageId); LOG.info("Trying to create container for {}", imageId); final DockerCreateContainer createContainer = containerLifecycle.getCreateContainer(); CreateContainerCmd containerConfig = client.createContainerCmd(imageId); // template specific options createContainer.fillContainerConfig(containerConfig, null); // cloud specific options appendContainerConfig(containerConfig); // create CreateContainerResponse createResp = containerConfig.exec(); String cId = createResp.getId(); setContainerId(cId); logger.println("Created container " + cId + ", for " + run.getDisplayName()); LOG.debug("Created container {}, for {}", cId, run.getDisplayName()); // start StartContainerCmd startCommand = client.startContainerCmd(cId); startCommand.exec(); logger.println("Started container " + cId); LOG.debug("Started container '{}', for '{}'.", cId, run.getDisplayName()); boolean running = false; long launchTime = System.currentTimeMillis(); while (!running && TimeUnit2.SECONDS.toMillis(launchTimeout) > System.currentTimeMillis() - launchTime) { try { InspectContainerResponse inspectResp = client.inspectContainerCmd(cId).exec(); if (isTrue(inspectResp.getState().getRunning())) { logger.println("Container is running."); // depends on control dependency: [if], data = [none] LOG.debug("Container '{}' is running.", cId); // depends on control dependency: [if], data = [none] running = true; // depends on control dependency: [if], data = [none] } else { logger.println("Container is not running..."); // depends on control dependency: [if], data = [none] } } catch (ProcessingException ignore) { } // depends on control dependency: [catch], data = [none] Thread.sleep(1000); // depends on control dependency: [while], data = [none] } if (!running) { listener.error("Failed to run container for %s, clean-up container", imageId); // depends on control dependency: [if], data = [none] LOG.error("Failed to run container for {}, clean-up container", imageId); // depends on control dependency: [if], data = [none] printLog(client, listener, cId); // depends on control dependency: [if], data = [none] throw new IllegalStateException("Container is not running!"); } // now real launch final String rootUrl = getJenkinsUrl(Jenkins.getInstance().getRootUrl()); // Objects.requireNonNull(rootUrl, "Jenkins root url is not specified!"); if (isNull(rootUrl)) { listener.fatalError("Jenkins root url is not specified!"); // depends on control dependency: [if], data = [none] containerLifecycle.getRemoveContainer().exec(client, cId); // depends on control dependency: [if], data = [none] throw new IllegalStateException("Jenkins root url is not specified!"); } final DockerSlaveSingle node = computer.getNode(); if (isNull(node)) { listener.error("Failed to run container for %s", imageId); // depends on control dependency: [if], data = [none] printLog(client, listener, containerId); // depends on control dependency: [if], data = [none] throw new IllegalStateException("Node for computer: '" + computer.getName() + "' can't be null, probably remote node disappeared."); } // exec jnlp connection in running container // TODO implement PID 1 replacement String startCmd = "cat << EOF > /tmp/config.sh.tmp && cd /tmp && mv config.sh.tmp config.sh\n" + "JENKINS_URL=\"" + rootUrl + NL + "JENKINS_USER=\"" + getUser() + NL + "JENKINS_HOME=\"" + node.getRemoteFS() + NL + "COMPUTER_URL=\"" + computer.getUrl() + NL + "COMPUTER_SECRET=\"" + computer.getJnlpMac() + NL + "JAVA_OPTS=\"" + getJvmOpts() + NL + "SLAVE_OPTS=\"" + getSlaveOpts() + NL + "NO_CERTIFICATE_CHECK=\"" + isNoCertificateCheck() + NL + "NO_RECONNECT_SLAVE=\"" + isNoReconnect() + NL + "EOF" + "\n"; try { final ExecCreateCmdResponse createCmdResponse = client.execCreateCmd(cId) .withTty(true) .withAttachStdin(false) .withAttachStderr(true) .withAttachStdout(true) .withCmd("/bin/sh", "-cxe", startCmd.replace("$", "\\$")) .exec(); logger.println("Starting connection command for " + cId); LOG.info("Starting connection command for {}", cId); try (ExecStartResultCallback exec = client.execStartCmd(createCmdResponse.getId()) .withDetach(true) .withTty(true) .exec(new ExecStartResultCallback()) ) { exec.awaitCompletion(10, SECONDS); } catch (NotFoundException ex) { listener.error("Can't execute command: " + ex.getMessage().trim()); LOG.error("Can't execute jnlp connection command: '{}'", ex.getMessage().trim()); // depends on control dependency: [if], data = [none] throw ex; } } catch (Throwable ex) { listener.error("Can't execute command: " + ex.getMessage().trim()); LOG.error("Can't execute jnlp connection command: '{}'", ex.getMessage().trim()); throw ex; } LOG.info("Successfully executed jnlp connection for '{}'", cId); logger.println("Successfully executed jnlp connection for " + cId); // TODO better strategy launchTime = System.currentTimeMillis(); while (computer.isReallyOffline() && TimeUnit2.SECONDS.toMillis(launchTimeout) > System.currentTimeMillis() - launchTime) { logger.println("Waiting slave connection..."); Thread.sleep(1000); } if (computer.isReallyOffline()) { LOG.info("Launch timeout, terminating slave based on '{}'", cId); logger.println("Launch timeout, terminating slave."); printLog(client, listener, cId); throw new IllegalStateException("Agent didn't connect after timeout."); } LOG.info("Launched slave '{}' '{}' based on '{}'", computer.getSlaveVersion(), computer.getName(), cId); logger.println("Launched slave for " + cId); } }
public class class_name { public static void closeAll() { try { H2O._udpSocket.close(); } catch( IOException e ) { } try { H2O._apiSocket.close(); } catch( IOException e ) { } try { TCPReceiverThread.SOCK.close(); } catch( IOException e ) { } } }
public class class_name { public static void closeAll() { try { H2O._udpSocket.close(); } catch( IOException e ) { } // depends on control dependency: [try], data = [none] // depends on control dependency: [catch], data = [none] try { H2O._apiSocket.close(); } catch( IOException e ) { } // depends on control dependency: [try], data = [none] // depends on control dependency: [catch], data = [none] try { TCPReceiverThread.SOCK.close(); } catch( IOException e ) { } // depends on control dependency: [try], data = [none] // depends on control dependency: [catch], data = [none] } }
public class class_name { public Optional<Member> getOptionalMember(Object groupIdOrPath, int userId) { try { return (Optional.ofNullable(getMember(groupIdOrPath, userId))); } catch (GitLabApiException glae) { return (GitLabApi.createOptionalFromException(glae)); } } }
public class class_name { public Optional<Member> getOptionalMember(Object groupIdOrPath, int userId) { try { return (Optional.ofNullable(getMember(groupIdOrPath, userId))); // depends on control dependency: [try], data = [none] } catch (GitLabApiException glae) { return (GitLabApi.createOptionalFromException(glae)); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private int indexRows(long geoPackageId, FeatureCursor cursor) { int count = -1; try { while ((progress == null || progress.isActive()) && cursor.moveToNext()) { if (count < 0) { count++; } try { FeatureRow row = cursor.getRow(); if (row.isValid()) { boolean indexed = index(geoPackageId, row, false); if (indexed) { count++; } if (progress != null) { progress.addProgress(1); } } } catch (Exception e) { Log.e(FeatureIndexer.class.getSimpleName(), "Failed to index feature. Table: " + featureDao.getTableName() + ", Position: " + cursor.getPosition(), e); } } } finally { cursor.close(); } return count; } }
public class class_name { private int indexRows(long geoPackageId, FeatureCursor cursor) { int count = -1; try { while ((progress == null || progress.isActive()) && cursor.moveToNext()) { if (count < 0) { count++; // depends on control dependency: [if], data = [none] } try { FeatureRow row = cursor.getRow(); if (row.isValid()) { boolean indexed = index(geoPackageId, row, false); if (indexed) { count++; // depends on control dependency: [if], data = [none] } if (progress != null) { progress.addProgress(1); // depends on control dependency: [if], data = [none] } } } catch (Exception e) { Log.e(FeatureIndexer.class.getSimpleName(), "Failed to index feature. Table: " + featureDao.getTableName() + ", Position: " + cursor.getPosition(), e); } // depends on control dependency: [catch], data = [none] } } finally { cursor.close(); } return count; } }
public class class_name { private void getAllDescendants(Resource<L> parent, List<Resource<L>> descendants) { for (Resource<L> child : getChildren(parent)) { if (!descendants.contains(child)) { getAllDescendants(child, descendants); descendants.add(child); } } return; } }
public class class_name { private void getAllDescendants(Resource<L> parent, List<Resource<L>> descendants) { for (Resource<L> child : getChildren(parent)) { if (!descendants.contains(child)) { getAllDescendants(child, descendants); // depends on control dependency: [if], data = [none] descendants.add(child); // depends on control dependency: [if], data = [none] } } return; } }
public class class_name { private AuthzHandler createAuthzHandler( List<Annotation> controllerAnnotations, List<Annotation> methodAnnotations) { //没有注解 if (controllerAnnotations.size() == 0 && methodAnnotations.size() == 0) { return null; } //至少有一个注解 List<AuthzHandler> authzHandlers = Lists.newArrayListWithCapacity(5); for (int index = 0; index < 5; index++) { authzHandlers.add(null); } // 逐个扫描注解,若是相应的注解则在相应的位置赋值。 scanAnnotation(authzHandlers, controllerAnnotations); // 逐个扫描注解,若是相应的注解则在相应的位置赋值。函数的注解优先级高于Controller scanAnnotation(authzHandlers, methodAnnotations); // 去除空值 List<AuthzHandler> finalAuthzHandlers = Lists.newArrayList(); for (AuthzHandler a : authzHandlers) { if (a != null) { finalAuthzHandlers.add(a); } } authzHandlers = null; // 存在多个,则构建组合AuthzHandler if (finalAuthzHandlers.size() > 1) { return new CompositeAuthzHandler(finalAuthzHandlers); } // 一个的话直接返回 return finalAuthzHandlers.get(0); } }
public class class_name { private AuthzHandler createAuthzHandler( List<Annotation> controllerAnnotations, List<Annotation> methodAnnotations) { //没有注解 if (controllerAnnotations.size() == 0 && methodAnnotations.size() == 0) { return null; // depends on control dependency: [if], data = [none] } //至少有一个注解 List<AuthzHandler> authzHandlers = Lists.newArrayListWithCapacity(5); for (int index = 0; index < 5; index++) { authzHandlers.add(null); // depends on control dependency: [for], data = [none] } // 逐个扫描注解,若是相应的注解则在相应的位置赋值。 scanAnnotation(authzHandlers, controllerAnnotations); // 逐个扫描注解,若是相应的注解则在相应的位置赋值。函数的注解优先级高于Controller scanAnnotation(authzHandlers, methodAnnotations); // 去除空值 List<AuthzHandler> finalAuthzHandlers = Lists.newArrayList(); for (AuthzHandler a : authzHandlers) { if (a != null) { finalAuthzHandlers.add(a); // depends on control dependency: [if], data = [(a] } } authzHandlers = null; // 存在多个,则构建组合AuthzHandler if (finalAuthzHandlers.size() > 1) { return new CompositeAuthzHandler(finalAuthzHandlers); // depends on control dependency: [if], data = [none] } // 一个的话直接返回 return finalAuthzHandlers.get(0); } }
public class class_name { public static <E> void notNullOrEmpty(final E[] argument, final String name) { if (argument == null) { s_logger.error("Argument {} was null", name); throw new QuandlRuntimeException("Value " + name + " was null"); } else if (argument.length == 0) { s_logger.error("Argument {} was empty array", name); throw new QuandlRuntimeException("Value " + name + " was empty array"); } } }
public class class_name { public static <E> void notNullOrEmpty(final E[] argument, final String name) { if (argument == null) { s_logger.error("Argument {} was null", name); // depends on control dependency: [if], data = [none] throw new QuandlRuntimeException("Value " + name + " was null"); } else if (argument.length == 0) { s_logger.error("Argument {} was empty array", name); // depends on control dependency: [if], data = [none] throw new QuandlRuntimeException("Value " + name + " was empty array"); } } }
public class class_name { @SuppressWarnings("unchecked") public static <T> Function<? super Publisher<T>, ? extends Publisher<T>> scopePassingSpanOperator( BeanFactory beanFactory) { if (log.isTraceEnabled()) { log.trace("Scope passing operator [" + beanFactory + "]"); } // Adapt if lazy bean factory BooleanSupplier isActive = beanFactory instanceof ConfigurableApplicationContext ? ((ConfigurableApplicationContext) beanFactory)::isActive : () -> true; return Operators.liftPublisher((p, sub) -> { // if Flux/Mono #just, #empty, #error if (p instanceof Fuseable.ScalarCallable) { return sub; } Scannable scannable = Scannable.from(p); // rest of the logic unchanged... if (isActive.getAsBoolean()) { if (log.isTraceEnabled()) { log.trace("Spring Context [" + beanFactory + "] already refreshed. Creating a scope " + "passing span subscriber with Reactor Context " + "[" + sub.currentContext() + "] and name [" + scannable.name() + "]"); } return scopePassingSpanSubscription(beanFactory.getBean(Tracing.class), sub); } if (log.isTraceEnabled()) { log.trace("Spring Context [" + beanFactory + "] is not yet refreshed, falling back to lazy span subscriber. Reactor Context is [" + sub.currentContext() + "] and name is [" + scannable.name() + "]"); } return new LazySpanSubscriber<>( lazyScopePassingSpanSubscription(beanFactory, scannable, sub)); }); } }
public class class_name { @SuppressWarnings("unchecked") public static <T> Function<? super Publisher<T>, ? extends Publisher<T>> scopePassingSpanOperator( BeanFactory beanFactory) { if (log.isTraceEnabled()) { log.trace("Scope passing operator [" + beanFactory + "]"); // depends on control dependency: [if], data = [none] } // Adapt if lazy bean factory BooleanSupplier isActive = beanFactory instanceof ConfigurableApplicationContext ? ((ConfigurableApplicationContext) beanFactory)::isActive : () -> true; return Operators.liftPublisher((p, sub) -> { // if Flux/Mono #just, #empty, #error if (p instanceof Fuseable.ScalarCallable) { return sub; // depends on control dependency: [if], data = [none] } Scannable scannable = Scannable.from(p); // rest of the logic unchanged... if (isActive.getAsBoolean()) { if (log.isTraceEnabled()) { log.trace("Spring Context [" + beanFactory + "] already refreshed. Creating a scope " + "passing span subscriber with Reactor Context " + "[" + sub.currentContext() + "] and name [" + scannable.name() + "]"); // depends on control dependency: [if], data = [none] } return scopePassingSpanSubscription(beanFactory.getBean(Tracing.class), sub); // depends on control dependency: [if], data = [none] } if (log.isTraceEnabled()) { log.trace("Spring Context [" + beanFactory + "] is not yet refreshed, falling back to lazy span subscriber. Reactor Context is [" + sub.currentContext() + "] and name is [" + scannable.name() + "]"); // depends on control dependency: [if], data = [none] } return new LazySpanSubscriber<>( lazyScopePassingSpanSubscription(beanFactory, scannable, sub)); }); } }
public class class_name { protected void writeMethodInfo(MethodInfo info) { Node currentNode = this.currentNode; Element tmp = doc.createElementNS(XML_URI, "method"); currentNode.appendChild(tmp); this.currentNode = tmp; addAccessFlags(info); if (info.getName() != null) tmp.setAttribute( "name", info.getName()); if (info.getSignature() != null) tmp.setAttribute( "signature", info.getSignature()); if (info.getDesc() != null) addMethodNodes(info.getDesc()); String[] exceptions = info.getExceptions(); if (exceptions != null) { for (int i = 0; i < exceptions.length; i++) { Element excep = doc.createElementNS(XML_URI, "exception"); excep.setAttribute( "name", exceptions[i]); tmp.appendChild(excep); } } this.currentNode = currentNode; } }
public class class_name { protected void writeMethodInfo(MethodInfo info) { Node currentNode = this.currentNode; Element tmp = doc.createElementNS(XML_URI, "method"); currentNode.appendChild(tmp); this.currentNode = tmp; addAccessFlags(info); if (info.getName() != null) tmp.setAttribute( "name", info.getName()); if (info.getSignature() != null) tmp.setAttribute( "signature", info.getSignature()); if (info.getDesc() != null) addMethodNodes(info.getDesc()); String[] exceptions = info.getExceptions(); if (exceptions != null) { for (int i = 0; i < exceptions.length; i++) { Element excep = doc.createElementNS(XML_URI, "exception"); excep.setAttribute( "name", exceptions[i]); // depends on control dependency: [for], data = [i] tmp.appendChild(excep); // depends on control dependency: [for], data = [none] } } this.currentNode = currentNode; } }
public class class_name { public static PnkyPromise<Void> runAsync(final ThrowingRunnable operation, final Executor executor) { final Pnky<Void> pnky = Pnky.create(); executor.execute(new Runnable() { @Override public void run() { if (pnky.state.compareAndSet(WAITING, RUNNING)) { try { operation.run(); pnky.resolve(null); } catch (final Throwable e) { pnky.reject(e); } } } }); return pnky; } }
public class class_name { public static PnkyPromise<Void> runAsync(final ThrowingRunnable operation, final Executor executor) { final Pnky<Void> pnky = Pnky.create(); executor.execute(new Runnable() { @Override public void run() { if (pnky.state.compareAndSet(WAITING, RUNNING)) { try { operation.run(); // depends on control dependency: [try], data = [none] pnky.resolve(null); // depends on control dependency: [try], data = [none] } catch (final Throwable e) { pnky.reject(e); } // depends on control dependency: [catch], data = [none] } } }); return pnky; } }
public class class_name { private void addQueryStringPair(String cleanKey, Object rawValue, StringBuilder queryStringBuilder) { // Serialize null values as an empty string. String valueAsString = rawValue == null ? "" : String.valueOf(rawValue); String cleanValue = this.url(valueAsString); if (queryStringBuilder.length() != 0) { queryStringBuilder.append(AND); } queryStringBuilder.append(cleanKey).append(EQUALS).append(cleanValue); } }
public class class_name { private void addQueryStringPair(String cleanKey, Object rawValue, StringBuilder queryStringBuilder) { // Serialize null values as an empty string. String valueAsString = rawValue == null ? "" : String.valueOf(rawValue); String cleanValue = this.url(valueAsString); if (queryStringBuilder.length() != 0) { queryStringBuilder.append(AND); // depends on control dependency: [if], data = [none] } queryStringBuilder.append(cleanKey).append(EQUALS).append(cleanValue); } }
public class class_name { protected List<CmsResource> allChangedInFolderDate( CmsObject cms, String param, boolean tree, boolean asc, int numResults) throws CmsException { Map<String, String> params = getParameters(param); String foldername = "/"; if (params.containsKey(PARAM_KEY_RESOURCE)) { foldername = CmsResource.getFolderPath(params.get(PARAM_KEY_RESOURCE)); } long dateFrom = 0L; long dateTo = Long.MAX_VALUE; if (params.containsKey(PARAM_KEY_DATEFROM)) { try { dateFrom = Long.parseLong(params.get(PARAM_KEY_DATEFROM)); } catch (NumberFormatException e) { // error parsing from date LOG.error( Messages.get().getBundle().key( Messages.ERR_COLLECTOR_PARAM_INVALID_1, PARAM_KEY_DATEFROM + "=" + params.get(PARAM_KEY_DATEFROM))); throw e; } } if (params.containsKey(PARAM_KEY_DATETO)) { try { dateTo = Long.parseLong(params.get(PARAM_KEY_DATETO)); } catch (NumberFormatException e) { // error parsing to date LOG.error( Messages.get().getBundle().key( Messages.ERR_COLLECTOR_PARAM_INVALID_1, PARAM_KEY_DATETO + "=" + params.get(PARAM_KEY_DATETO))); throw e; } } // create the filter to read the resources CmsResourceFilter filter = CmsResourceFilter.DEFAULT_FILES.addExcludeFlags( CmsResource.FLAG_TEMPFILE).addRequireLastModifiedAfter(dateFrom).addRequireLastModifiedBefore(dateTo); // check if a resource type has to be excluded if (params.containsKey(PARAM_KEY_EXCLUDETYPE)) { String excludeType = params.get(PARAM_KEY_EXCLUDETYPE); int typeId = -1; try { // try to look up the resource type I_CmsResourceType resourceType = OpenCms.getResourceManager().getResourceType(excludeType); typeId = resourceType.getTypeId(); } catch (CmsLoaderException e1) { // maybe the int ID is directly used? try { int typeInt = Integer.parseInt(excludeType); I_CmsResourceType resourceType = OpenCms.getResourceManager().getResourceType(typeInt); typeId = resourceType.getTypeId(); if (LOG.isWarnEnabled()) { LOG.warn( Messages.get().getBundle().key( Messages.LOG_RESTYPE_INTID_2, resourceType.getTypeName(), new Integer(resourceType.getTypeId()))); } } catch (NumberFormatException e2) { // bad number format used for type throw new CmsRuntimeException( Messages.get().container( Messages.ERR_COLLECTOR_PARAM_INVALID_1, PARAM_KEY_EXCLUDETYPE + "=" + params.get(PARAM_KEY_EXCLUDETYPE)), e2); } catch (CmsLoaderException e2) { // this resource type does not exist throw new CmsRuntimeException( Messages.get().container(Messages.ERR_UNKNOWN_RESTYPE_1, excludeType), e2); } } if (typeId != -1) { filter = filter.addExcludeType(typeId); } } // read the resources using the configured filter List<CmsResource> result = cms.readResources(foldername, filter, tree); // determine which attribute should be used to sort the result String sortBy = CmsDateResourceComparator.DATE_ATTRIBUTES_LIST.get(1); if (params.containsKey(PARAM_KEY_SORTBY)) { sortBy = params.get(PARAM_KEY_SORTBY); } List<String> dateIdentifiers = new ArrayList<String>(1); dateIdentifiers.add(sortBy); // a special date comparator is used to sort the resources CmsDateResourceComparator comparator = new CmsDateResourceComparator(cms, dateIdentifiers, asc); Collections.sort(result, comparator); int count = -1; if (params.containsKey(PARAM_KEY_COUNT)) { try { count = Integer.parseInt(params.get(PARAM_KEY_COUNT)); } catch (NumberFormatException e) { // error parsing the count LOG.error( Messages.get().getBundle().key( Messages.ERR_COLLECTOR_PARAM_INVALID_1, PARAM_KEY_COUNT + "=" + params.get(PARAM_KEY_COUNT))); throw e; } } if ((count > 0) || (numResults > 0)) { return shrinkToFit(result, count, numResults); } else { return result; } } }
public class class_name { protected List<CmsResource> allChangedInFolderDate( CmsObject cms, String param, boolean tree, boolean asc, int numResults) throws CmsException { Map<String, String> params = getParameters(param); String foldername = "/"; if (params.containsKey(PARAM_KEY_RESOURCE)) { foldername = CmsResource.getFolderPath(params.get(PARAM_KEY_RESOURCE)); } long dateFrom = 0L; long dateTo = Long.MAX_VALUE; if (params.containsKey(PARAM_KEY_DATEFROM)) { try { dateFrom = Long.parseLong(params.get(PARAM_KEY_DATEFROM)); // depends on control dependency: [try], data = [none] } catch (NumberFormatException e) { // error parsing from date LOG.error( Messages.get().getBundle().key( Messages.ERR_COLLECTOR_PARAM_INVALID_1, PARAM_KEY_DATEFROM + "=" + params.get(PARAM_KEY_DATEFROM))); throw e; } // depends on control dependency: [catch], data = [none] } if (params.containsKey(PARAM_KEY_DATETO)) { try { dateTo = Long.parseLong(params.get(PARAM_KEY_DATETO)); // depends on control dependency: [try], data = [none] } catch (NumberFormatException e) { // error parsing to date LOG.error( Messages.get().getBundle().key( Messages.ERR_COLLECTOR_PARAM_INVALID_1, PARAM_KEY_DATETO + "=" + params.get(PARAM_KEY_DATETO))); throw e; } // depends on control dependency: [catch], data = [none] } // create the filter to read the resources CmsResourceFilter filter = CmsResourceFilter.DEFAULT_FILES.addExcludeFlags( CmsResource.FLAG_TEMPFILE).addRequireLastModifiedAfter(dateFrom).addRequireLastModifiedBefore(dateTo); // check if a resource type has to be excluded if (params.containsKey(PARAM_KEY_EXCLUDETYPE)) { String excludeType = params.get(PARAM_KEY_EXCLUDETYPE); int typeId = -1; try { // try to look up the resource type I_CmsResourceType resourceType = OpenCms.getResourceManager().getResourceType(excludeType); typeId = resourceType.getTypeId(); // depends on control dependency: [try], data = [none] } catch (CmsLoaderException e1) { // maybe the int ID is directly used? try { int typeInt = Integer.parseInt(excludeType); I_CmsResourceType resourceType = OpenCms.getResourceManager().getResourceType(typeInt); typeId = resourceType.getTypeId(); // depends on control dependency: [try], data = [none] if (LOG.isWarnEnabled()) { LOG.warn( Messages.get().getBundle().key( Messages.LOG_RESTYPE_INTID_2, resourceType.getTypeName(), new Integer(resourceType.getTypeId()))); // depends on control dependency: [if], data = [none] } } catch (NumberFormatException e2) { // bad number format used for type throw new CmsRuntimeException( Messages.get().container( Messages.ERR_COLLECTOR_PARAM_INVALID_1, PARAM_KEY_EXCLUDETYPE + "=" + params.get(PARAM_KEY_EXCLUDETYPE)), e2); } catch (CmsLoaderException e2) { // depends on control dependency: [catch], data = [none] // this resource type does not exist throw new CmsRuntimeException( Messages.get().container(Messages.ERR_UNKNOWN_RESTYPE_1, excludeType), e2); } // depends on control dependency: [catch], data = [none] } // depends on control dependency: [catch], data = [none] if (typeId != -1) { filter = filter.addExcludeType(typeId); // depends on control dependency: [if], data = [(typeId] } } // read the resources using the configured filter List<CmsResource> result = cms.readResources(foldername, filter, tree); // determine which attribute should be used to sort the result String sortBy = CmsDateResourceComparator.DATE_ATTRIBUTES_LIST.get(1); if (params.containsKey(PARAM_KEY_SORTBY)) { sortBy = params.get(PARAM_KEY_SORTBY); } List<String> dateIdentifiers = new ArrayList<String>(1); dateIdentifiers.add(sortBy); // a special date comparator is used to sort the resources CmsDateResourceComparator comparator = new CmsDateResourceComparator(cms, dateIdentifiers, asc); Collections.sort(result, comparator); int count = -1; if (params.containsKey(PARAM_KEY_COUNT)) { try { count = Integer.parseInt(params.get(PARAM_KEY_COUNT)); // depends on control dependency: [try], data = [none] } catch (NumberFormatException e) { // error parsing the count LOG.error( Messages.get().getBundle().key( Messages.ERR_COLLECTOR_PARAM_INVALID_1, PARAM_KEY_COUNT + "=" + params.get(PARAM_KEY_COUNT))); throw e; } // depends on control dependency: [catch], data = [none] } if ((count > 0) || (numResults > 0)) { return shrinkToFit(result, count, numResults); } else { return result; } } }
public class class_name { public void close() { if (!isClosed) { isClosed = true; try { if (null != selectionKey) { selectionKey.cancel(); } if (null != transportPoller) { transportPoller.cancelRead(this); transportPoller.selectNowWithoutProcessing(); } if (null != sendDatagramChannel) { sendDatagramChannel.close(); } if (receiveDatagramChannel != sendDatagramChannel && null != receiveDatagramChannel) { receiveDatagramChannel.close(); } if (null != transportPoller) { transportPoller.selectNowWithoutProcessing(); } } catch (final IOException ex) { errorLog.record(ex); } } } }
public class class_name { public void close() { if (!isClosed) { isClosed = true; // depends on control dependency: [if], data = [none] try { if (null != selectionKey) { selectionKey.cancel(); // depends on control dependency: [if], data = [none] } if (null != transportPoller) { transportPoller.cancelRead(this); // depends on control dependency: [if], data = [none] transportPoller.selectNowWithoutProcessing(); // depends on control dependency: [if], data = [none] } if (null != sendDatagramChannel) { sendDatagramChannel.close(); // depends on control dependency: [if], data = [none] } if (receiveDatagramChannel != sendDatagramChannel && null != receiveDatagramChannel) { receiveDatagramChannel.close(); // depends on control dependency: [if], data = [none] } if (null != transportPoller) { transportPoller.selectNowWithoutProcessing(); // depends on control dependency: [if], data = [none] } } catch (final IOException ex) { errorLog.record(ex); } // depends on control dependency: [catch], data = [none] } } }
public class class_name { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ApplicationProcessor applicationProcessor = ApplicationProcessor.getInstance(); if (request.getMethod().equals(Constants.METHOD_GET)) { if (applicationProcessor == null) { Writer writer = response.getWriter(); writer.write("Failed to find OpenAPI application processor"); response.setStatus(404); } String acceptHeader = ""; acceptHeader = request.getHeader(Constants.ACCEPT_HEADER); String format = "yaml"; if (acceptHeader != null && acceptHeader.equals(MediaType.APPLICATION_JSON)) { format = "json"; } String formatParam = request.getParameter("format"); if (formatParam != null && formatParam.equals("json")) { format = "json"; } response.setCharacterEncoding("UTF-8"); if (format.equals("json")) { String document = applicationProcessor.getOpenAPIDocument(request, DocType.JSON); if (document != null) { response.setContentType(MediaType.APPLICATION_JSON); Writer writer = response.getWriter(); writer.write(document); } else { if (OpenAPIUtils.isEventEnabled(tc)) { Tr.event(this, tc, "Null document (json). Return 500."); } response.setStatus(500); } } else { String document = applicationProcessor.getOpenAPIDocument(request, DocType.YAML); if (document != null) { response.setContentType(MediaType.TEXT_PLAIN); Writer writer = response.getWriter(); writer.write(document); } else { if (OpenAPIUtils.isEventEnabled(tc)) { Tr.event(this, tc, "Null document (yaml). Return 500."); } response.setStatus(500); } } } else { if (OpenAPIUtils.isEventEnabled(tc)) { Tr.event(this, tc, "Invalid method. Return 405."); } response.setStatus(405); } } }
public class class_name { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ApplicationProcessor applicationProcessor = ApplicationProcessor.getInstance(); if (request.getMethod().equals(Constants.METHOD_GET)) { if (applicationProcessor == null) { Writer writer = response.getWriter(); writer.write("Failed to find OpenAPI application processor"); // depends on control dependency: [if], data = [none] response.setStatus(404); // depends on control dependency: [if], data = [none] } String acceptHeader = ""; acceptHeader = request.getHeader(Constants.ACCEPT_HEADER); String format = "yaml"; if (acceptHeader != null && acceptHeader.equals(MediaType.APPLICATION_JSON)) { format = "json"; // depends on control dependency: [if], data = [none] } String formatParam = request.getParameter("format"); if (formatParam != null && formatParam.equals("json")) { format = "json"; // depends on control dependency: [if], data = [none] } response.setCharacterEncoding("UTF-8"); if (format.equals("json")) { String document = applicationProcessor.getOpenAPIDocument(request, DocType.JSON); if (document != null) { response.setContentType(MediaType.APPLICATION_JSON); // depends on control dependency: [if], data = [none] Writer writer = response.getWriter(); writer.write(document); // depends on control dependency: [if], data = [(document] } else { if (OpenAPIUtils.isEventEnabled(tc)) { Tr.event(this, tc, "Null document (json). Return 500."); // depends on control dependency: [if], data = [none] } response.setStatus(500); // depends on control dependency: [if], data = [none] } } else { String document = applicationProcessor.getOpenAPIDocument(request, DocType.YAML); if (document != null) { response.setContentType(MediaType.TEXT_PLAIN); // depends on control dependency: [if], data = [none] Writer writer = response.getWriter(); writer.write(document); // depends on control dependency: [if], data = [(document] } else { if (OpenAPIUtils.isEventEnabled(tc)) { Tr.event(this, tc, "Null document (yaml). Return 500."); // depends on control dependency: [if], data = [none] } response.setStatus(500); // depends on control dependency: [if], data = [none] } } } else { if (OpenAPIUtils.isEventEnabled(tc)) { Tr.event(this, tc, "Invalid method. Return 405."); } response.setStatus(405); // depends on control dependency: [if], data = [none] } } }
public class class_name { public static boolean hasWonVoteOnFullCount(final ClusterMember[] members, final long candidateTermId) { int votes = 0; for (final ClusterMember member : members) { if (null == member.vote || member.candidateTermId != candidateTermId) { return false; } votes += member.vote ? 1 : 0; } return votes >= ClusterMember.quorumThreshold(members.length); } }
public class class_name { public static boolean hasWonVoteOnFullCount(final ClusterMember[] members, final long candidateTermId) { int votes = 0; for (final ClusterMember member : members) { if (null == member.vote || member.candidateTermId != candidateTermId) { return false; // depends on control dependency: [if], data = [none] } votes += member.vote ? 1 : 0; // depends on control dependency: [for], data = [member] } return votes >= ClusterMember.quorumThreshold(members.length); } }
public class class_name { public void marshall(CreateDocumentRequest createDocumentRequest, ProtocolMarshaller protocolMarshaller) { if (createDocumentRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(createDocumentRequest.getContent(), CONTENT_BINDING); protocolMarshaller.marshall(createDocumentRequest.getAttachments(), ATTACHMENTS_BINDING); protocolMarshaller.marshall(createDocumentRequest.getName(), NAME_BINDING); protocolMarshaller.marshall(createDocumentRequest.getVersionName(), VERSIONNAME_BINDING); protocolMarshaller.marshall(createDocumentRequest.getDocumentType(), DOCUMENTTYPE_BINDING); protocolMarshaller.marshall(createDocumentRequest.getDocumentFormat(), DOCUMENTFORMAT_BINDING); protocolMarshaller.marshall(createDocumentRequest.getTargetType(), TARGETTYPE_BINDING); protocolMarshaller.marshall(createDocumentRequest.getTags(), TAGS_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
public class class_name { public void marshall(CreateDocumentRequest createDocumentRequest, ProtocolMarshaller protocolMarshaller) { if (createDocumentRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(createDocumentRequest.getContent(), CONTENT_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(createDocumentRequest.getAttachments(), ATTACHMENTS_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(createDocumentRequest.getName(), NAME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(createDocumentRequest.getVersionName(), VERSIONNAME_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(createDocumentRequest.getDocumentType(), DOCUMENTTYPE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(createDocumentRequest.getDocumentFormat(), DOCUMENTFORMAT_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(createDocumentRequest.getTargetType(), TARGETTYPE_BINDING); // depends on control dependency: [try], data = [none] protocolMarshaller.marshall(createDocumentRequest.getTags(), TAGS_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 List<AbstractPlugin> getActiveScanRules () { ArrayList<AbstractPlugin> list = new ArrayList<>(); for (AddOn addOn : getAddOnCollection().getAddOns()) { AddOnClassLoader addOnClassLoader = this.addOnLoaders.get(addOn.getId()); if (addOnClassLoader != null) { list.addAll(AddOnLoaderUtils.getActiveScanRules(addOn, addOnClassLoader)); } } list.trimToSize(); return Collections.unmodifiableList(list); } }
public class class_name { public List<AbstractPlugin> getActiveScanRules () { ArrayList<AbstractPlugin> list = new ArrayList<>(); for (AddOn addOn : getAddOnCollection().getAddOns()) { AddOnClassLoader addOnClassLoader = this.addOnLoaders.get(addOn.getId()); if (addOnClassLoader != null) { list.addAll(AddOnLoaderUtils.getActiveScanRules(addOn, addOnClassLoader)); // depends on control dependency: [if], data = [none] } } list.trimToSize(); return Collections.unmodifiableList(list); } }
public class class_name { public static OWLValueObject buildAsResultFromObject(OWLModel model, Object object) throws NotYetImplementedException, OWLTranslationException { if (ObjectOWLSTranslator.isJenaBean(object)) { try { return new OWLValueObject( model, OWLURIClass.from(object), model.createResult(new URI(ObjectOWLSTranslator.beanToJenaResource(model, object).getURI()))); } catch (URISyntaxException ex) { throw new OWLTranslationException("translating to Jena: " + object.toString(), ex); } } throw new NotYetImplementedException("fail to build new " + OWLValueObject.class.toString() + " from a non JenaBeans compliant object: " + object.toString()); } }
public class class_name { public static OWLValueObject buildAsResultFromObject(OWLModel model, Object object) throws NotYetImplementedException, OWLTranslationException { if (ObjectOWLSTranslator.isJenaBean(object)) { try { return new OWLValueObject( model, OWLURIClass.from(object), model.createResult(new URI(ObjectOWLSTranslator.beanToJenaResource(model, object).getURI()))); // depends on control dependency: [try], data = [none] } catch (URISyntaxException ex) { throw new OWLTranslationException("translating to Jena: " + object.toString(), ex); } // depends on control dependency: [catch], data = [none] } throw new NotYetImplementedException("fail to build new " + OWLValueObject.class.toString() + " from a non JenaBeans compliant object: " + object.toString()); } }
public class class_name { public void onCreate(Bundle savedInstanceState) { Session session = Session.getActiveSession(); if (session == null) { if (savedInstanceState != null) { session = Session.restoreSession(activity, null, callback, savedInstanceState); } if (session == null) { session = new Session(activity); } Session.setActiveSession(session); } if (savedInstanceState != null) { pendingFacebookDialogCall = savedInstanceState.getParcelable(DIALOG_CALL_BUNDLE_SAVE_KEY); } } }
public class class_name { public void onCreate(Bundle savedInstanceState) { Session session = Session.getActiveSession(); if (session == null) { if (savedInstanceState != null) { session = Session.restoreSession(activity, null, callback, savedInstanceState); // depends on control dependency: [if], data = [none] } if (session == null) { session = new Session(activity); // depends on control dependency: [if], data = [none] } Session.setActiveSession(session); // depends on control dependency: [if], data = [(session] } if (savedInstanceState != null) { pendingFacebookDialogCall = savedInstanceState.getParcelable(DIALOG_CALL_BUNDLE_SAVE_KEY); // depends on control dependency: [if], data = [none] } } }
public class class_name { @Override public void contextInitialized(ServletContextEvent sce) { ServletContext context = sce.getServletContext(); String propertiesConfig = context.getInitParameter(PROPERTIES_CONFIG); if(propertiesConfig == null) { propertiesConfig = PROPERTIES_CONFIG_DEFAULT; } SystemProperties config = loadConfiguration(propertiesConfig, context); addProperties(config); if(config.getFile() != null) { addPropertiesFromFile(config, context); } } }
public class class_name { @Override public void contextInitialized(ServletContextEvent sce) { ServletContext context = sce.getServletContext(); String propertiesConfig = context.getInitParameter(PROPERTIES_CONFIG); if(propertiesConfig == null) { propertiesConfig = PROPERTIES_CONFIG_DEFAULT; // depends on control dependency: [if], data = [none] } SystemProperties config = loadConfiguration(propertiesConfig, context); addProperties(config); if(config.getFile() != null) { addPropertiesFromFile(config, context); // depends on control dependency: [if], data = [none] } } }
public class class_name { public StrBuilder insert(int index, Object obj) { if (obj instanceof CharSequence) { return insert(index, (CharSequence) obj); } return insert(index, Convert.toStr(obj)); } }
public class class_name { public StrBuilder insert(int index, Object obj) { if (obj instanceof CharSequence) { return insert(index, (CharSequence) obj); // depends on control dependency: [if], data = [none] } return insert(index, Convert.toStr(obj)); } }
public class class_name { public EClass getGEPROL() { if (geprolEClass == null) { geprolEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(448); } return geprolEClass; } }
public class class_name { public EClass getGEPROL() { if (geprolEClass == null) { geprolEClass = (EClass)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(448); // depends on control dependency: [if], data = [none] } return geprolEClass; } }
public class class_name { public RowResultSet<R> resultSet(int maxRows) { if (maxRows <= 0) { return new RowResultSet<R>(getRows()); } // end of if return new RowResultSet<R>(getRows().subList(0, maxRows)); } }
public class class_name { public RowResultSet<R> resultSet(int maxRows) { if (maxRows <= 0) { return new RowResultSet<R>(getRows()); // depends on control dependency: [if], data = [none] } // end of if return new RowResultSet<R>(getRows().subList(0, maxRows)); } }
public class class_name { public final void updateTableHeads(final Element root) { final Iterable<Element> tableHeadRows; // Heads to fix Element table; // HTML table Element thead; // Table's head for wrapping checkNotNull(root, "Received a null pointer as root element"); // Table rows with <th> tags in a <tbody> tableHeadRows = root.select("table > tbody > tr:has(th)"); for (final Element row : tableHeadRows) { // Gets the row's table // The selector ensured the row is inside a tbody table = row.parent().parent(); // Removes the row from its original position row.remove(); // Creates a table header element with the row thead = new Element(Tag.valueOf("thead"), ""); thead.appendChild(row); // Adds the head at the beginning of the table table.prependChild(thead); } } }
public class class_name { public final void updateTableHeads(final Element root) { final Iterable<Element> tableHeadRows; // Heads to fix Element table; // HTML table Element thead; // Table's head for wrapping checkNotNull(root, "Received a null pointer as root element"); // Table rows with <th> tags in a <tbody> tableHeadRows = root.select("table > tbody > tr:has(th)"); for (final Element row : tableHeadRows) { // Gets the row's table // The selector ensured the row is inside a tbody table = row.parent().parent(); // depends on control dependency: [for], data = [row] // Removes the row from its original position row.remove(); // depends on control dependency: [for], data = [row] // Creates a table header element with the row thead = new Element(Tag.valueOf("thead"), ""); // depends on control dependency: [for], data = [none] thead.appendChild(row); // depends on control dependency: [for], data = [row] // Adds the head at the beginning of the table table.prependChild(thead); // depends on control dependency: [for], data = [none] } } }
public class class_name { public static <R> R tryToExecute( final UnsafeSupplier<R> supplier, final Eid eid ) { try { return supplier.get(); } catch (Exception throwable) { throw new EidRuntimeException(ensureEid(eid), throwable); } } }
public class class_name { public static <R> R tryToExecute( final UnsafeSupplier<R> supplier, final Eid eid ) { try { return supplier.get(); // depends on control dependency: [try], data = [none] } catch (Exception throwable) { throw new EidRuntimeException(ensureEid(eid), throwable); } // depends on control dependency: [catch], data = [none] } }
public class class_name { @ResponseBody @RequestMapping(value = "/filetext/{configId}", method = RequestMethod.PUT) public JsonObjectBase updateFileWithText(@PathVariable long configId, @NotNull String fileContent) { // // 更新 // String emailNotification = ""; try { String str = new String(fileContent.getBytes(), "UTF-8"); LOG.info("receive file: " + str); emailNotification = configMgr.updateItemValue(configId, str); LOG.info("update " + configId + " ok"); } catch (Exception e) { throw new FileUploadException("upload.file.error", e); } // // 通知ZK // configMgr.notifyZookeeper(configId); return buildSuccess(emailNotification); } }
public class class_name { @ResponseBody @RequestMapping(value = "/filetext/{configId}", method = RequestMethod.PUT) public JsonObjectBase updateFileWithText(@PathVariable long configId, @NotNull String fileContent) { // // 更新 // String emailNotification = ""; try { String str = new String(fileContent.getBytes(), "UTF-8"); LOG.info("receive file: " + str); // depends on control dependency: [try], data = [none] emailNotification = configMgr.updateItemValue(configId, str); // depends on control dependency: [try], data = [none] LOG.info("update " + configId + " ok"); // depends on control dependency: [try], data = [none] } catch (Exception e) { throw new FileUploadException("upload.file.error", e); } // depends on control dependency: [catch], data = [none] // // 通知ZK // configMgr.notifyZookeeper(configId); return buildSuccess(emailNotification); } }
public class class_name { public void update(final Memory mem) { if (mem == null) { return; } ReservoirLongsSketch rls = ReservoirLongsSketch.heapify(mem); rls = (rls.getK() <= maxK_ ? rls : rls.downsampledCopy(maxK_)); if (gadget_ == null) { createNewGadget(rls, true); } else { twoWayMergeInternal(rls, true); } } }
public class class_name { public void update(final Memory mem) { if (mem == null) { return; // depends on control dependency: [if], data = [none] } ReservoirLongsSketch rls = ReservoirLongsSketch.heapify(mem); rls = (rls.getK() <= maxK_ ? rls : rls.downsampledCopy(maxK_)); if (gadget_ == null) { createNewGadget(rls, true); // depends on control dependency: [if], data = [none] } else { twoWayMergeInternal(rls, true); // depends on control dependency: [if], data = [none] } } }
public class class_name { @Override protected void readResponse(HttpState state, HttpConnection conn) throws IOException, HttpException { LOG.trace("enter HttpMethodBase.readResponse(HttpState, HttpConnection)"); boolean isUpgrade = false; while (getStatusLine() == null) { readStatusLine(state, conn); processStatusLine(state, conn); readResponseHeaders(state, conn); processResponseHeaders(state, conn); int status = this.statusLine.getStatusCode(); if (status == 101) { LOG.debug("Retrieved HTTP status code '101 Switching Protocols'. Keep connection open!"); // This means the requester has asked the server to switch protocols // and the server is acknowledging that it will do so // e.g.: upgrade to websocket if (conn instanceof ZapHttpConnection) { isUpgrade = true; // avoid connection release of HttpClient library conn.setHttpConnectionManager(null); } } else if ((status >= 100) && (status < 200)) { if (LOG.isInfoEnabled()) { LOG.info("Discarding unexpected response: " + this.statusLine.toString()); } this.statusLine = null; } } // get socket and input stream out of HttpClient if (conn instanceof ZapHttpConnection) { ZapHttpConnection zapConn = (ZapHttpConnection) conn; upgradedSocket = zapConn.getSocket(); inputStream = zapConn.getResponseInputStream(); } if (!isUpgrade) { // read & process rest of response // only if connection should not be kept readResponseBody(state, conn); processResponseBody(state, conn); } } }
public class class_name { @Override protected void readResponse(HttpState state, HttpConnection conn) throws IOException, HttpException { LOG.trace("enter HttpMethodBase.readResponse(HttpState, HttpConnection)"); boolean isUpgrade = false; while (getStatusLine() == null) { readStatusLine(state, conn); processStatusLine(state, conn); readResponseHeaders(state, conn); processResponseHeaders(state, conn); int status = this.statusLine.getStatusCode(); if (status == 101) { LOG.debug("Retrieved HTTP status code '101 Switching Protocols'. Keep connection open!"); // This means the requester has asked the server to switch protocols // and the server is acknowledging that it will do so // e.g.: upgrade to websocket if (conn instanceof ZapHttpConnection) { isUpgrade = true; // depends on control dependency: [if], data = [none] // avoid connection release of HttpClient library conn.setHttpConnectionManager(null); // depends on control dependency: [if], data = [none] } } else if ((status >= 100) && (status < 200)) { if (LOG.isInfoEnabled()) { LOG.info("Discarding unexpected response: " + this.statusLine.toString()); } this.statusLine = null; } } // get socket and input stream out of HttpClient if (conn instanceof ZapHttpConnection) { ZapHttpConnection zapConn = (ZapHttpConnection) conn; upgradedSocket = zapConn.getSocket(); inputStream = zapConn.getResponseInputStream(); } if (!isUpgrade) { // read & process rest of response // only if connection should not be kept readResponseBody(state, conn); processResponseBody(state, conn); } } }
public class class_name { private static NitDesc nitDescFromDynamic(DynamicInstantiatable d){ NitDesc nd = new NitDesc(); nd.setScript(d.getScript()); nd.setTheClass(d.getTheClass()); if (d.getSpec() == null || "java".equals(d.getSpec())){ nd.setSpec(NitDesc.NitSpec.JAVA_LOCAL_CLASSPATH); } else if ("groovy".equals(d.getSpec())){ nd.setSpec(NitDesc.NitSpec.GROOVY_CLASS_LOADER); } else if ("groovyclosure".equals(d.getSpec())){ nd.setSpec(NitDesc.NitSpec.GROOVY_CLOSURE); } else if ("url".equals(d.getSpec())){ nd.setSpec(NitDesc.NitSpec.JAVA_URL_CLASSLOADER); } else { nd.setSpec(NitDesc.NitSpec.valueOf(d.getSpec())); } return nd; } }
public class class_name { private static NitDesc nitDescFromDynamic(DynamicInstantiatable d){ NitDesc nd = new NitDesc(); nd.setScript(d.getScript()); nd.setTheClass(d.getTheClass()); if (d.getSpec() == null || "java".equals(d.getSpec())){ nd.setSpec(NitDesc.NitSpec.JAVA_LOCAL_CLASSPATH); // depends on control dependency: [if], data = [none] } else if ("groovy".equals(d.getSpec())){ nd.setSpec(NitDesc.NitSpec.GROOVY_CLASS_LOADER); // depends on control dependency: [if], data = [none] } else if ("groovyclosure".equals(d.getSpec())){ nd.setSpec(NitDesc.NitSpec.GROOVY_CLOSURE); // depends on control dependency: [if], data = [none] } else if ("url".equals(d.getSpec())){ nd.setSpec(NitDesc.NitSpec.JAVA_URL_CLASSLOADER); // depends on control dependency: [if], data = [none] } else { nd.setSpec(NitDesc.NitSpec.valueOf(d.getSpec())); // depends on control dependency: [if], data = [none] } return nd; } }
public class class_name { public void setImageDetails(java.util.Collection<ImageDetail> imageDetails) { if (imageDetails == null) { this.imageDetails = null; return; } this.imageDetails = new java.util.ArrayList<ImageDetail>(imageDetails); } }
public class class_name { public void setImageDetails(java.util.Collection<ImageDetail> imageDetails) { if (imageDetails == null) { this.imageDetails = null; // depends on control dependency: [if], data = [none] return; // depends on control dependency: [if], data = [none] } this.imageDetails = new java.util.ArrayList<ImageDetail>(imageDetails); } }
public class class_name { @Override public DescriptorValue calculate(IAtomContainer atomContainer) { if (!GeometryUtil.has3DCoordinates(atomContainer)) return getDummyDescriptorValue(new CDKException("Molecule must have 3D coordinates")); double angle = 10.0; double maxLOB = 0; double minArea = 1e6; double mmLOB = 0; double lob, bol, area; double[] xyzRanges; double[][] coords = new double[atomContainer.getAtomCount()][3]; for (int i = 0; i < atomContainer.getAtomCount(); i++) { coords[i][0] = atomContainer.getAtom(i).getPoint3d().x; coords[i][1] = atomContainer.getAtom(i).getPoint3d().y; coords[i][2] = atomContainer.getAtom(i).getPoint3d().z; } // get the com Point3d com = GeometryUtil.get3DCentreOfMass(atomContainer); if (com == null) return getDummyDescriptorValue(new CDKException("Error in center of mass calculation, has exact mass been set on all atoms?")); // translate everything to COM for (int i = 0; i < coords.length; i++) { coords[i][0] -= com.x; coords[i][1] -= com.y; coords[i][2] -= com.z; } int nangle = (int) (90 / angle); for (int i = 0; i < nangle; i++) { rotateZ(coords, Math.PI / 180.0 * angle); try { xyzRanges = extents(atomContainer, coords, true); } catch (CDKException e) { return getDummyDescriptorValue(e); } lob = xyzRanges[0] / xyzRanges[1]; bol = 1.0 / lob; if (lob < bol) { double tmp = lob; lob = bol; bol = tmp; } area = xyzRanges[0] * xyzRanges[1]; if (lob > maxLOB) maxLOB = lob; if (area < minArea) { minArea = area; mmLOB = lob; } } DoubleArrayResult result = new DoubleArrayResult(2); result.add(maxLOB); result.add(mmLOB); return new DescriptorValue(getSpecification(), getParameterNames(), getParameters(), result, getDescriptorNames()); } }
public class class_name { @Override public DescriptorValue calculate(IAtomContainer atomContainer) { if (!GeometryUtil.has3DCoordinates(atomContainer)) return getDummyDescriptorValue(new CDKException("Molecule must have 3D coordinates")); double angle = 10.0; double maxLOB = 0; double minArea = 1e6; double mmLOB = 0; double lob, bol, area; double[] xyzRanges; double[][] coords = new double[atomContainer.getAtomCount()][3]; for (int i = 0; i < atomContainer.getAtomCount(); i++) { coords[i][0] = atomContainer.getAtom(i).getPoint3d().x; // depends on control dependency: [for], data = [i] coords[i][1] = atomContainer.getAtom(i).getPoint3d().y; // depends on control dependency: [for], data = [i] coords[i][2] = atomContainer.getAtom(i).getPoint3d().z; // depends on control dependency: [for], data = [i] } // get the com Point3d com = GeometryUtil.get3DCentreOfMass(atomContainer); if (com == null) return getDummyDescriptorValue(new CDKException("Error in center of mass calculation, has exact mass been set on all atoms?")); // translate everything to COM for (int i = 0; i < coords.length; i++) { coords[i][0] -= com.x; // depends on control dependency: [for], data = [i] coords[i][1] -= com.y; // depends on control dependency: [for], data = [i] coords[i][2] -= com.z; // depends on control dependency: [for], data = [i] } int nangle = (int) (90 / angle); for (int i = 0; i < nangle; i++) { rotateZ(coords, Math.PI / 180.0 * angle); // depends on control dependency: [for], data = [none] try { xyzRanges = extents(atomContainer, coords, true); // depends on control dependency: [try], data = [none] } catch (CDKException e) { return getDummyDescriptorValue(e); } // depends on control dependency: [catch], data = [none] lob = xyzRanges[0] / xyzRanges[1]; // depends on control dependency: [for], data = [none] bol = 1.0 / lob; // depends on control dependency: [for], data = [none] if (lob < bol) { double tmp = lob; lob = bol; // depends on control dependency: [if], data = [none] bol = tmp; // depends on control dependency: [if], data = [none] } area = xyzRanges[0] * xyzRanges[1]; // depends on control dependency: [for], data = [none] if (lob > maxLOB) maxLOB = lob; if (area < minArea) { minArea = area; // depends on control dependency: [if], data = [none] mmLOB = lob; // depends on control dependency: [if], data = [none] } } DoubleArrayResult result = new DoubleArrayResult(2); result.add(maxLOB); result.add(mmLOB); return new DescriptorValue(getSpecification(), getParameterNames(), getParameters(), result, getDescriptorNames()); } }
public class class_name { private static boolean processPositionalVariation(CharIter iter, CxSmilesState state) { if (state.positionVar == null) state.positionVar = new TreeMap<>(); while (iter.hasNext()) { if (isDigit(iter.curr())) { final int beg = processUnsignedInt(iter); if (!iter.nextIf(':')) return false; List<Integer> endpoints = new ArrayList<>(6); if (!processIntList(iter, DOT_SEPARATOR, endpoints)) return false; iter.nextIf(','); state.positionVar.put(beg, endpoints); } else { return true; } } return false; } }
public class class_name { private static boolean processPositionalVariation(CharIter iter, CxSmilesState state) { if (state.positionVar == null) state.positionVar = new TreeMap<>(); while (iter.hasNext()) { if (isDigit(iter.curr())) { final int beg = processUnsignedInt(iter); if (!iter.nextIf(':')) return false; List<Integer> endpoints = new ArrayList<>(6); if (!processIntList(iter, DOT_SEPARATOR, endpoints)) return false; iter.nextIf(','); // depends on control dependency: [if], data = [none] state.positionVar.put(beg, endpoints); // depends on control dependency: [if], data = [none] } else { return true; // depends on control dependency: [if], data = [none] } } return false; } }
public class class_name { protected String[] getColumnClasses(PanelGrid panelGrid, int[] colSpans) { String columnsCSV = panelGrid.getColumnClasses(); String[] columnClasses; if (null == columnsCSV || columnsCSV.trim().length()==0) columnClasses = null; else { columnClasses = columnsCSV.split(","); if (columnClasses.length > colSpans.length) { throw new FacesException("PanelGrid: You defined more columnClasses than columns or colSpans"); } } String size = panelGrid.getSize(); if (null == size || size.trim().equals("")) { size = "lg"; } else { size = Responsive.translateSize(size, true); } String[] result = new String[colSpans.length]; for (int i = 0; i < colSpans.length; i++) { if (columnClasses == null) { result[i] = "col-" + size + "-" + colSpans[i]; } else { String current = columnClasses[i % columnClasses.length]; if (current.contains("col-")) { result[i] = current; } else { result[i] = "col-" + size + "-" + colSpans[i] + " " + current; } } } return result; } }
public class class_name { protected String[] getColumnClasses(PanelGrid panelGrid, int[] colSpans) { String columnsCSV = panelGrid.getColumnClasses(); String[] columnClasses; if (null == columnsCSV || columnsCSV.trim().length()==0) columnClasses = null; else { columnClasses = columnsCSV.split(","); // depends on control dependency: [if], data = [none] if (columnClasses.length > colSpans.length) { throw new FacesException("PanelGrid: You defined more columnClasses than columns or colSpans"); } } String size = panelGrid.getSize(); if (null == size || size.trim().equals("")) { size = "lg"; // depends on control dependency: [if], data = [none] } else { size = Responsive.translateSize(size, true); // depends on control dependency: [if], data = [none] } String[] result = new String[colSpans.length]; for (int i = 0; i < colSpans.length; i++) { if (columnClasses == null) { result[i] = "col-" + size + "-" + colSpans[i]; // depends on control dependency: [if], data = [none] } else { String current = columnClasses[i % columnClasses.length]; if (current.contains("col-")) { result[i] = current; // depends on control dependency: [if], data = [none] } else { result[i] = "col-" + size + "-" + colSpans[i] + " " + current; // depends on control dependency: [if], data = [none] } } } return result; } }
public class class_name { public static String longToString(long longValue, boolean noCase) { char[] digits = noCase ? DIGITS_NOCASE : DIGITS; int digitsLength = digits.length; if (longValue == 0) { return String.valueOf(digits[0]); } if (longValue < 0) { longValue = -longValue; } StringBuilder strValue = new StringBuilder(); while (longValue != 0) { int digit = (int) (longValue % digitsLength); longValue = longValue / digitsLength; strValue.append(digits[digit]); } return strValue.toString(); } }
public class class_name { public static String longToString(long longValue, boolean noCase) { char[] digits = noCase ? DIGITS_NOCASE : DIGITS; int digitsLength = digits.length; if (longValue == 0) { return String.valueOf(digits[0]); // depends on control dependency: [if], data = [none] } if (longValue < 0) { longValue = -longValue; // depends on control dependency: [if], data = [none] } StringBuilder strValue = new StringBuilder(); while (longValue != 0) { int digit = (int) (longValue % digitsLength); longValue = longValue / digitsLength; // depends on control dependency: [while], data = [none] strValue.append(digits[digit]); // depends on control dependency: [while], data = [none] } return strValue.toString(); } }
public class class_name { private <T extends ProgramElementDoc> void mapAnnotations(Map<String,List<T>> map, Object doc, T holder) { AnnotationDesc[] annotations; boolean isPackage = false; if (doc instanceof ProgramElementDoc) { annotations = ((ProgramElementDoc) doc).annotations(); } else if (doc instanceof PackageDoc) { annotations = ((PackageDoc) doc).annotations(); isPackage = true; } else if (doc instanceof Parameter) { annotations = ((Parameter) doc).annotations(); } else { throw new DocletAbortException("should not happen"); } for (AnnotationDesc annotation : annotations) { AnnotationTypeDoc annotationDoc = annotation.annotationType(); if (isPackage) refList(map, annotationDoc).add(holder); else add(map, annotationDoc, holder); } } }
public class class_name { private <T extends ProgramElementDoc> void mapAnnotations(Map<String,List<T>> map, Object doc, T holder) { AnnotationDesc[] annotations; boolean isPackage = false; if (doc instanceof ProgramElementDoc) { annotations = ((ProgramElementDoc) doc).annotations(); // depends on control dependency: [if], data = [none] } else if (doc instanceof PackageDoc) { annotations = ((PackageDoc) doc).annotations(); // depends on control dependency: [if], data = [none] isPackage = true; // depends on control dependency: [if], data = [none] } else if (doc instanceof Parameter) { annotations = ((Parameter) doc).annotations(); // depends on control dependency: [if], data = [none] } else { throw new DocletAbortException("should not happen"); } for (AnnotationDesc annotation : annotations) { AnnotationTypeDoc annotationDoc = annotation.annotationType(); if (isPackage) refList(map, annotationDoc).add(holder); else add(map, annotationDoc, holder); } } }
public class class_name { public void setStartFolder(String folder) { if (!folder.startsWith("/")) { folder = "/" + folder; } if (!folder.endsWith("/")) { folder = folder + "/"; } m_startFolder = folder; } }
public class class_name { public void setStartFolder(String folder) { if (!folder.startsWith("/")) { folder = "/" + folder; // depends on control dependency: [if], data = [none] } if (!folder.endsWith("/")) { folder = folder + "/"; // depends on control dependency: [if], data = [none] } m_startFolder = folder; } }
public class class_name { public static void localiseButton(AbstractButton button, String key, String defaultString, boolean setMnemonic) { AnnotatedString as = new AnnotatedString(L10N.getLocalString(key, defaultString)); button.setText(as.toString()); int mnemonic; if (setMnemonic && (mnemonic = as.getMnemonic()) != KeyEvent.VK_UNDEFINED) { button.setMnemonic(mnemonic); button.setDisplayedMnemonicIndex(as.getMnemonicIndex()); } } }
public class class_name { public static void localiseButton(AbstractButton button, String key, String defaultString, boolean setMnemonic) { AnnotatedString as = new AnnotatedString(L10N.getLocalString(key, defaultString)); button.setText(as.toString()); int mnemonic; if (setMnemonic && (mnemonic = as.getMnemonic()) != KeyEvent.VK_UNDEFINED) { button.setMnemonic(mnemonic); // depends on control dependency: [if], data = [none] button.setDisplayedMnemonicIndex(as.getMnemonicIndex()); // depends on control dependency: [if], data = [none] } } }
public class class_name { private static String getRegEx(int position, String... options) { String value = "" + position; for (int i = 0; i < options.length; i++) { value += "," + options[i]; } return "{" + value + "}"; } }
public class class_name { private static String getRegEx(int position, String... options) { String value = "" + position; for (int i = 0; i < options.length; i++) { value += "," + options[i]; // depends on control dependency: [for], data = [i] } return "{" + value + "}"; } }
public class class_name { void notifyStateTransition(Execution execution, ExecutionState newState, Throwable error) { // only forward this notification if the execution is still the current execution // otherwise we have an outdated execution if (currentExecution == execution) { getExecutionGraph().notifyExecutionChange(execution, newState, error); } } }
public class class_name { void notifyStateTransition(Execution execution, ExecutionState newState, Throwable error) { // only forward this notification if the execution is still the current execution // otherwise we have an outdated execution if (currentExecution == execution) { getExecutionGraph().notifyExecutionChange(execution, newState, error); // depends on control dependency: [if], data = [none] } } }
public class class_name { @SuppressWarnings("BooleanMethodIsAlwaysInverted") public boolean canDeleteSelection(int beforeLength) { if (getObjects().size() < 1) return true; // if beforeLength is 1, we either have no selection or the call is coming from OnKey Event. // In these scenarios, getSelectionStart() will return the correct value. int endSelection = getSelectionEnd(); int startSelection = beforeLength == 1 ? getSelectionStart() : endSelection - beforeLength; Editable text = getText(); TokenImageSpan[] spans = text.getSpans(0, text.length(), TokenImageSpan.class); // Iterate over all tokens and allow the deletion // if there are no tokens not removable in the selection for (TokenImageSpan span : spans) { int startTokenSelection = text.getSpanStart(span); int endTokenSelection = text.getSpanEnd(span); // moving on, no need to check this token if (isTokenRemovable(span.token)) continue; if (startSelection == endSelection) { // Delete single if (endTokenSelection + 1 == endSelection) { return false; } } else { // Delete range // Don't delete if a non removable token is in range if (startSelection <= startTokenSelection && endTokenSelection + 1 <= endSelection) { return false; } } } return true; } }
public class class_name { @SuppressWarnings("BooleanMethodIsAlwaysInverted") public boolean canDeleteSelection(int beforeLength) { if (getObjects().size() < 1) return true; // if beforeLength is 1, we either have no selection or the call is coming from OnKey Event. // In these scenarios, getSelectionStart() will return the correct value. int endSelection = getSelectionEnd(); int startSelection = beforeLength == 1 ? getSelectionStart() : endSelection - beforeLength; Editable text = getText(); TokenImageSpan[] spans = text.getSpans(0, text.length(), TokenImageSpan.class); // Iterate over all tokens and allow the deletion // if there are no tokens not removable in the selection for (TokenImageSpan span : spans) { int startTokenSelection = text.getSpanStart(span); int endTokenSelection = text.getSpanEnd(span); // moving on, no need to check this token if (isTokenRemovable(span.token)) continue; if (startSelection == endSelection) { // Delete single if (endTokenSelection + 1 == endSelection) { return false; // depends on control dependency: [if], data = [none] } } else { // Delete range // Don't delete if a non removable token is in range if (startSelection <= startTokenSelection && endTokenSelection + 1 <= endSelection) { return false; // depends on control dependency: [if], data = [none] } } } return true; } }
public class class_name { public WebTarget appendPathAndQueryParameters(final WebTarget webTarget) { ArgumentChecker.notNull(webTarget, "webTarget"); WebTarget resultTarget = webTarget; resultTarget = resultTarget.path(DATASETS_RELATIVE_URL + EXTENSION); if (_databaseCode != null) { resultTarget = resultTarget.queryParam(DATABASE_CODE_PARAM, _databaseCode); } if (_query != null) { resultTarget = resultTarget.queryParam(QUERY_PARAM, _query); } if (_pageNumber != null) { resultTarget = resultTarget.queryParam(PAGE_PARAM, _pageNumber); } if (_maxDocsPerPage != null) { resultTarget = resultTarget.queryParam(PER_PAGE_PARAM, _maxDocsPerPage); } return resultTarget; } }
public class class_name { public WebTarget appendPathAndQueryParameters(final WebTarget webTarget) { ArgumentChecker.notNull(webTarget, "webTarget"); WebTarget resultTarget = webTarget; resultTarget = resultTarget.path(DATASETS_RELATIVE_URL + EXTENSION); if (_databaseCode != null) { resultTarget = resultTarget.queryParam(DATABASE_CODE_PARAM, _databaseCode); // depends on control dependency: [if], data = [none] } if (_query != null) { resultTarget = resultTarget.queryParam(QUERY_PARAM, _query); // depends on control dependency: [if], data = [none] } if (_pageNumber != null) { resultTarget = resultTarget.queryParam(PAGE_PARAM, _pageNumber); // depends on control dependency: [if], data = [none] } if (_maxDocsPerPage != null) { resultTarget = resultTarget.queryParam(PER_PAGE_PARAM, _maxDocsPerPage); // depends on control dependency: [if], data = [none] } return resultTarget; } }
public class class_name { public static Duration getInstance(String dur, NumberFormat format, Locale locale) throws MPXJException { try { int lastIndex = dur.length() - 1; int index = lastIndex; double duration; TimeUnit units; while ((index > 0) && (Character.isDigit(dur.charAt(index)) == false)) { --index; } // // If we have no units suffix, assume days to allow for MPX3 // if (index == lastIndex) { duration = format.parse(dur).doubleValue(); units = TimeUnit.DAYS; } else { ++index; duration = format.parse(dur.substring(0, index)).doubleValue(); while ((index < lastIndex) && (Character.isWhitespace(dur.charAt(index)))) { ++index; } units = TimeUnitUtility.getInstance(dur.substring(index), locale); } return (Duration.getInstance(duration, units)); } catch (ParseException ex) { throw new MPXJException("Failed to parse duration", ex); } } }
public class class_name { public static Duration getInstance(String dur, NumberFormat format, Locale locale) throws MPXJException { try { int lastIndex = dur.length() - 1; int index = lastIndex; double duration; TimeUnit units; while ((index > 0) && (Character.isDigit(dur.charAt(index)) == false)) { --index; } // // If we have no units suffix, assume days to allow for MPX3 // if (index == lastIndex) { duration = format.parse(dur).doubleValue(); units = TimeUnit.DAYS; } else { ++index; duration = format.parse(dur.substring(0, index)).doubleValue(); while ((index < lastIndex) && (Character.isWhitespace(dur.charAt(index)))) { ++index; // depends on control dependency: [while], data = [none] } units = TimeUnitUtility.getInstance(dur.substring(index), locale); } return (Duration.getInstance(duration, units)); } catch (ParseException ex) { throw new MPXJException("Failed to parse duration", ex); } } }
public class class_name { private boolean updateChargingStationOpeningTimes(ChargingStationOpeningTimesChangedEvent event, boolean clear) { ChargingStation chargingStation = repository.findOne(event.getChargingStationId().getId()); if (chargingStation != null) { if (!event.getOpeningTimes().isEmpty()) { if (clear) { chargingStation.getOpeningTimes().clear(); } for (OpeningTime coreOpeningTime : event.getOpeningTimes()) { Day dayOfWeek = coreOpeningTime.getDay(); String timeStart = String.format(TIME_FORMAT, coreOpeningTime.getTimeStart().getHourOfDay(), coreOpeningTime.getTimeStart().getMinutesInHour()); String timeStop = String.format(TIME_FORMAT, coreOpeningTime.getTimeStop().getHourOfDay(), coreOpeningTime.getTimeStop().getMinutesInHour()); io.motown.operatorapi.viewmodel.persistence.entities.OpeningTime openingTime = new io.motown.operatorapi.viewmodel.persistence.entities.OpeningTime(dayOfWeek, timeStart, timeStop); chargingStation.getOpeningTimes().add(openingTime); } repository.createOrUpdate(chargingStation); } } else { LOG.error("operator api repo COULD NOT FIND CHARGEPOINT {} and update its opening times", event.getChargingStationId()); } return chargingStation != null; } }
public class class_name { private boolean updateChargingStationOpeningTimes(ChargingStationOpeningTimesChangedEvent event, boolean clear) { ChargingStation chargingStation = repository.findOne(event.getChargingStationId().getId()); if (chargingStation != null) { if (!event.getOpeningTimes().isEmpty()) { if (clear) { chargingStation.getOpeningTimes().clear(); // depends on control dependency: [if], data = [none] } for (OpeningTime coreOpeningTime : event.getOpeningTimes()) { Day dayOfWeek = coreOpeningTime.getDay(); String timeStart = String.format(TIME_FORMAT, coreOpeningTime.getTimeStart().getHourOfDay(), coreOpeningTime.getTimeStart().getMinutesInHour()); String timeStop = String.format(TIME_FORMAT, coreOpeningTime.getTimeStop().getHourOfDay(), coreOpeningTime.getTimeStop().getMinutesInHour()); io.motown.operatorapi.viewmodel.persistence.entities.OpeningTime openingTime = new io.motown.operatorapi.viewmodel.persistence.entities.OpeningTime(dayOfWeek, timeStart, timeStop); chargingStation.getOpeningTimes().add(openingTime); // depends on control dependency: [for], data = [none] } repository.createOrUpdate(chargingStation); // depends on control dependency: [if], data = [none] } } else { LOG.error("operator api repo COULD NOT FIND CHARGEPOINT {} and update its opening times", event.getChargingStationId()); // depends on control dependency: [if], data = [none] } return chargingStation != null; } }
public class class_name { protected boolean hasDividerBeforeChildAt(int childIndex) { if (childIndex == 0) { return (mShowDividers & SHOW_DIVIDER_BEGINNING) != 0; } else if (childIndex == getChildCount()) { return (mShowDividers & SHOW_DIVIDER_END) != 0; } else if ((mShowDividers & SHOW_DIVIDER_MIDDLE) != 0) { boolean hasVisibleViewBefore = false; for (int i = childIndex - 1; i >= 0; i--) { if (getChildAt(i).getVisibility() != GONE) { hasVisibleViewBefore = true; break; } } return hasVisibleViewBefore; } return false; } }
public class class_name { protected boolean hasDividerBeforeChildAt(int childIndex) { if (childIndex == 0) { return (mShowDividers & SHOW_DIVIDER_BEGINNING) != 0; // depends on control dependency: [if], data = [none] } else if (childIndex == getChildCount()) { return (mShowDividers & SHOW_DIVIDER_END) != 0; // depends on control dependency: [if], data = [none] } else if ((mShowDividers & SHOW_DIVIDER_MIDDLE) != 0) { boolean hasVisibleViewBefore = false; for (int i = childIndex - 1; i >= 0; i--) { if (getChildAt(i).getVisibility() != GONE) { hasVisibleViewBefore = true; // depends on control dependency: [if], data = [none] break; } } return hasVisibleViewBefore; // depends on control dependency: [if], data = [none] } return false; } }
public class class_name { public void handleFragmentResponseMessage(FragmentResponseMessage message) { TransactionState txn = m_outstandingTxns.get(message.getTxnId()); // We could already have received the CompleteTransactionMessage from // the local site and the transaction is dead, despite FragmentResponses // in flight from remote sites. Drop those on the floor. // IZZY: After implementing BorrowTasks, I'm not sure that the above sequence // can actually happen any longer, but leaving this and logging it for now. // RTB: Didn't we decide early rollback can do this legitimately. if (txn != null) { SerializableException ex = message.getException(); if (ex instanceof TransactionRestartException && ((TransactionRestartException)ex).isMisrouted()) { tmLog.debug("MpScheduler received misroute FragmentResponseMessage"); ((TransactionRestartException)ex).updateReplicas(m_iv2Masters, m_partitionMasters); } ((MpTransactionState)txn).offerReceivedFragmentResponse(message); } else if (tmLog.isDebugEnabled()){ tmLog.debug("MpScheduler received a FragmentResponseMessage for a null TXN ID: " + message); } } }
public class class_name { public void handleFragmentResponseMessage(FragmentResponseMessage message) { TransactionState txn = m_outstandingTxns.get(message.getTxnId()); // We could already have received the CompleteTransactionMessage from // the local site and the transaction is dead, despite FragmentResponses // in flight from remote sites. Drop those on the floor. // IZZY: After implementing BorrowTasks, I'm not sure that the above sequence // can actually happen any longer, but leaving this and logging it for now. // RTB: Didn't we decide early rollback can do this legitimately. if (txn != null) { SerializableException ex = message.getException(); if (ex instanceof TransactionRestartException && ((TransactionRestartException)ex).isMisrouted()) { tmLog.debug("MpScheduler received misroute FragmentResponseMessage"); // depends on control dependency: [if], data = [none] ((TransactionRestartException)ex).updateReplicas(m_iv2Masters, m_partitionMasters); // depends on control dependency: [if], data = [none] } ((MpTransactionState)txn).offerReceivedFragmentResponse(message); // depends on control dependency: [if], data = [none] } else if (tmLog.isDebugEnabled()){ tmLog.debug("MpScheduler received a FragmentResponseMessage for a null TXN ID: " + message); // depends on control dependency: [if], data = [none] } } }
public class class_name { private void postprocess_ModifyMemberProperty(ShapeModel shapeModel, String memberName, ShapeModifier_ModifyModel modifyModel) { if (modifyModel.getEmitEnumName() != null) { EnumModel enumModel = shapeModel.findEnumModelByValue(memberName); if (enumModel == null) { throw new IllegalStateException( String.format("Cannot find enum [%s] in the intermediate model when processing " + "customization config shapeModifiers.%s", memberName, memberName)); } enumModel.setName(modifyModel.getEmitEnumName()); } if (modifyModel.getMarshallLocationName() != null) { MemberModel memberModel = shapeModel.findMemberModelByC2jName(memberName); memberModel.getHttp().setMarshallLocationName(modifyModel.getMarshallLocationName()); } if (modifyModel.getUnmarshallLocationName() != null) { MemberModel memberModel = shapeModel.findMemberModelByC2jName(memberName); memberModel.getHttp().setUnmarshallLocationName(modifyModel .getUnmarshallLocationName()); } } }
public class class_name { private void postprocess_ModifyMemberProperty(ShapeModel shapeModel, String memberName, ShapeModifier_ModifyModel modifyModel) { if (modifyModel.getEmitEnumName() != null) { EnumModel enumModel = shapeModel.findEnumModelByValue(memberName); if (enumModel == null) { throw new IllegalStateException( String.format("Cannot find enum [%s] in the intermediate model when processing " + "customization config shapeModifiers.%s", memberName, memberName)); } enumModel.setName(modifyModel.getEmitEnumName()); // depends on control dependency: [if], data = [(modifyModel.getEmitEnumName()] } if (modifyModel.getMarshallLocationName() != null) { MemberModel memberModel = shapeModel.findMemberModelByC2jName(memberName); memberModel.getHttp().setMarshallLocationName(modifyModel.getMarshallLocationName()); // depends on control dependency: [if], data = [(modifyModel.getMarshallLocationName()] } if (modifyModel.getUnmarshallLocationName() != null) { MemberModel memberModel = shapeModel.findMemberModelByC2jName(memberName); memberModel.getHttp().setUnmarshallLocationName(modifyModel .getUnmarshallLocationName()); // depends on control dependency: [if], data = [none] } } }
public class class_name { private Map getAuthConfigMapToCheck(LookupMode lookupMode, Map authConfigMap) { String configMapKey = lookupMode.getConfigMapKey(); if (configMapKey == null) { return authConfigMap; } if (authConfigMap != null) { return (Map) authConfigMap.get(configMapKey); } return null; } }
public class class_name { private Map getAuthConfigMapToCheck(LookupMode lookupMode, Map authConfigMap) { String configMapKey = lookupMode.getConfigMapKey(); if (configMapKey == null) { return authConfigMap; // depends on control dependency: [if], data = [none] } if (authConfigMap != null) { return (Map) authConfigMap.get(configMapKey); // depends on control dependency: [if], data = [none] } return null; } }
public class class_name { @Nullable public static MethodSymbol getSymbol(MethodInvocationTree tree) { Symbol sym = ASTHelpers.getSymbol(tree.getMethodSelect()); if (!(sym instanceof MethodSymbol)) { // Defensive. Would only occur if there are errors in the AST. return null; } return (MethodSymbol) sym; } }
public class class_name { @Nullable public static MethodSymbol getSymbol(MethodInvocationTree tree) { Symbol sym = ASTHelpers.getSymbol(tree.getMethodSelect()); if (!(sym instanceof MethodSymbol)) { // Defensive. Would only occur if there are errors in the AST. return null; // depends on control dependency: [if], data = [none] } return (MethodSymbol) sym; } }
public class class_name { @Override public boolean hasNext() { while (!(iterators.isEmpty() || iterators.peek().hasNext())) { Assert.isFalse(iterators.removeFirst().hasNext(), new IllegalStateException("removing a non-empty Iterator")); } return (!iterators.isEmpty() && iterators.peek().hasNext()); } }
public class class_name { @Override public boolean hasNext() { while (!(iterators.isEmpty() || iterators.peek().hasNext())) { Assert.isFalse(iterators.removeFirst().hasNext(), new IllegalStateException("removing a non-empty Iterator")); // depends on control dependency: [while], data = [none] } return (!iterators.isEmpty() && iterators.peek().hasNext()); } }
public class class_name { private static boolean isClassAvailable(final String className) { try { return LoaderUtil.loadClass(className) != null; } catch (final Throwable e) { return false; } } }
public class class_name { private static boolean isClassAvailable(final String className) { try { return LoaderUtil.loadClass(className) != null; // depends on control dependency: [try], data = [none] } catch (final Throwable e) { return false; } // depends on control dependency: [catch], data = [none] } }
public class class_name { void cancel(boolean permanent) { enabled = false; if (permanent && wakeUp != null) { wakeUp.cancel(false); wakeUp = null; } } }
public class class_name { void cancel(boolean permanent) { enabled = false; if (permanent && wakeUp != null) { wakeUp.cancel(false); // depends on control dependency: [if], data = [none] wakeUp = null; // depends on control dependency: [if], data = [none] } } }
public class class_name { protected void initJsonReader() { String readerList = config.getJsonReaders(); if (readerList != null) { String[] readers = readerList.split(","); Set<String> supportedReaders = TreeReaderRegistry.getReadersByFormat("json"); TreeReader selectedReader = null; for (String reader : readers) { reader = reader.trim().toLowerCase(); if (!reader.isEmpty()) { for (String supportedReader : supportedReaders) { int i = supportedReader.lastIndexOf('.'); if (i > -1) { supportedReader = supportedReader.substring(i + 1); } if (supportedReader.toLowerCase().contains(reader)) { selectedReader = TreeReaderRegistry.getReader(supportedReader); logger.info("Default JSON deserializer/reader is \"" + selectedReader.getClass() + "\"."); TreeReaderRegistry.setReader("json", selectedReader); break; } } if (selectedReader != null) { break; } } } } } }
public class class_name { protected void initJsonReader() { String readerList = config.getJsonReaders(); if (readerList != null) { String[] readers = readerList.split(","); Set<String> supportedReaders = TreeReaderRegistry.getReadersByFormat("json"); TreeReader selectedReader = null; for (String reader : readers) { reader = reader.trim().toLowerCase(); // depends on control dependency: [for], data = [reader] if (!reader.isEmpty()) { for (String supportedReader : supportedReaders) { int i = supportedReader.lastIndexOf('.'); if (i > -1) { supportedReader = supportedReader.substring(i + 1); // depends on control dependency: [if], data = [(i] } if (supportedReader.toLowerCase().contains(reader)) { selectedReader = TreeReaderRegistry.getReader(supportedReader); // depends on control dependency: [if], data = [none] logger.info("Default JSON deserializer/reader is \"" + selectedReader.getClass() + "\"."); // depends on control dependency: [if], data = [none] TreeReaderRegistry.setReader("json", selectedReader); // depends on control dependency: [if], data = [none] break; } } if (selectedReader != null) { break; } } } } } }
public class class_name { private ParseTree parseEquality(Expression expressionIn) { SourcePosition start = getTreeStartLocation(); ParseTree left = parseRelational(expressionIn); while (peekEqualityOperator()) { Token operator = nextToken(); ParseTree right = parseRelational(expressionIn); left = new BinaryOperatorTree(getTreeLocation(start), left, operator, right); } return left; } }
public class class_name { private ParseTree parseEquality(Expression expressionIn) { SourcePosition start = getTreeStartLocation(); ParseTree left = parseRelational(expressionIn); while (peekEqualityOperator()) { Token operator = nextToken(); ParseTree right = parseRelational(expressionIn); left = new BinaryOperatorTree(getTreeLocation(start), left, operator, right); // depends on control dependency: [while], data = [none] } return left; } }
public class class_name { protected DoubleMatrix1D getFi(DoubleMatrix1D X){ final ConvexMultivariateRealFunction[] fis = request.getFi(); if(fis==null){ return null; } final double[] ret = new double[fis.length]; final double[] x = X.toArray(); for(int i=0; i<fis.length; i++){ final ConvexMultivariateRealFunction fi = fis[i]; final double fix = fi.value(x); ret[i] = fix; } return F1.make(ret); } }
public class class_name { protected DoubleMatrix1D getFi(DoubleMatrix1D X){ final ConvexMultivariateRealFunction[] fis = request.getFi(); if(fis==null){ return null; // depends on control dependency: [if], data = [none] } final double[] ret = new double[fis.length]; final double[] x = X.toArray(); for(int i=0; i<fis.length; i++){ final ConvexMultivariateRealFunction fi = fis[i]; final double fix = fi.value(x); ret[i] = fix; // depends on control dependency: [for], data = [i] } return F1.make(ret); } }
public class class_name { private static String getNormalizedParent(String filePath) { if (new File(filePath).getParent() == null) { // parent doesn't exist .. return null return null; } String parentDir = filePath.substring(0, filePath.lastIndexOf("/")); if (!parentDir.contains("/")) { //catch cases where filePath is something like C:/temp.zip or /home.zip parentDir = parentDir + "/"; } return parentDir; } }
public class class_name { private static String getNormalizedParent(String filePath) { if (new File(filePath).getParent() == null) { // parent doesn't exist .. return null return null; // depends on control dependency: [if], data = [none] } String parentDir = filePath.substring(0, filePath.lastIndexOf("/")); if (!parentDir.contains("/")) { //catch cases where filePath is something like C:/temp.zip or /home.zip parentDir = parentDir + "/"; // depends on control dependency: [if], data = [none] } return parentDir; } }
public class class_name { private void doProcessNext() { int _position = getPosition(); Node _current = getSource().item(_position); if (getActionPool().containsKey(_current.getNodeName())) { getActionPool().get(_current.getNodeName()).execute(_current, _position); } else if (getActionPool().containsKey(NODE_NAME__DEFAULT)) { getActionPool().get(NODE_NAME__DEFAULT).execute(_current, _position); } // else do nothing... // done _position++; setPosition(_position); } }
public class class_name { private void doProcessNext() { int _position = getPosition(); Node _current = getSource().item(_position); if (getActionPool().containsKey(_current.getNodeName())) { getActionPool().get(_current.getNodeName()).execute(_current, _position); // depends on control dependency: [if], data = [none] } else if (getActionPool().containsKey(NODE_NAME__DEFAULT)) { getActionPool().get(NODE_NAME__DEFAULT).execute(_current, _position); // depends on control dependency: [if], data = [none] } // else do nothing... // done _position++; setPosition(_position); } }
public class class_name { private void save(CmsParameterConfiguration properties, String source, String target, Set<String> forceWrite) { try { Set<String> alreadyWritten = new HashSet<String>(); LineNumberReader lnr = new LineNumberReader(new FileReader(new File(m_configRfsPath + source))); FileWriter fw = new FileWriter(new File(m_configRfsPath + target)); while (true) { String line = lnr.readLine(); if (line == null) { break; } line = line.trim(); if ("".equals(line)) { // output empty line fw.write("\n"); } else if (line.startsWith("#")) { // output comment fw.write(line); fw.write("\n"); } else { int index = line.indexOf('='); int index1 = line.indexOf("\\="); if ((line.indexOf('=') > -1) && (index1 != (index - 1))) { String key = line.substring(0, line.indexOf('=')).trim(); if (alreadyWritten.contains(key)) { continue; } String additionalPrefix = ADDITIONAL_PREFIX; if (key.startsWith(additionalPrefix)) { String additionalPropKey = key.substring(additionalPrefix.length()); String additionalContent = m_additionalProperties.get(additionalPropKey); if (additionalContent == null) { fw.write(key + "=\n"); } else { fw.write(additionalContent + "\n"); } continue; } // write key fw.write((key + "=")); try { Object obj = properties.getObject(key); if (obj != null) { String valueToWrite = getPropertyValueToWrite(obj); fw.write(valueToWrite); } } catch (NullPointerException e) { // no value found - do nothing } // add trailing line feed fw.write("\n"); // remember that this properties is already written (multi values) alreadyWritten.add(key); } } } if (forceWrite != null) { for (String forced : forceWrite) { if (!alreadyWritten.contains(forced) && properties.containsKey(forced)) { fw.write("\n\n"); fw.write(forced + "="); try { Object obj = properties.getObject(forced); if (obj != null) { String valueToWrite = getPropertyValueToWrite(obj); fw.write(valueToWrite); } } catch (NullPointerException e) { // no value found - do nothing } fw.write("\n"); } } } lnr.close(); fw.close(); } catch (Exception e) { m_errors.add("Could not save properties to " + target + " \n"); m_errors.add(e.toString() + "\n"); } } }
public class class_name { private void save(CmsParameterConfiguration properties, String source, String target, Set<String> forceWrite) { try { Set<String> alreadyWritten = new HashSet<String>(); LineNumberReader lnr = new LineNumberReader(new FileReader(new File(m_configRfsPath + source))); FileWriter fw = new FileWriter(new File(m_configRfsPath + target)); while (true) { String line = lnr.readLine(); if (line == null) { break; } line = line.trim(); // depends on control dependency: [while], data = [none] if ("".equals(line)) { // output empty line fw.write("\n"); // depends on control dependency: [if], data = [none] } else if (line.startsWith("#")) { // output comment fw.write(line); // depends on control dependency: [if], data = [none] fw.write("\n"); // depends on control dependency: [if], data = [none] } else { int index = line.indexOf('='); int index1 = line.indexOf("\\="); if ((line.indexOf('=') > -1) && (index1 != (index - 1))) { String key = line.substring(0, line.indexOf('=')).trim(); if (alreadyWritten.contains(key)) { continue; } String additionalPrefix = ADDITIONAL_PREFIX; if (key.startsWith(additionalPrefix)) { String additionalPropKey = key.substring(additionalPrefix.length()); String additionalContent = m_additionalProperties.get(additionalPropKey); if (additionalContent == null) { fw.write(key + "=\n"); // depends on control dependency: [if], data = [none] } else { fw.write(additionalContent + "\n"); // depends on control dependency: [if], data = [(additionalContent] } continue; } // write key fw.write((key + "=")); // depends on control dependency: [if], data = [none] try { Object obj = properties.getObject(key); if (obj != null) { String valueToWrite = getPropertyValueToWrite(obj); fw.write(valueToWrite); // depends on control dependency: [if], data = [none] } } catch (NullPointerException e) { // no value found - do nothing } // depends on control dependency: [catch], data = [none] // add trailing line feed fw.write("\n"); // depends on control dependency: [if], data = [none] // remember that this properties is already written (multi values) alreadyWritten.add(key); // depends on control dependency: [if], data = [none] } } } if (forceWrite != null) { for (String forced : forceWrite) { if (!alreadyWritten.contains(forced) && properties.containsKey(forced)) { fw.write("\n\n"); // depends on control dependency: [if], data = [none] fw.write(forced + "="); // depends on control dependency: [if], data = [none] try { Object obj = properties.getObject(forced); if (obj != null) { String valueToWrite = getPropertyValueToWrite(obj); fw.write(valueToWrite); // depends on control dependency: [if], data = [none] } } catch (NullPointerException e) { // no value found - do nothing } // depends on control dependency: [catch], data = [none] fw.write("\n"); // depends on control dependency: [if], data = [none] } } } lnr.close(); // depends on control dependency: [try], data = [none] fw.close(); // depends on control dependency: [try], data = [none] } catch (Exception e) { m_errors.add("Could not save properties to " + target + " \n"); m_errors.add(e.toString() + "\n"); } // depends on control dependency: [catch], data = [none] } }
public class class_name { private String getDefaultVersion(Set<String> keys, String appName) { SortedSet<String> listOfApps = new TreeSet<String>(); for (String key : keys) { if (key.split(":")[0].contentEquals(appName)) { listOfApps.add(key); } } return listOfApps.size() > 0 ? listOfApps.last() : null; } }
public class class_name { private String getDefaultVersion(Set<String> keys, String appName) { SortedSet<String> listOfApps = new TreeSet<String>(); for (String key : keys) { if (key.split(":")[0].contentEquals(appName)) { listOfApps.add(key); // depends on control dependency: [if], data = [none] } } return listOfApps.size() > 0 ? listOfApps.last() : null; } }
public class class_name { public void setStaticVariables(final Map<String, ?> variables) { if (variables != null) { if (this.staticVariables == null) { this.staticVariables = new HashMap<String, Object>(3, 1.0f); } this.staticVariables.putAll(variables); } } }
public class class_name { public void setStaticVariables(final Map<String, ?> variables) { if (variables != null) { if (this.staticVariables == null) { this.staticVariables = new HashMap<String, Object>(3, 1.0f); // depends on control dependency: [if], data = [none] } this.staticVariables.putAll(variables); // depends on control dependency: [if], data = [(variables] } } }
public class class_name { @Override public String convert(SIFInteraction inter) { String s = inter.toString(); for (OutputColumn column : columns) { s += "\t" + column.getColumnValue(inter); } return s; } }
public class class_name { @Override public String convert(SIFInteraction inter) { String s = inter.toString(); for (OutputColumn column : columns) { s += "\t" + column.getColumnValue(inter); // depends on control dependency: [for], data = [column] } return s; } }
public class class_name { public final BELScriptParser.document_property_return document_property() throws RecognitionException { BELScriptParser.document_property_return retval = new BELScriptParser.document_property_return(); retval.start = input.LT(1); Object root_0 = null; Token set47=null; Object set47_tree=null; try { // BELScript.g:121:18: ( 'Authors' | 'ContactInfo' | 'Copyright' | 'Description' | 'Disclaimer' | 'Licenses' | 'Name' | 'Version' ) // BELScript.g: { root_0 = (Object)adaptor.nil(); set47=(Token)input.LT(1); if ( (input.LA(1)>=35 && input.LA(1)<=42) ) { input.consume(); adaptor.addChild(root_0, (Object)adaptor.create(set47)); state.errorRecovery=false; } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } } retval.stop = input.LT(-1); retval.tree = (Object)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { } return retval; } }
public class class_name { public final BELScriptParser.document_property_return document_property() throws RecognitionException { BELScriptParser.document_property_return retval = new BELScriptParser.document_property_return(); retval.start = input.LT(1); Object root_0 = null; Token set47=null; Object set47_tree=null; try { // BELScript.g:121:18: ( 'Authors' | 'ContactInfo' | 'Copyright' | 'Description' | 'Disclaimer' | 'Licenses' | 'Name' | 'Version' ) // BELScript.g: { root_0 = (Object)adaptor.nil(); set47=(Token)input.LT(1); if ( (input.LA(1)>=35 && input.LA(1)<=42) ) { input.consume(); // depends on control dependency: [if], data = [none] adaptor.addChild(root_0, (Object)adaptor.create(set47)); // depends on control dependency: [if], data = [none] state.errorRecovery=false; // depends on control dependency: [if], data = [none] } else { MismatchedSetException mse = new MismatchedSetException(null,input); throw mse; } } retval.stop = input.LT(-1); retval.tree = (Object)adaptor.rulePostProcessing(root_0); adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop); } catch (RecognitionException re) { reportError(re); recover(input,re); retval.tree = (Object)adaptor.errorNode(input, retval.start, input.LT(-1), re); } finally { } return retval; } }
public class class_name { public AT_Row setHtmlElementTranslator(HtmlElementTranslator htmlElementTranslator) { if(this.hasCells()){ for(AT_Cell cell : this.getCells()){ cell.getContext().setHtmlElementTranslator(htmlElementTranslator); } } return this; } }
public class class_name { public AT_Row setHtmlElementTranslator(HtmlElementTranslator htmlElementTranslator) { if(this.hasCells()){ for(AT_Cell cell : this.getCells()){ cell.getContext().setHtmlElementTranslator(htmlElementTranslator); // depends on control dependency: [for], data = [cell] } } return this; } }
public class class_name { public static SafeHtml concat(Iterable<SafeHtml> htmls) { int concatLength = 0; for (SafeHtml html : htmls) { concatLength += html.getSafeHtmlString().length(); } StringBuilder result = new StringBuilder(concatLength); for (SafeHtml html : htmls) { result.append(html.getSafeHtmlString()); } return create(result.toString()); } }
public class class_name { public static SafeHtml concat(Iterable<SafeHtml> htmls) { int concatLength = 0; for (SafeHtml html : htmls) { concatLength += html.getSafeHtmlString().length(); // depends on control dependency: [for], data = [html] } StringBuilder result = new StringBuilder(concatLength); for (SafeHtml html : htmls) { result.append(html.getSafeHtmlString()); // depends on control dependency: [for], data = [html] } return create(result.toString()); } }