code stringlengths 130 281k | code_dependency stringlengths 182 306k |
|---|---|
public class class_name {
public Optional<String> getSigningKey(final RegisteredService registeredService) {
val property = getSigningKeyRegisteredServiceProperty();
if (property.isAssignedTo(registeredService)) {
val signingKey = property.getPropertyValue(registeredService).getValue();
return Optional.of(signingKey);
}
return Optional.empty();
} } | public class class_name {
public Optional<String> getSigningKey(final RegisteredService registeredService) {
val property = getSigningKeyRegisteredServiceProperty();
if (property.isAssignedTo(registeredService)) {
val signingKey = property.getPropertyValue(registeredService).getValue();
return Optional.of(signingKey); // depends on control dependency: [if], data = [none]
}
return Optional.empty();
} } |
public class class_name {
protected void addANYHandler(final EventHandler eventHandler)
{
final int eventType = eventHandler.getEventType();
if (eventType != Events.ANY)
{
LOG.error("The incoming handler {} is not of type ANY",
eventHandler);
throw new IllegalArgumentException(
"The incoming handler is not of type ANY");
}
anyHandler.add(eventHandler);
Callback<List<Event>> eventCallback = createEventCallbackForHandler(eventHandler);
BatchSubscriber<Event> batchEventSubscriber = new BatchSubscriber<Event>(
fiber, eventCallback, 0, TimeUnit.MILLISECONDS);
Disposable disposable = eventQueue.subscribe(batchEventSubscriber);
disposableHandlerMap.put(eventHandler, disposable);
} } | public class class_name {
protected void addANYHandler(final EventHandler eventHandler)
{
final int eventType = eventHandler.getEventType();
if (eventType != Events.ANY)
{
LOG.error("The incoming handler {} is not of type ANY",
eventHandler); // depends on control dependency: [if], data = [none]
throw new IllegalArgumentException(
"The incoming handler is not of type ANY");
}
anyHandler.add(eventHandler);
Callback<List<Event>> eventCallback = createEventCallbackForHandler(eventHandler);
BatchSubscriber<Event> batchEventSubscriber = new BatchSubscriber<Event>(
fiber, eventCallback, 0, TimeUnit.MILLISECONDS);
Disposable disposable = eventQueue.subscribe(batchEventSubscriber);
disposableHandlerMap.put(eventHandler, disposable);
} } |
public class class_name {
public String getPageContent(String element) {
// Determine the folder to read the contents from
String contentFolder = property(CmsPropertyDefinition.PROPERTY_TEMPLATE_ELEMENTS, "search", "");
if (CmsStringUtil.isEmpty(contentFolder)) {
contentFolder = VFS_FOLDER_HANDLER + "contents/";
}
// determine the file to read the contents from
String fileName = "content" + getStatusCodeMessage() + ".html";
if (!getCmsObject().existsResource(contentFolder + fileName)) {
// special file does not exist, use generic one
fileName = "content" + UNKKNOWN_STATUS_CODE + ".html";
}
// get the content
return getContent(contentFolder + fileName, element, getLocale());
} } | public class class_name {
public String getPageContent(String element) {
// Determine the folder to read the contents from
String contentFolder = property(CmsPropertyDefinition.PROPERTY_TEMPLATE_ELEMENTS, "search", "");
if (CmsStringUtil.isEmpty(contentFolder)) {
contentFolder = VFS_FOLDER_HANDLER + "contents/"; // depends on control dependency: [if], data = [none]
}
// determine the file to read the contents from
String fileName = "content" + getStatusCodeMessage() + ".html";
if (!getCmsObject().existsResource(contentFolder + fileName)) {
// special file does not exist, use generic one
fileName = "content" + UNKKNOWN_STATUS_CODE + ".html"; // depends on control dependency: [if], data = [none]
}
// get the content
return getContent(contentFolder + fileName, element, getLocale());
} } |
public class class_name {
static boolean killProcess(final String processName, int id) {
int pid;
try {
pid = processUtils.resolveProcessId(processName, id);
if(pid > 0) {
try {
Runtime.getRuntime().exec(processUtils.getKillCommand(pid));
return true;
} catch (Throwable t) {
ProcessLogger.ROOT_LOGGER.debugf(t, "failed to kill process '%s' with pid '%s'", processName, pid);
}
}
} catch (Throwable t) {
ProcessLogger.ROOT_LOGGER.debugf(t, "failed to resolve pid of process '%s'", processName);
}
return false;
} } | public class class_name {
static boolean killProcess(final String processName, int id) {
int pid;
try {
pid = processUtils.resolveProcessId(processName, id); // depends on control dependency: [try], data = [none]
if(pid > 0) {
try {
Runtime.getRuntime().exec(processUtils.getKillCommand(pid)); // depends on control dependency: [try], data = [none]
return true; // depends on control dependency: [try], data = [none]
} catch (Throwable t) {
ProcessLogger.ROOT_LOGGER.debugf(t, "failed to kill process '%s' with pid '%s'", processName, pid);
} // depends on control dependency: [catch], data = [none]
}
} catch (Throwable t) {
ProcessLogger.ROOT_LOGGER.debugf(t, "failed to resolve pid of process '%s'", processName);
} // depends on control dependency: [catch], data = [none]
return false;
} } |
public class class_name {
public static List<HttpCode> getHttpStatusCodes(List<BinaryAnnotation> binaryAnnotations) {
if (binaryAnnotations == null) {
return Collections.emptyList();
}
List<HttpCode> httpCodes = new ArrayList<>();
for (BinaryAnnotation binaryAnnotation: binaryAnnotations) {
if (Constants.ZIPKIN_BIN_ANNOTATION_HTTP_STATUS_CODE.equals(binaryAnnotation.getKey()) &&
binaryAnnotation.getValue() != null) {
String strHttpCode = binaryAnnotation.getValue();
Integer httpCode = toInt(strHttpCode.trim());
if (httpCode != null) {
String description = EnglishReasonPhraseCatalog.INSTANCE.getReason(httpCode, Locale.ENGLISH);
httpCodes.add(new HttpCode(httpCode, description));
}
}
}
return httpCodes;
} } | public class class_name {
public static List<HttpCode> getHttpStatusCodes(List<BinaryAnnotation> binaryAnnotations) {
if (binaryAnnotations == null) {
return Collections.emptyList(); // depends on control dependency: [if], data = [none]
}
List<HttpCode> httpCodes = new ArrayList<>();
for (BinaryAnnotation binaryAnnotation: binaryAnnotations) {
if (Constants.ZIPKIN_BIN_ANNOTATION_HTTP_STATUS_CODE.equals(binaryAnnotation.getKey()) &&
binaryAnnotation.getValue() != null) {
String strHttpCode = binaryAnnotation.getValue();
Integer httpCode = toInt(strHttpCode.trim());
if (httpCode != null) {
String description = EnglishReasonPhraseCatalog.INSTANCE.getReason(httpCode, Locale.ENGLISH);
httpCodes.add(new HttpCode(httpCode, description)); // depends on control dependency: [if], data = [(httpCode]
}
}
}
return httpCodes;
} } |
public class class_name {
public static double Canberra(double[] p, double[] q) {
double distance = 0;
for (int i = 0; i < p.length; i++) {
distance += Math.abs(p[i] - q[i]) / (Math.abs(p[i]) + Math.abs(q[i]));
}
return distance;
} } | public class class_name {
public static double Canberra(double[] p, double[] q) {
double distance = 0;
for (int i = 0; i < p.length; i++) {
distance += Math.abs(p[i] - q[i]) / (Math.abs(p[i]) + Math.abs(q[i])); // depends on control dependency: [for], data = [i]
}
return distance;
} } |
public class class_name {
private static boolean validateVersion(Context ctx, ChangeLog clog){
// Get Preferences
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
int lastSeen = prefs.getInt(PREF_CHANGELOG_LAST_SEEN, -1);
// Second sort versions by it's code
int latest = Integer.MIN_VALUE;
for(Version version: clog.versions){
if(version.code > latest){
latest = version.code;
}
}
// Get applications current version
if(latest > lastSeen){
if(!BuildConfig.DEBUG) prefs.edit().putInt(PREF_CHANGELOG_LAST_SEEN, latest).apply();
return true;
}
return false;
} } | public class class_name {
private static boolean validateVersion(Context ctx, ChangeLog clog){
// Get Preferences
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
int lastSeen = prefs.getInt(PREF_CHANGELOG_LAST_SEEN, -1);
// Second sort versions by it's code
int latest = Integer.MIN_VALUE;
for(Version version: clog.versions){
if(version.code > latest){
latest = version.code; // depends on control dependency: [if], data = [none]
}
}
// Get applications current version
if(latest > lastSeen){
if(!BuildConfig.DEBUG) prefs.edit().putInt(PREF_CHANGELOG_LAST_SEEN, latest).apply();
return true; // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
@Programmatic
public Blob downloadLayouts() {
final LayoutJsonExporter exporter = new LayoutJsonExporter();
final Collection<ObjectSpecification> allSpecs = specificationLoader.allSpecifications();
final Collection<ObjectSpecification> domainObjectSpecs = Collections2.filter(allSpecs, new Predicate<ObjectSpecification>(){
@Override
public boolean apply(final ObjectSpecification input) {
return !input.isAbstract() &&
!input.isService() &&
!input.isValue() &&
!input.isParentedOrFreeCollection();
}});
try {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final ZipOutputStream zos = new ZipOutputStream(baos);
final OutputStreamWriter writer = new OutputStreamWriter(zos);
for (final ObjectSpecification objectSpec : domainObjectSpecs) {
zos.putNextEntry(new ZipEntry(zipEntryNameFor(objectSpec)));
writer.write(exporter.asJson(objectSpec));
writer.flush();
zos.closeEntry();
}
writer.close();
return new Blob("layouts.zip", mimeTypeApplicationZip, baos.toByteArray());
} catch (final IOException ex) {
throw new FatalException("Unable to create zip of layouts", ex);
}
} } | public class class_name {
@Programmatic
public Blob downloadLayouts() {
final LayoutJsonExporter exporter = new LayoutJsonExporter();
final Collection<ObjectSpecification> allSpecs = specificationLoader.allSpecifications();
final Collection<ObjectSpecification> domainObjectSpecs = Collections2.filter(allSpecs, new Predicate<ObjectSpecification>(){
@Override
public boolean apply(final ObjectSpecification input) {
return !input.isAbstract() &&
!input.isService() &&
!input.isValue() &&
!input.isParentedOrFreeCollection();
}});
try {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
final ZipOutputStream zos = new ZipOutputStream(baos);
final OutputStreamWriter writer = new OutputStreamWriter(zos);
for (final ObjectSpecification objectSpec : domainObjectSpecs) {
zos.putNextEntry(new ZipEntry(zipEntryNameFor(objectSpec))); // depends on control dependency: [for], data = [objectSpec]
writer.write(exporter.asJson(objectSpec)); // depends on control dependency: [for], data = [objectSpec]
writer.flush(); // depends on control dependency: [for], data = [none]
zos.closeEntry(); // depends on control dependency: [for], data = [none]
}
writer.close(); // depends on control dependency: [try], data = [none]
return new Blob("layouts.zip", mimeTypeApplicationZip, baos.toByteArray()); // depends on control dependency: [try], data = [none]
} catch (final IOException ex) {
throw new FatalException("Unable to create zip of layouts", ex);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
@GuardedBy("lock")
private boolean isSatisfied(Guard guard) {
try {
return guard.isSatisfied();
} catch (Throwable throwable) {
signalAllWaiters();
throw Throwables.propagate(throwable);
}
} } | public class class_name {
@GuardedBy("lock")
private boolean isSatisfied(Guard guard) {
try {
return guard.isSatisfied(); // depends on control dependency: [try], data = [none]
} catch (Throwable throwable) {
signalAllWaiters();
throw Throwables.propagate(throwable);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static String resolveWildCardForJarSpec(String workingDirectory, String unresolvedJarSpec,
Logger log) {
log.debug("resolveWildCardForJarSpec: unresolved jar specification: " + unresolvedJarSpec);
log.debug("working directory: " + workingDirectory);
if (unresolvedJarSpec == null || unresolvedJarSpec.isEmpty()) {
return "";
}
StringBuilder resolvedJarSpec = new StringBuilder();
String[] unresolvedJarSpecList = unresolvedJarSpec.split(",");
for (String s : unresolvedJarSpecList) {
// if need resolution
if (s.endsWith("*")) {
// remove last 2 characters to get to the folder
String dirName = String.format("%s/%s", workingDirectory, s.substring(0, s.length() - 2));
File[] jars = null;
try {
jars = getFilesInFolderByRegex(new File(dirName), ".*jar");
} catch (FileNotFoundException fnfe) {
log.warn("folder does not exist: " + dirName);
continue;
}
// if the folder is there, add them to the jar list
for (File jar : jars) {
resolvedJarSpec.append(jar.toString()).append(",");
}
} else { // no need for resolution
resolvedJarSpec.append(s).append(",");
}
}
log.debug("resolveWildCardForJarSpec: resolvedJarSpec: " + resolvedJarSpec);
// remove the trailing comma
int lastCharIndex = resolvedJarSpec.length() - 1;
if (lastCharIndex >= 0 && resolvedJarSpec.charAt(lastCharIndex) == ',') {
resolvedJarSpec.deleteCharAt(lastCharIndex);
}
return resolvedJarSpec.toString();
} } | public class class_name {
public static String resolveWildCardForJarSpec(String workingDirectory, String unresolvedJarSpec,
Logger log) {
log.debug("resolveWildCardForJarSpec: unresolved jar specification: " + unresolvedJarSpec);
log.debug("working directory: " + workingDirectory);
if (unresolvedJarSpec == null || unresolvedJarSpec.isEmpty()) {
return ""; // depends on control dependency: [if], data = [none]
}
StringBuilder resolvedJarSpec = new StringBuilder();
String[] unresolvedJarSpecList = unresolvedJarSpec.split(",");
for (String s : unresolvedJarSpecList) {
// if need resolution
if (s.endsWith("*")) {
// remove last 2 characters to get to the folder
String dirName = String.format("%s/%s", workingDirectory, s.substring(0, s.length() - 2));
File[] jars = null;
try {
jars = getFilesInFolderByRegex(new File(dirName), ".*jar"); // depends on control dependency: [try], data = [none]
} catch (FileNotFoundException fnfe) {
log.warn("folder does not exist: " + dirName);
continue;
} // depends on control dependency: [catch], data = [none]
// if the folder is there, add them to the jar list
for (File jar : jars) {
resolvedJarSpec.append(jar.toString()).append(","); // depends on control dependency: [for], data = [jar]
}
} else { // no need for resolution
resolvedJarSpec.append(s).append(","); // depends on control dependency: [if], data = [none]
}
}
log.debug("resolveWildCardForJarSpec: resolvedJarSpec: " + resolvedJarSpec);
// remove the trailing comma
int lastCharIndex = resolvedJarSpec.length() - 1;
if (lastCharIndex >= 0 && resolvedJarSpec.charAt(lastCharIndex) == ',') {
resolvedJarSpec.deleteCharAt(lastCharIndex); // depends on control dependency: [if], data = [none]
}
return resolvedJarSpec.toString();
} } |
public class class_name {
static Message mergeSources(List<Object> sources, Message message) {
List<Object> messageSources = message.getSources();
// It is possible that the end of getSources() and the beginning of message.getSources() are
// equivalent, in this case we should drop the repeated source when joining the lists. The
// most likely scenario where this would happen is when a scoped binding throws an exception,
// due to the fact that InternalFactoryToProviderAdapter applies the binding source when
// merging errors.
if (!sources.isEmpty()
&& !messageSources.isEmpty()
&& Objects.equal(messageSources.get(0), sources.get(sources.size() - 1))) {
messageSources = messageSources.subList(1, messageSources.size());
}
return new Message(
ImmutableList.builder().addAll(sources).addAll(messageSources).build(),
message.getMessage(),
message.getCause());
} } | public class class_name {
static Message mergeSources(List<Object> sources, Message message) {
List<Object> messageSources = message.getSources();
// It is possible that the end of getSources() and the beginning of message.getSources() are
// equivalent, in this case we should drop the repeated source when joining the lists. The
// most likely scenario where this would happen is when a scoped binding throws an exception,
// due to the fact that InternalFactoryToProviderAdapter applies the binding source when
// merging errors.
if (!sources.isEmpty()
&& !messageSources.isEmpty()
&& Objects.equal(messageSources.get(0), sources.get(sources.size() - 1))) {
messageSources = messageSources.subList(1, messageSources.size()); // depends on control dependency: [if], data = [none]
}
return new Message(
ImmutableList.builder().addAll(sources).addAll(messageSources).build(),
message.getMessage(),
message.getCause());
} } |
public class class_name {
public static Model newModel(String modelPath, String unused) {
Model m = new Model();
if (!modelPath.equals("")) {
m.loadModel(modelPath);
}
return m;
} } | public class class_name {
public static Model newModel(String modelPath, String unused) {
Model m = new Model();
if (!modelPath.equals("")) {
m.loadModel(modelPath); // depends on control dependency: [if], data = [none]
}
return m;
} } |
public class class_name {
@SuppressWarnings("unchecked")
@Override
public void publishEvent(ApplicationEvent event) {
if (event instanceof MappingContextEvent) {
this.schmeaCreator
.onApplicationEvent((MappingContextEvent<SolrPersistentEntity<?>, SolrPersistentProperty>) event);
}
} } | public class class_name {
@SuppressWarnings("unchecked")
@Override
public void publishEvent(ApplicationEvent event) {
if (event instanceof MappingContextEvent) {
this.schmeaCreator
.onApplicationEvent((MappingContextEvent<SolrPersistentEntity<?>, SolrPersistentProperty>) event); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static int mainWithReturnCode(String args[]) {
TimeZone.setDefault(TimeZone.getTimeZone("GMT+0"));
// Initialize parameter defaults
String serverList = "localhost";
int port = 21212;
String user = "";
String password = "";
String credentials = "";
String kerberos = "";
FileReader fr = null;
List<String> queries = null;
String ddlFileText = "";
String sslConfigFile = null;
boolean enableSSL = false;
// Parse out parameters
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if (arg.startsWith("--servers=")) {
serverList = extractArgInput(arg);
if (serverList == null) return -1;
}
else if (arg.startsWith("--port=")) {
String portStr = extractArgInput(arg);
if (portStr == null) return -1;
port = Integer.valueOf(portStr);
}
else if (arg.startsWith("--user=")) {
user = extractArgInput(arg);
if (user == null) return -1;
}
else if (arg.startsWith("--password=")) {
password = extractArgInput(arg);
if (password == null) return -1;
}
else if (arg.startsWith("--credentials")) {
credentials = extractArgInput(arg);
if (credentials == null) return -1;
}
else if (arg.startsWith("--kerberos=")) {
kerberos = extractArgInput(arg);
if (kerberos == null) return -1;
}
else if (arg.startsWith("--kerberos")) {
kerberos = "VoltDBClient";
}
else if (arg.startsWith("--query=")) {
List<String> argQueries = SQLLexer.splitStatements(arg.substring(8)).getCompletelyParsedStmts();
if (!argQueries.isEmpty()) {
if (queries == null) {
queries = argQueries;
}
else {
queries.addAll(argQueries);
}
}
}
else if (arg.startsWith("--output-format=")) {
String formatName = extractArgInput(arg);
if (formatName == null) return -1;
formatName = formatName.toLowerCase();
if (formatName.equals("fixed")) {
m_outputFormatter = new SQLCommandOutputFormatterDefault();
}
else if (formatName.equals("csv")) {
m_outputFormatter = new SQLCommandOutputFormatterCSV();
}
else if (formatName.equals("tab")) {
m_outputFormatter = new SQLCommandOutputFormatterTabDelimited();
}
else {
printUsage("Invalid value for --output-format");
return -1;
}
}
else if (arg.startsWith("--stop-on-error=")) {
String optionName = extractArgInput(arg);
if (optionName == null) return -1;
optionName = optionName.toLowerCase();
if (optionName.equals("true")) {
m_stopOnError = true;
}
else if (optionName.equals("false")) {
m_stopOnError = false;
}
else {
printUsage("Invalid value for --stop-on-error");
return -1;
}
}
else if (arg.startsWith("--ddl-file=")) {
String ddlFilePath = extractArgInput(arg);
if (ddlFilePath == null) return -1;
try {
File ddlJavaFile = new File(ddlFilePath);
Scanner scanner = new Scanner(ddlJavaFile);
ddlFileText = scanner.useDelimiter("\\Z").next();
scanner.close();
} catch (FileNotFoundException e) {
printUsage("DDL file not found at path:" + ddlFilePath);
return -1;
}
}
else if (arg.startsWith("--query-timeout=")) {
m_hasBatchTimeout = true;
String batchTimeoutStr = extractArgInput(arg);
if (batchTimeoutStr == null) return -1;
m_batchTimeout = Integer.valueOf(batchTimeoutStr);
}
// equals check starting here
else if (arg.equals("--output-skip-metadata")) {
m_outputShowMetadata = false;
}
else if (arg.startsWith("--ssl=")) {
enableSSL = true;
sslConfigFile = extractArgInput(arg);
if (sslConfigFile == null) return -1;
}
else if (arg.startsWith("--ssl")) {
enableSSL = true;
sslConfigFile = null;
}
else if (arg.equals("--debug")) {
m_debug = true;
}
else if (arg.equals("--help")) {
printHelp(System.out); // Print readme to the screen
System.out.println("\n\n");
printUsage();
return -1;
}
else if (arg.equals("--no-version-check")) {
m_versionCheck = false; // Disable new version phone home check
}
else if ((arg.equals("--usage")) || (arg.equals("-?"))) {
printUsage();
return -1;
}
else {
printUsage("Invalid Parameter: " + arg);
return -1;
}
}
// Split server list
String[] servers = serverList.split(",");
// Phone home to see if there is a newer version of VoltDB
if (m_versionCheck) {
openURLAsync();
}
// read username and password from txt file
if (credentials != null && !credentials.trim().isEmpty()) {
Properties props = MiscUtils.readPropertiesFromCredentials(credentials);
user = props.getProperty("username");
password = props.getProperty("password");
}
try
{
// If we need to prompt the user for a password, do so.
password = CLIConfig.readPasswordIfNeeded(user, password, "Enter password: ");
}
catch (IOException ex)
{
printUsage("Unable to read password: " + ex);
}
// Create connection
ClientConfig config = new ClientConfig(user, password, null);
if (enableSSL) {
if (sslConfigFile != null && !sslConfigFile.trim().isEmpty()) {
config.setTrustStoreConfigFromPropertyFile(sslConfigFile);
} else {
config.setTrustStoreConfigFromDefault();
}
config.enableSSL();
}
config.setProcedureCallTimeout(0); // Set procedure all to infinite timeout, see ENG-2670
try {
// if specified enable kerberos
if (!kerberos.isEmpty()) {
config.enableKerberosAuthentication(kerberos);
}
m_client = getClient(config, servers, port);
} catch (Exception exc) {
System.err.println(exc.getMessage());
return -1;
}
try {
if (! ddlFileText.equals("")) {
// fast DDL Loader mode
// System.out.println("fast DDL Loader mode with DDL input:\n" + ddlFile);
m_client.callProcedure("@AdHoc", ddlFileText);
return m_exitCode;
}
// Load system procedures
loadSystemProcedures();
// Load user stored procs
loadStoredProcedures(Procedures, Classlist);
// Removed code to prevent Ctrl-C from exiting. The original code is visible
// in Git history hash 837df236c059b5b4362ffca7e7a5426fba1b7f20.
m_interactive = true;
if (queries != null && !queries.isEmpty()) {
// If queries are provided via command line options run them in
// non-interactive mode.
//TODO: Someday we should honor batching.
m_interactive = false;
for (String query : queries) {
executeStatement(query, null, 0);
}
}
// This test for an interactive environment is mostly
// reliable. See stackoverflow.com/questions/1403772.
// It accurately detects when data is piped into the program
// but it fails to distinguish the case when data is ONLY piped
// OUT of the command -- that's a possible but very strange way
// to run an interactive session, so it's OK that we don't support
// it. Instead, in that edge case, we fall back to non-interactive
// mode but IN THAT MODE, we wait on and process user input as if
// from a slow pipe. Strange, but acceptable, and preferable to the
// check used here in the past (System.in.available() > 0)
// which would fail in the opposite direction, when a 0-length
// file was piped in, showing an interactive greeting and prompt
// before quitting.
if (System.console() == null && m_interactive) {
m_interactive = false;
executeNoninteractive();
}
if (m_interactive) {
// Print out welcome message
System.out.printf("SQL Command :: %s%s:%d\n", (user == "" ? "" : user + "@"), serverList, port);
interactWithTheUser();
}
}
catch (SQLCmdEarlyExitException e) {
return m_exitCode;
}
catch (Exception x) {
try { stopOrContinue(x); } catch (SQLCmdEarlyExitException e) { return m_exitCode; }
}
finally {
try { m_client.close(); } catch (Exception x) { }
}
// Processing may have been continued after one or more errors.
// Reflect them in the exit code.
// This might be a little unconventional for an interactive session,
// but it's also likely to be ignored in that case, so "no great harm done".
//* enable to debug */ System.err.println("Exiting with code " + m_exitCode);
return m_exitCode;
} } | public class class_name {
public static int mainWithReturnCode(String args[]) {
TimeZone.setDefault(TimeZone.getTimeZone("GMT+0"));
// Initialize parameter defaults
String serverList = "localhost";
int port = 21212;
String user = "";
String password = "";
String credentials = "";
String kerberos = "";
FileReader fr = null;
List<String> queries = null;
String ddlFileText = "";
String sslConfigFile = null;
boolean enableSSL = false;
// Parse out parameters
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if (arg.startsWith("--servers=")) {
serverList = extractArgInput(arg); // depends on control dependency: [if], data = [none]
if (serverList == null) return -1;
}
else if (arg.startsWith("--port=")) {
String portStr = extractArgInput(arg);
if (portStr == null) return -1;
port = Integer.valueOf(portStr); // depends on control dependency: [if], data = [none]
}
else if (arg.startsWith("--user=")) {
user = extractArgInput(arg); // depends on control dependency: [if], data = [none]
if (user == null) return -1;
}
else if (arg.startsWith("--password=")) {
password = extractArgInput(arg); // depends on control dependency: [if], data = [none]
if (password == null) return -1;
}
else if (arg.startsWith("--credentials")) {
credentials = extractArgInput(arg); // depends on control dependency: [if], data = [none]
if (credentials == null) return -1;
}
else if (arg.startsWith("--kerberos=")) {
kerberos = extractArgInput(arg); // depends on control dependency: [if], data = [none]
if (kerberos == null) return -1;
}
else if (arg.startsWith("--kerberos")) {
kerberos = "VoltDBClient"; // depends on control dependency: [if], data = [none]
}
else if (arg.startsWith("--query=")) {
List<String> argQueries = SQLLexer.splitStatements(arg.substring(8)).getCompletelyParsedStmts();
if (!argQueries.isEmpty()) {
if (queries == null) {
queries = argQueries; // depends on control dependency: [if], data = [none]
}
else {
queries.addAll(argQueries); // depends on control dependency: [if], data = [none]
}
}
}
else if (arg.startsWith("--output-format=")) {
String formatName = extractArgInput(arg);
if (formatName == null) return -1;
formatName = formatName.toLowerCase(); // depends on control dependency: [if], data = [none]
if (formatName.equals("fixed")) {
m_outputFormatter = new SQLCommandOutputFormatterDefault(); // depends on control dependency: [if], data = [none]
}
else if (formatName.equals("csv")) {
m_outputFormatter = new SQLCommandOutputFormatterCSV(); // depends on control dependency: [if], data = [none]
}
else if (formatName.equals("tab")) {
m_outputFormatter = new SQLCommandOutputFormatterTabDelimited(); // depends on control dependency: [if], data = [none]
}
else {
printUsage("Invalid value for --output-format"); // depends on control dependency: [if], data = [none]
return -1; // depends on control dependency: [if], data = [none]
}
}
else if (arg.startsWith("--stop-on-error=")) {
String optionName = extractArgInput(arg);
if (optionName == null) return -1;
optionName = optionName.toLowerCase(); // depends on control dependency: [if], data = [none]
if (optionName.equals("true")) {
m_stopOnError = true; // depends on control dependency: [if], data = [none]
}
else if (optionName.equals("false")) {
m_stopOnError = false; // depends on control dependency: [if], data = [none]
}
else {
printUsage("Invalid value for --stop-on-error"); // depends on control dependency: [if], data = [none]
return -1; // depends on control dependency: [if], data = [none]
}
}
else if (arg.startsWith("--ddl-file=")) {
String ddlFilePath = extractArgInput(arg);
if (ddlFilePath == null) return -1;
try {
File ddlJavaFile = new File(ddlFilePath);
Scanner scanner = new Scanner(ddlJavaFile);
ddlFileText = scanner.useDelimiter("\\Z").next(); // depends on control dependency: [try], data = [none]
scanner.close(); // depends on control dependency: [try], data = [none]
} catch (FileNotFoundException e) {
printUsage("DDL file not found at path:" + ddlFilePath);
return -1;
} // depends on control dependency: [catch], data = [none]
}
else if (arg.startsWith("--query-timeout=")) {
m_hasBatchTimeout = true; // depends on control dependency: [if], data = [none]
String batchTimeoutStr = extractArgInput(arg);
if (batchTimeoutStr == null) return -1;
m_batchTimeout = Integer.valueOf(batchTimeoutStr); // depends on control dependency: [if], data = [none]
}
// equals check starting here
else if (arg.equals("--output-skip-metadata")) {
m_outputShowMetadata = false; // depends on control dependency: [if], data = [none]
}
else if (arg.startsWith("--ssl=")) {
enableSSL = true; // depends on control dependency: [if], data = [none]
sslConfigFile = extractArgInput(arg); // depends on control dependency: [if], data = [none]
if (sslConfigFile == null) return -1;
}
else if (arg.startsWith("--ssl")) {
enableSSL = true; // depends on control dependency: [if], data = [none]
sslConfigFile = null; // depends on control dependency: [if], data = [none]
}
else if (arg.equals("--debug")) {
m_debug = true; // depends on control dependency: [if], data = [none]
}
else if (arg.equals("--help")) {
printHelp(System.out); // Print readme to the screen // depends on control dependency: [if], data = [none]
System.out.println("\n\n"); // depends on control dependency: [if], data = [none]
printUsage(); // depends on control dependency: [if], data = [none]
return -1; // depends on control dependency: [if], data = [none]
}
else if (arg.equals("--no-version-check")) {
m_versionCheck = false; // Disable new version phone home check // depends on control dependency: [if], data = [none]
}
else if ((arg.equals("--usage")) || (arg.equals("-?"))) {
printUsage(); // depends on control dependency: [if], data = [none]
return -1; // depends on control dependency: [if], data = [none]
}
else {
printUsage("Invalid Parameter: " + arg); // depends on control dependency: [if], data = [none]
return -1; // depends on control dependency: [if], data = [none]
}
}
// Split server list
String[] servers = serverList.split(",");
// Phone home to see if there is a newer version of VoltDB
if (m_versionCheck) {
openURLAsync(); // depends on control dependency: [if], data = [none]
}
// read username and password from txt file
if (credentials != null && !credentials.trim().isEmpty()) {
Properties props = MiscUtils.readPropertiesFromCredentials(credentials);
user = props.getProperty("username"); // depends on control dependency: [if], data = [none]
password = props.getProperty("password"); // depends on control dependency: [if], data = [none]
}
try
{
// If we need to prompt the user for a password, do so.
password = CLIConfig.readPasswordIfNeeded(user, password, "Enter password: "); // depends on control dependency: [try], data = [none]
}
catch (IOException ex)
{
printUsage("Unable to read password: " + ex);
} // depends on control dependency: [catch], data = [none]
// Create connection
ClientConfig config = new ClientConfig(user, password, null);
if (enableSSL) {
if (sslConfigFile != null && !sslConfigFile.trim().isEmpty()) {
config.setTrustStoreConfigFromPropertyFile(sslConfigFile); // depends on control dependency: [if], data = [(sslConfigFile]
} else {
config.setTrustStoreConfigFromDefault(); // depends on control dependency: [if], data = [none]
}
config.enableSSL(); // depends on control dependency: [if], data = [none]
}
config.setProcedureCallTimeout(0); // Set procedure all to infinite timeout, see ENG-2670
try {
// if specified enable kerberos
if (!kerberos.isEmpty()) {
config.enableKerberosAuthentication(kerberos); // depends on control dependency: [if], data = [none]
}
m_client = getClient(config, servers, port); // depends on control dependency: [try], data = [none]
} catch (Exception exc) {
System.err.println(exc.getMessage());
return -1;
} // depends on control dependency: [catch], data = [none]
try {
if (! ddlFileText.equals("")) {
// fast DDL Loader mode
// System.out.println("fast DDL Loader mode with DDL input:\n" + ddlFile);
m_client.callProcedure("@AdHoc", ddlFileText); // depends on control dependency: [if], data = [none]
return m_exitCode; // depends on control dependency: [if], data = [none]
}
// Load system procedures
loadSystemProcedures(); // depends on control dependency: [try], data = [none]
// Load user stored procs
loadStoredProcedures(Procedures, Classlist); // depends on control dependency: [try], data = [none]
// Removed code to prevent Ctrl-C from exiting. The original code is visible
// in Git history hash 837df236c059b5b4362ffca7e7a5426fba1b7f20.
m_interactive = true; // depends on control dependency: [try], data = [none]
if (queries != null && !queries.isEmpty()) {
// If queries are provided via command line options run them in
// non-interactive mode.
//TODO: Someday we should honor batching.
m_interactive = false; // depends on control dependency: [if], data = [none]
for (String query : queries) {
executeStatement(query, null, 0); // depends on control dependency: [for], data = [query]
}
}
// This test for an interactive environment is mostly
// reliable. See stackoverflow.com/questions/1403772.
// It accurately detects when data is piped into the program
// but it fails to distinguish the case when data is ONLY piped
// OUT of the command -- that's a possible but very strange way
// to run an interactive session, so it's OK that we don't support
// it. Instead, in that edge case, we fall back to non-interactive
// mode but IN THAT MODE, we wait on and process user input as if
// from a slow pipe. Strange, but acceptable, and preferable to the
// check used here in the past (System.in.available() > 0)
// which would fail in the opposite direction, when a 0-length
// file was piped in, showing an interactive greeting and prompt
// before quitting.
if (System.console() == null && m_interactive) {
m_interactive = false; // depends on control dependency: [if], data = [none]
executeNoninteractive(); // depends on control dependency: [if], data = [none]
}
if (m_interactive) {
// Print out welcome message
System.out.printf("SQL Command :: %s%s:%d\n", (user == "" ? "" : user + "@"), serverList, port); // depends on control dependency: [if], data = [none]
interactWithTheUser(); // depends on control dependency: [if], data = [none]
}
}
catch (SQLCmdEarlyExitException e) {
return m_exitCode;
} // depends on control dependency: [catch], data = [none]
catch (Exception x) {
try { stopOrContinue(x); } catch (SQLCmdEarlyExitException e) { return m_exitCode; } // depends on control dependency: [try], data = [none] // depends on control dependency: [catch], data = [none]
} // depends on control dependency: [catch], data = [none]
finally {
try { m_client.close(); } catch (Exception x) { } // depends on control dependency: [try], data = [none] // depends on control dependency: [catch], data = [none]
}
// Processing may have been continued after one or more errors.
// Reflect them in the exit code.
// This might be a little unconventional for an interactive session,
// but it's also likely to be ignored in that case, so "no great harm done".
//* enable to debug */ System.err.println("Exiting with code " + m_exitCode);
return m_exitCode;
} } |
public class class_name {
@Override
public void parse(final String... parameters) {
// Manage gray scale
if (parameters.length >= 1) {
grayProperty().set(Double.parseDouble(parameters[0]));
}
// Opacity
if (parameters.length == 2) {
opacityProperty().set(Double.parseDouble(parameters[1]));
}
} } | public class class_name {
@Override
public void parse(final String... parameters) {
// Manage gray scale
if (parameters.length >= 1) {
grayProperty().set(Double.parseDouble(parameters[0]));
// depends on control dependency: [if], data = [none]
}
// Opacity
if (parameters.length == 2) {
opacityProperty().set(Double.parseDouble(parameters[1]));
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private void thirdPartyTransfer()
throws UrlCopyException {
logger.debug("Trying third party transfer...");
FTPClient srcFTP = null;
FTPClient dstFTP = null;
try {
srcFTP = createFTPConnection(srcUrl, true);
dstFTP = createFTPConnection(dstUrl, false);
negotiateDCAU(srcFTP, dstFTP);
srcFTP.setType(Session.TYPE_IMAGE);
dstFTP.setType(Session.TYPE_IMAGE);
if (listeners != null) {
fireUrlTransferProgressEvent(-1, -1);
}
if (this.sourceOffset == 0 &&
this.destinationOffset == 0 &&
this.sourceLength == Long.MAX_VALUE) {
srcFTP.setMode(Session.MODE_STREAM);
dstFTP.setMode(Session.MODE_STREAM);
srcFTP.transfer(srcUrl.getPath(),
dstFTP,
dstUrl.getPath(),
false,
null);
} else if (srcFTP instanceof GridFTPClient &&
dstFTP instanceof GridFTPClient) {
GridFTPClient srcGridFTP = (GridFTPClient) srcFTP;
GridFTPClient dstGridFTP = (GridFTPClient) dstFTP;
srcGridFTP.setMode(GridFTPSession.MODE_EBLOCK);
dstGridFTP.setMode(GridFTPSession.MODE_EBLOCK);
srcGridFTP.extendedTransfer(srcUrl.getPath(),
this.sourceOffset,
this.sourceLength,
dstGridFTP,
dstUrl.getPath(),
this.destinationOffset,
null);
} else {
throw new UrlCopyException("Partial 3rd party transfers not supported " +
"by FTP client. Use GridFTP for both source and destination.");
}
} catch(Exception e) {
throw new UrlCopyException("UrlCopy third party transfer failed.",
e);
} finally {
if (srcFTP != null) {
try { srcFTP.close(); } catch (Exception ee) {}
}
if (dstFTP != null) {
try { dstFTP.close(); } catch (Exception ee) {}
}
}
} } | public class class_name {
private void thirdPartyTransfer()
throws UrlCopyException {
logger.debug("Trying third party transfer...");
FTPClient srcFTP = null;
FTPClient dstFTP = null;
try {
srcFTP = createFTPConnection(srcUrl, true);
dstFTP = createFTPConnection(dstUrl, false);
negotiateDCAU(srcFTP, dstFTP);
srcFTP.setType(Session.TYPE_IMAGE);
dstFTP.setType(Session.TYPE_IMAGE);
if (listeners != null) {
fireUrlTransferProgressEvent(-1, -1); // depends on control dependency: [if], data = [none]
}
if (this.sourceOffset == 0 &&
this.destinationOffset == 0 &&
this.sourceLength == Long.MAX_VALUE) {
srcFTP.setMode(Session.MODE_STREAM); // depends on control dependency: [if], data = [none]
dstFTP.setMode(Session.MODE_STREAM); // depends on control dependency: [if], data = [none]
srcFTP.transfer(srcUrl.getPath(),
dstFTP,
dstUrl.getPath(),
false,
null); // depends on control dependency: [if], data = [none]
} else if (srcFTP instanceof GridFTPClient &&
dstFTP instanceof GridFTPClient) {
GridFTPClient srcGridFTP = (GridFTPClient) srcFTP;
GridFTPClient dstGridFTP = (GridFTPClient) dstFTP;
srcGridFTP.setMode(GridFTPSession.MODE_EBLOCK); // depends on control dependency: [if], data = [none]
dstGridFTP.setMode(GridFTPSession.MODE_EBLOCK); // depends on control dependency: [if], data = [none]
srcGridFTP.extendedTransfer(srcUrl.getPath(),
this.sourceOffset,
this.sourceLength,
dstGridFTP,
dstUrl.getPath(),
this.destinationOffset,
null); // depends on control dependency: [if], data = [none]
} else {
throw new UrlCopyException("Partial 3rd party transfers not supported " +
"by FTP client. Use GridFTP for both source and destination.");
}
} catch(Exception e) {
throw new UrlCopyException("UrlCopy third party transfer failed.",
e);
} finally {
if (srcFTP != null) {
try { srcFTP.close(); } catch (Exception ee) {} // depends on control dependency: [try], data = [none] // depends on control dependency: [catch], data = [none]
}
if (dstFTP != null) {
try { dstFTP.close(); } catch (Exception ee) {} // depends on control dependency: [try], data = [none] // depends on control dependency: [catch], data = [none]
}
}
} } |
public class class_name {
public void restart() {
sync.lock();
try {
stop();
Thread.sleep(1000); // allow some time to release native resources
start();
} catch (InterruptedException e) {
// ignore
} finally {
sync.unlock();
}
} } | public class class_name {
public void restart() {
sync.lock();
try {
stop(); // depends on control dependency: [try], data = [none]
Thread.sleep(1000); // allow some time to release native resources // depends on control dependency: [try], data = [none]
start(); // depends on control dependency: [try], data = [none]
} catch (InterruptedException e) {
// ignore
} finally { // depends on control dependency: [catch], data = [none]
sync.unlock();
}
} } |
public class class_name {
public static Service createService(String classNameKey,String defaultClassName,ConfigurationHolder configurationHolder,String propertyPart)
{
//validate input
if(configurationHolder==null)
{
throw new FaxException("Service configuration not provided.");
}
if(classNameKey==null)
{
throw new FaxException("Service class name key not provided.");
}
//get class name
String className=configurationHolder.getConfigurationValue(classNameKey);
if(className==null)
{
className=defaultClassName;
if(className==null)
{
throw new FaxException("Service class name not found in configuration and no default value provided.");
}
}
//get configuration
Map<String,String> configuration=configurationHolder.getConfiguration();
//create service
Service service=(Service)ReflectionHelper.createInstance(className);
//set property part
service.setPropertyPart(propertyPart);
//initialize service
service.initialize(configuration);
return service;
} } | public class class_name {
public static Service createService(String classNameKey,String defaultClassName,ConfigurationHolder configurationHolder,String propertyPart)
{
//validate input
if(configurationHolder==null)
{
throw new FaxException("Service configuration not provided.");
}
if(classNameKey==null)
{
throw new FaxException("Service class name key not provided.");
}
//get class name
String className=configurationHolder.getConfigurationValue(classNameKey);
if(className==null)
{
className=defaultClassName; // depends on control dependency: [if], data = [none]
if(className==null)
{
throw new FaxException("Service class name not found in configuration and no default value provided.");
}
}
//get configuration
Map<String,String> configuration=configurationHolder.getConfiguration();
//create service
Service service=(Service)ReflectionHelper.createInstance(className);
//set property part
service.setPropertyPart(propertyPart);
//initialize service
service.initialize(configuration);
return service;
} } |
public class class_name {
public int compareIntervalOrder(Interval<E> other)
{
int flags = getRelationFlags(other);
if (checkFlagExclusiveSet(flags, REL_FLAGS_INTERVAL_BEFORE, REL_FLAGS_INTERVAL_UNKNOWN)) {
return -1;
} else if (checkFlagExclusiveSet(flags, REL_FLAGS_INTERVAL_AFTER, REL_FLAGS_INTERVAL_UNKNOWN)) {
return 1;
} else {
return 0;
}
} } | public class class_name {
public int compareIntervalOrder(Interval<E> other)
{
int flags = getRelationFlags(other);
if (checkFlagExclusiveSet(flags, REL_FLAGS_INTERVAL_BEFORE, REL_FLAGS_INTERVAL_UNKNOWN)) {
return -1;
// depends on control dependency: [if], data = [none]
} else if (checkFlagExclusiveSet(flags, REL_FLAGS_INTERVAL_AFTER, REL_FLAGS_INTERVAL_UNKNOWN)) {
return 1;
// depends on control dependency: [if], data = [none]
} else {
return 0;
// depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
private void removeInstance() {
// unregister client
ClientRegistry ref = registry.get();
if (ref != null) {
ref.removeClient(this);
} else {
log.warn("Client registry reference was not accessable, removal failed");
// TODO: attempt to lookup the registry via the global.clientRegistry
}
} } | public class class_name {
private void removeInstance() {
// unregister client
ClientRegistry ref = registry.get();
if (ref != null) {
ref.removeClient(this);
// depends on control dependency: [if], data = [none]
} else {
log.warn("Client registry reference was not accessable, removal failed");
// depends on control dependency: [if], data = [none]
// TODO: attempt to lookup the registry via the global.clientRegistry
}
} } |
public class class_name {
private void removeNavigationFrameView(SwingFrame frameView) {
navigationFrames.remove(frameView);
if (navigationFrames.size() == 0) {
System.exit(0);
}
} } | public class class_name {
private void removeNavigationFrameView(SwingFrame frameView) {
navigationFrames.remove(frameView);
if (navigationFrames.size() == 0) {
System.exit(0); // depends on control dependency: [if], data = [0)]
}
} } |
public class class_name {
@Override
public String configurationInfo()
{
StringBuilder result = new StringBuilder();
result.append("MediaWikiParser configuration:\n");
result.append("ParserClass: " + this.getClass() + "\n");
result.append("ShowImageText: " + showImageText + "\n");
result.append("DeleteTags: " + deleteTags + "\n");
result.append("ShowMathTagContent: " + showMathTagContent + "\n");
result.append("CalculateSrcSpans: " + calculateSrcSpans + "\n");
result.append("LanguageIdentifers: ");
for (String s : languageIdentifers)
{
result.append(s + " ");
}
result.append("\n");
result.append("CategoryIdentifers: ");
for (String s : categoryIdentifers)
{
result.append(s + " ");
}
result.append("\n");
result.append("ImageIdentifers: ");
for (String s : imageIdentifers)
{
result.append(s + " ");
}
result.append("\n");
result.append("TemplateParser: " + templateParser.getClass() + "\n");
result.append(templateParser.configurationInfo());
return result.toString();
} } | public class class_name {
@Override
public String configurationInfo()
{
StringBuilder result = new StringBuilder();
result.append("MediaWikiParser configuration:\n");
result.append("ParserClass: " + this.getClass() + "\n");
result.append("ShowImageText: " + showImageText + "\n");
result.append("DeleteTags: " + deleteTags + "\n");
result.append("ShowMathTagContent: " + showMathTagContent + "\n");
result.append("CalculateSrcSpans: " + calculateSrcSpans + "\n");
result.append("LanguageIdentifers: ");
for (String s : languageIdentifers)
{
result.append(s + " "); // depends on control dependency: [for], data = [s]
}
result.append("\n");
result.append("CategoryIdentifers: ");
for (String s : categoryIdentifers)
{
result.append(s + " "); // depends on control dependency: [for], data = [s]
}
result.append("\n");
result.append("ImageIdentifers: ");
for (String s : imageIdentifers)
{
result.append(s + " "); // depends on control dependency: [for], data = [s]
}
result.append("\n");
result.append("TemplateParser: " + templateParser.getClass() + "\n");
result.append(templateParser.configurationInfo());
return result.toString();
} } |
public class class_name {
@Override
protected void submitRedoMeta(final int futureUse) {
if (!useRedo) {
return;
}
createRedoThread();
final ByteBuffer buf = bufstack.pop();
buf.putInt(0x0C0C0C0C); // META HEADER/FOOTER
buf.flip();
if (useRedoThread) {
try {
redoQueue.put(buf);
} catch (InterruptedException e) {
log.error("InterruptedException in submitRedoMeta(" + futureUse + ")", e);
}
} else {
redoStore.write(buf);
bufstack.push(buf);
}
} } | public class class_name {
@Override
protected void submitRedoMeta(final int futureUse) {
if (!useRedo) {
return; // depends on control dependency: [if], data = [none]
}
createRedoThread();
final ByteBuffer buf = bufstack.pop();
buf.putInt(0x0C0C0C0C); // META HEADER/FOOTER
buf.flip();
if (useRedoThread) {
try {
redoQueue.put(buf); // depends on control dependency: [try], data = [none]
} catch (InterruptedException e) {
log.error("InterruptedException in submitRedoMeta(" + futureUse + ")", e);
} // depends on control dependency: [catch], data = [none]
} else {
redoStore.write(buf); // depends on control dependency: [if], data = [none]
bufstack.push(buf); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@SuppressWarnings("unchecked")
public <T extends ApnsPushNotification> PushNotificationFuture<T, PushNotificationResponse<T>> sendNotification(final T notification) {
final PushNotificationFuture<T, PushNotificationResponse<T>> responseFuture;
if (!this.isClosed.get()) {
final PushNotificationPromise<T, PushNotificationResponse<T>> responsePromise =
new PushNotificationPromise<>(this.eventLoopGroup.next(), notification);
final long notificationId = this.nextNotificationId.getAndIncrement();
this.channelPool.acquire().addListener(new GenericFutureListener<Future<Channel>>() {
@Override
public void operationComplete(final Future<Channel> acquireFuture) throws Exception {
if (acquireFuture.isSuccess()) {
final Channel channel = acquireFuture.getNow();
channel.writeAndFlush(responsePromise).addListener(new GenericFutureListener<ChannelFuture>() {
@Override
public void operationComplete(final ChannelFuture future) throws Exception {
if (future.isSuccess()) {
ApnsClient.this.metricsListener.handleNotificationSent(ApnsClient.this, notificationId);
}
}
});
ApnsClient.this.channelPool.release(channel);
} else {
responsePromise.tryFailure(acquireFuture.cause());
}
}
});
responsePromise.addListener(new PushNotificationResponseListener<T>() {
@Override
public void operationComplete(final PushNotificationFuture<T, PushNotificationResponse<T>> future) throws Exception {
if (future.isSuccess()) {
final PushNotificationResponse response = future.getNow();
if (response.isAccepted()) {
ApnsClient.this.metricsListener.handleNotificationAccepted(ApnsClient.this, notificationId);
} else {
ApnsClient.this.metricsListener.handleNotificationRejected(ApnsClient.this, notificationId);
}
} else {
ApnsClient.this.metricsListener.handleWriteFailure(ApnsClient.this, notificationId);
}
}
});
responseFuture = responsePromise;
} else {
final PushNotificationPromise<T, PushNotificationResponse<T>> failedPromise =
new PushNotificationPromise<>(GlobalEventExecutor.INSTANCE, notification);
failedPromise.setFailure(CLIENT_CLOSED_EXCEPTION);
responseFuture = failedPromise;
}
return responseFuture;
} } | public class class_name {
@SuppressWarnings("unchecked")
public <T extends ApnsPushNotification> PushNotificationFuture<T, PushNotificationResponse<T>> sendNotification(final T notification) {
final PushNotificationFuture<T, PushNotificationResponse<T>> responseFuture;
if (!this.isClosed.get()) {
final PushNotificationPromise<T, PushNotificationResponse<T>> responsePromise =
new PushNotificationPromise<>(this.eventLoopGroup.next(), notification);
final long notificationId = this.nextNotificationId.getAndIncrement();
this.channelPool.acquire().addListener(new GenericFutureListener<Future<Channel>>() {
@Override
public void operationComplete(final Future<Channel> acquireFuture) throws Exception {
if (acquireFuture.isSuccess()) {
final Channel channel = acquireFuture.getNow();
channel.writeAndFlush(responsePromise).addListener(new GenericFutureListener<ChannelFuture>() {
@Override
public void operationComplete(final ChannelFuture future) throws Exception {
if (future.isSuccess()) {
ApnsClient.this.metricsListener.handleNotificationSent(ApnsClient.this, notificationId); // depends on control dependency: [if], data = [none]
}
}
}); // depends on control dependency: [if], data = [none]
ApnsClient.this.channelPool.release(channel); // depends on control dependency: [if], data = [none]
} else {
responsePromise.tryFailure(acquireFuture.cause()); // depends on control dependency: [if], data = [none]
}
}
});
responsePromise.addListener(new PushNotificationResponseListener<T>() {
@Override
public void operationComplete(final PushNotificationFuture<T, PushNotificationResponse<T>> future) throws Exception {
if (future.isSuccess()) {
final PushNotificationResponse response = future.getNow();
if (response.isAccepted()) {
ApnsClient.this.metricsListener.handleNotificationAccepted(ApnsClient.this, notificationId);
} else {
ApnsClient.this.metricsListener.handleNotificationRejected(ApnsClient.this, notificationId);
}
} else {
ApnsClient.this.metricsListener.handleWriteFailure(ApnsClient.this, notificationId);
}
}
});
responseFuture = responsePromise;
} else {
final PushNotificationPromise<T, PushNotificationResponse<T>> failedPromise =
new PushNotificationPromise<>(GlobalEventExecutor.INSTANCE, notification);
failedPromise.setFailure(CLIENT_CLOSED_EXCEPTION);
responseFuture = failedPromise;
}
return responseFuture;
} } |
public class class_name {
@Override
public CommerceAccount fetchByU_T_First(long userId, int type,
OrderByComparator<CommerceAccount> orderByComparator) {
List<CommerceAccount> list = findByU_T(userId, type, 0, 1,
orderByComparator);
if (!list.isEmpty()) {
return list.get(0);
}
return null;
} } | public class class_name {
@Override
public CommerceAccount fetchByU_T_First(long userId, int type,
OrderByComparator<CommerceAccount> orderByComparator) {
List<CommerceAccount> list = findByU_T(userId, type, 0, 1,
orderByComparator);
if (!list.isEmpty()) {
return list.get(0); // depends on control dependency: [if], data = [none]
}
return null;
} } |
public class class_name {
public boolean accept(String kind, String mimetype) {
if (m_includeAll) {
return true;
}
int slashpos = mimetype.indexOf("/");
String supertype = mimetype.substring(0, slashpos);
return m_kinds.contains(kind) || m_types.contains(mimetype) || m_supertypes.contains(supertype);
} } | public class class_name {
public boolean accept(String kind, String mimetype) {
if (m_includeAll) {
return true;
// depends on control dependency: [if], data = [none]
}
int slashpos = mimetype.indexOf("/");
String supertype = mimetype.substring(0, slashpos);
return m_kinds.contains(kind) || m_types.contains(mimetype) || m_supertypes.contains(supertype);
} } |
public class class_name {
public String replaceDocRootDir(String htmlstr) {
// Return if no inline tags exist
int index = htmlstr.indexOf("{@");
if (index < 0) {
return htmlstr;
}
Matcher docrootMatcher = docrootPattern.matcher(htmlstr);
if (!docrootMatcher.find()) {
return htmlstr;
}
StringBuilder buf = new StringBuilder();
int prevEnd = 0;
do {
int match = docrootMatcher.start();
// append htmlstr up to start of next {@docroot}
buf.append(htmlstr.substring(prevEnd, match));
prevEnd = docrootMatcher.end();
if (configuration.docrootparent.length() > 0 && htmlstr.startsWith("/..", prevEnd)) {
// Insert the absolute link if {@docRoot} is followed by "/..".
buf.append(configuration.docrootparent);
prevEnd += 3;
} else {
// Insert relative path where {@docRoot} was located
buf.append(pathToRoot.isEmpty() ? "." : pathToRoot.getPath());
}
// Append slash if next character is not a slash
if (prevEnd < htmlstr.length() && htmlstr.charAt(prevEnd) != '/') {
buf.append('/');
}
} while (docrootMatcher.find());
buf.append(htmlstr.substring(prevEnd));
return buf.toString();
} } | public class class_name {
public String replaceDocRootDir(String htmlstr) {
// Return if no inline tags exist
int index = htmlstr.indexOf("{@");
if (index < 0) {
return htmlstr; // depends on control dependency: [if], data = [none]
}
Matcher docrootMatcher = docrootPattern.matcher(htmlstr);
if (!docrootMatcher.find()) {
return htmlstr; // depends on control dependency: [if], data = [none]
}
StringBuilder buf = new StringBuilder();
int prevEnd = 0;
do {
int match = docrootMatcher.start();
// append htmlstr up to start of next {@docroot}
buf.append(htmlstr.substring(prevEnd, match));
prevEnd = docrootMatcher.end();
if (configuration.docrootparent.length() > 0 && htmlstr.startsWith("/..", prevEnd)) {
// Insert the absolute link if {@docRoot} is followed by "/..".
buf.append(configuration.docrootparent); // depends on control dependency: [if], data = [none]
prevEnd += 3; // depends on control dependency: [if], data = [none]
} else {
// Insert relative path where {@docRoot} was located
buf.append(pathToRoot.isEmpty() ? "." : pathToRoot.getPath()); // depends on control dependency: [if], data = [none]
}
// Append slash if next character is not a slash
if (prevEnd < htmlstr.length() && htmlstr.charAt(prevEnd) != '/') {
buf.append('/'); // depends on control dependency: [if], data = ['/')]
}
} while (docrootMatcher.find());
buf.append(htmlstr.substring(prevEnd));
return buf.toString();
} } |
public class class_name {
@Override
public void uncaughtException(Thread thread, Throwable thrown) {
if (enabled) {
logger.trace("Uncaught exception received.");
EventBuilder eventBuilder = new EventBuilder()
.withMessage(thrown.getMessage())
.withLevel(Event.Level.FATAL)
.withSentryInterface(new ExceptionInterface(thrown));
try {
Sentry.capture(eventBuilder);
} catch (Exception e) {
logger.error("Error sending uncaught exception to Sentry.", e);
}
}
// taken from ThreadGroup#uncaughtException
if (defaultExceptionHandler != null) {
// call the original handler
defaultExceptionHandler.uncaughtException(thread, thrown);
} else if (!(thrown instanceof ThreadDeath)) {
// CHECKSTYLE.OFF: RegexpSinglelineJava
System.err.print("Exception in thread \"" + thread.getName() + "\" ");
thrown.printStackTrace(System.err);
// CHECKSTYLE.ON: RegexpSinglelineJava
}
} } | public class class_name {
@Override
public void uncaughtException(Thread thread, Throwable thrown) {
if (enabled) {
logger.trace("Uncaught exception received."); // depends on control dependency: [if], data = [none]
EventBuilder eventBuilder = new EventBuilder()
.withMessage(thrown.getMessage())
.withLevel(Event.Level.FATAL)
.withSentryInterface(new ExceptionInterface(thrown));
try {
Sentry.capture(eventBuilder); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
logger.error("Error sending uncaught exception to Sentry.", e);
} // depends on control dependency: [catch], data = [none]
}
// taken from ThreadGroup#uncaughtException
if (defaultExceptionHandler != null) {
// call the original handler
defaultExceptionHandler.uncaughtException(thread, thrown); // depends on control dependency: [if], data = [none]
} else if (!(thrown instanceof ThreadDeath)) {
// CHECKSTYLE.OFF: RegexpSinglelineJava
System.err.print("Exception in thread \"" + thread.getName() + "\" "); // depends on control dependency: [if], data = [none]
thrown.printStackTrace(System.err); // depends on control dependency: [if], data = [none]
// CHECKSTYLE.ON: RegexpSinglelineJava
}
} } |
public class class_name {
public boolean isFlowActive() {
Object val = this.getArgument("active");
if (val instanceof Integer) {
return ((Integer)val).intValue() == 1;
}
else {
throw new IllegalStateException("ChannelEvent does not contain the 'active' argument");
}
} } | public class class_name {
public boolean isFlowActive() {
Object val = this.getArgument("active");
if (val instanceof Integer) {
return ((Integer)val).intValue() == 1; // depends on control dependency: [if], data = [none]
}
else {
throw new IllegalStateException("ChannelEvent does not contain the 'active' argument");
}
} } |
public class class_name {
public static Array listToArrayTrim(String list, String delimiter, int[] info) {
if (delimiter.length() == 1) return listToArrayTrim(list, delimiter.charAt(0), info);
if (list.length() == 0) return new ArrayImpl();
char[] del = delimiter.toCharArray();
char c;
// remove at start
outer: while (list.length() > 0) {
c = list.charAt(0);
for (int i = 0; i < del.length; i++) {
if (c == del[i]) {
info[0]++;
list = list.substring(1);
continue outer;
}
}
break;
}
int len;
outer: while (list.length() > 0) {
c = list.charAt(list.length() - 1);
for (int i = 0; i < del.length; i++) {
if (c == del[i]) {
info[1]++;
len = list.length();
list = list.substring(0, len - 1 < 0 ? 0 : len - 1);
continue outer;
}
}
break;
}
return listToArray(list, delimiter);
} } | public class class_name {
public static Array listToArrayTrim(String list, String delimiter, int[] info) {
if (delimiter.length() == 1) return listToArrayTrim(list, delimiter.charAt(0), info);
if (list.length() == 0) return new ArrayImpl();
char[] del = delimiter.toCharArray();
char c;
// remove at start
outer: while (list.length() > 0) {
c = list.charAt(0); // depends on control dependency: [while], data = [0)]
for (int i = 0; i < del.length; i++) {
if (c == del[i]) {
info[0]++; // depends on control dependency: [if], data = [none]
list = list.substring(1); // depends on control dependency: [if], data = [none]
continue outer;
}
}
break;
}
int len;
outer: while (list.length() > 0) {
c = list.charAt(list.length() - 1); // depends on control dependency: [while], data = [(list.length()]
for (int i = 0; i < del.length; i++) {
if (c == del[i]) {
info[1]++; // depends on control dependency: [if], data = [none]
len = list.length(); // depends on control dependency: [if], data = [none]
list = list.substring(0, len - 1 < 0 ? 0 : len - 1); // depends on control dependency: [if], data = [none]
continue outer;
}
}
break;
}
return listToArray(list, delimiter);
} } |
public class class_name {
public DescribePlayerSessionsResult withPlayerSessions(PlayerSession... playerSessions) {
if (this.playerSessions == null) {
setPlayerSessions(new java.util.ArrayList<PlayerSession>(playerSessions.length));
}
for (PlayerSession ele : playerSessions) {
this.playerSessions.add(ele);
}
return this;
} } | public class class_name {
public DescribePlayerSessionsResult withPlayerSessions(PlayerSession... playerSessions) {
if (this.playerSessions == null) {
setPlayerSessions(new java.util.ArrayList<PlayerSession>(playerSessions.length)); // depends on control dependency: [if], data = [none]
}
for (PlayerSession ele : playerSessions) {
this.playerSessions.add(ele); // depends on control dependency: [for], data = [ele]
}
return this;
} } |
public class class_name {
public void initBatch(
TypeDescription orcSchema,
StructField[] requiredFields,
int[] requestedDataColIds,
int[] requestedPartitionColIds,
InternalRow partitionValues) {
wrap = new VectorizedRowBatchWrap(orcSchema.createRowBatch(capacity));
assert(!wrap.batch().selectedInUse); // `selectedInUse` should be initialized with `false`.
assert(requiredFields.length == requestedDataColIds.length);
assert(requiredFields.length == requestedPartitionColIds.length);
// If a required column is also partition column, use partition value and don't read from file.
for (int i = 0; i < requiredFields.length; i++) {
if (requestedPartitionColIds[i] != -1) {
requestedDataColIds[i] = -1;
}
}
this.requiredFields = requiredFields;
this.requestedDataColIds = requestedDataColIds;
StructType resultSchema = new StructType(requiredFields);
// Just wrap the ORC column vector instead of copying it to Spark column vector.
orcVectorWrappers = new org.apache.spark.sql.vectorized.ColumnVector[resultSchema.length()];
for (int i = 0; i < requiredFields.length; i++) {
DataType dt = requiredFields[i].dataType();
if (requestedPartitionColIds[i] != -1) {
OnHeapColumnVector partitionCol = new OnHeapColumnVector(capacity, dt);
ColumnVectorUtils.populate(partitionCol, partitionValues, requestedPartitionColIds[i]);
partitionCol.setIsConstant();
orcVectorWrappers[i] = partitionCol;
} else {
int colId = requestedDataColIds[i];
// Initialize the missing columns once.
if (colId == -1) {
OnHeapColumnVector missingCol = new OnHeapColumnVector(capacity, dt);
missingCol.putNulls(0, capacity);
missingCol.setIsConstant();
orcVectorWrappers[i] = missingCol;
} else {
orcVectorWrappers[i] = new OrcColumnVector(dt, wrap.batch().cols[colId]);
}
}
}
columnarBatch = new ColumnarBatch(orcVectorWrappers);
} } | public class class_name {
public void initBatch(
TypeDescription orcSchema,
StructField[] requiredFields,
int[] requestedDataColIds,
int[] requestedPartitionColIds,
InternalRow partitionValues) {
wrap = new VectorizedRowBatchWrap(orcSchema.createRowBatch(capacity));
assert(!wrap.batch().selectedInUse); // `selectedInUse` should be initialized with `false`.
assert(requiredFields.length == requestedDataColIds.length);
assert(requiredFields.length == requestedPartitionColIds.length);
// If a required column is also partition column, use partition value and don't read from file.
for (int i = 0; i < requiredFields.length; i++) {
if (requestedPartitionColIds[i] != -1) {
requestedDataColIds[i] = -1; // depends on control dependency: [if], data = [none]
}
}
this.requiredFields = requiredFields;
this.requestedDataColIds = requestedDataColIds;
StructType resultSchema = new StructType(requiredFields);
// Just wrap the ORC column vector instead of copying it to Spark column vector.
orcVectorWrappers = new org.apache.spark.sql.vectorized.ColumnVector[resultSchema.length()];
for (int i = 0; i < requiredFields.length; i++) {
DataType dt = requiredFields[i].dataType();
if (requestedPartitionColIds[i] != -1) {
OnHeapColumnVector partitionCol = new OnHeapColumnVector(capacity, dt);
ColumnVectorUtils.populate(partitionCol, partitionValues, requestedPartitionColIds[i]); // depends on control dependency: [if], data = [none]
partitionCol.setIsConstant(); // depends on control dependency: [if], data = [none]
orcVectorWrappers[i] = partitionCol; // depends on control dependency: [if], data = [none]
} else {
int colId = requestedDataColIds[i];
// Initialize the missing columns once.
if (colId == -1) {
OnHeapColumnVector missingCol = new OnHeapColumnVector(capacity, dt);
missingCol.putNulls(0, capacity); // depends on control dependency: [if], data = [none]
missingCol.setIsConstant(); // depends on control dependency: [if], data = [none]
orcVectorWrappers[i] = missingCol; // depends on control dependency: [if], data = [none]
} else {
orcVectorWrappers[i] = new OrcColumnVector(dt, wrap.batch().cols[colId]); // depends on control dependency: [if], data = [none]
}
}
}
columnarBatch = new ColumnarBatch(orcVectorWrappers);
} } |
public class class_name {
public void buildFieldInfo(XMLNode node, Content fieldsContentTree) {
if(configuration.nocomment){
return;
}
VariableElement field = (VariableElement)currentMember;
TypeElement te = utils.getEnclosingTypeElement(currentMember);
// Process default Serializable field.
if ((utils.getSerialTrees(field).isEmpty()) /*&& ! field.isSynthetic()*/
&& configuration.serialwarn) {
messages.warning(field,
"doclet.MissingSerialTag", utils.getFullyQualifiedName(te),
utils.getSimpleName(field));
}
fieldWriter.addMemberDescription(field, fieldsContentTree);
fieldWriter.addMemberTags(field, fieldsContentTree);
} } | public class class_name {
public void buildFieldInfo(XMLNode node, Content fieldsContentTree) {
if(configuration.nocomment){
return; // depends on control dependency: [if], data = [none]
}
VariableElement field = (VariableElement)currentMember;
TypeElement te = utils.getEnclosingTypeElement(currentMember);
// Process default Serializable field.
if ((utils.getSerialTrees(field).isEmpty()) /*&& ! field.isSynthetic()*/
&& configuration.serialwarn) {
messages.warning(field,
"doclet.MissingSerialTag", utils.getFullyQualifiedName(te),
utils.getSimpleName(field)); // depends on control dependency: [if], data = [none]
}
fieldWriter.addMemberDescription(field, fieldsContentTree);
fieldWriter.addMemberTags(field, fieldsContentTree);
} } |
public class class_name {
@SuppressWarnings("rawtypes")
public Columns columns(Row row) {
ColumnFamily columnFamily = row.cf;
Columns columns = new Columns();
// Get row's columns iterator skipping clustering column
Iterator<Cell> cellIterator = columnFamily.iterator();
cellIterator.next();
// Stuff for grouping collection columns (sets, lists and maps)
String name;
CollectionType collectionType;
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
CellName cellName = cell.name();
ColumnDefinition columnDefinition = metadata.getColumnDefinition(cellName);
if (columnDefinition == null) {
continue;
}
AbstractType<?> valueType = columnDefinition.type;
ByteBuffer cellValue = cell.value();
name = cellName.cql3ColumnName(metadata).toString();
if (valueType.isCollection()) {
collectionType = (CollectionType<?>) valueType;
switch (collectionType.kind) {
case SET: {
AbstractType<?> type = collectionType.nameComparator();
ByteBuffer value = cellName.collectionElement();
columns.add(Column.fromDecomposed(name, value, type));
break;
}
case LIST: {
AbstractType<?> type = collectionType.valueComparator();
columns.add(Column.fromDecomposed(name, cellValue, type));
break;
}
case MAP: {
AbstractType<?> type = collectionType.valueComparator();
ByteBuffer keyValue = cellName.collectionElement();
AbstractType<?> keyType = collectionType.nameComparator();
String nameSufix = keyType.compose(keyValue).toString();
columns.add(Column.fromDecomposed(name, nameSufix, cellValue, type));
break;
}
}
} else {
columns.add(Column.fromDecomposed(name, cellValue, valueType));
}
}
return columns;
} } | public class class_name {
@SuppressWarnings("rawtypes")
public Columns columns(Row row) {
ColumnFamily columnFamily = row.cf;
Columns columns = new Columns();
// Get row's columns iterator skipping clustering column
Iterator<Cell> cellIterator = columnFamily.iterator();
cellIterator.next();
// Stuff for grouping collection columns (sets, lists and maps)
String name;
CollectionType collectionType;
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
CellName cellName = cell.name();
ColumnDefinition columnDefinition = metadata.getColumnDefinition(cellName);
if (columnDefinition == null) {
continue;
}
AbstractType<?> valueType = columnDefinition.type;
ByteBuffer cellValue = cell.value();
name = cellName.cql3ColumnName(metadata).toString(); // depends on control dependency: [while], data = [none]
if (valueType.isCollection()) {
collectionType = (CollectionType<?>) valueType; // depends on control dependency: [if], data = [none]
switch (collectionType.kind) {
case SET: {
AbstractType<?> type = collectionType.nameComparator();
ByteBuffer value = cellName.collectionElement();
columns.add(Column.fromDecomposed(name, value, type));
break;
}
case LIST: {
AbstractType<?> type = collectionType.valueComparator();
columns.add(Column.fromDecomposed(name, cellValue, type)); // depends on control dependency: [if], data = [none]
break;
}
case MAP: {
AbstractType<?> type = collectionType.valueComparator();
ByteBuffer keyValue = cellName.collectionElement();
AbstractType<?> keyType = collectionType.nameComparator();
String nameSufix = keyType.compose(keyValue).toString();
columns.add(Column.fromDecomposed(name, nameSufix, cellValue, type)); // depends on control dependency: [while], data = [none]
break;
}
}
} else {
columns.add(Column.fromDecomposed(name, cellValue, valueType));
}
}
return columns;
} } |
public class class_name {
public long run(int agent_id, String phone_no, long call_id, TimestampType start_ts) {
voltQueueSQL(findOpenCall, EXPECT_ZERO_OR_ONE_ROW, call_id, agent_id, phone_no);
voltQueueSQL(findCompletedCall, EXPECT_ZERO_OR_ONE_ROW, call_id, agent_id, phone_no);
VoltTable[] results = voltExecuteSQL();
boolean completedCall = results[1].getRowCount() > 0;
if (completedCall) {
return -1;
}
VoltTable openRowTable = results[0];
if (openRowTable.getRowCount() > 0) {
VoltTableRow existingCall = openRowTable.fetchRow(0);
// check if this is the second begin we've seen for this open call
existingCall.getTimestampAsTimestamp("start_ts");
if (existingCall.wasNull() == false) {
return -1;
}
// check if this completes the call
TimestampType end_ts = existingCall.getTimestampAsTimestamp("end_ts");
if (existingCall.wasNull() == false) {
int durationms = (int) ((end_ts.getTime() - start_ts.getTime()) / 1000);
// update per-day running stddev calculation
computeRunningStdDev(agent_id, end_ts, durationms);
// completes the call
voltQueueSQL(deleteOpenCall, EXPECT_SCALAR_MATCH(1),
call_id, agent_id, phone_no);
voltQueueSQL(insertCompletedCall, EXPECT_SCALAR_MATCH(1),
call_id, agent_id, phone_no, start_ts, end_ts, durationms);
voltExecuteSQL(true);
return 0;
}
}
voltQueueSQL(upsertOpenCall, EXPECT_SCALAR_MATCH(1), call_id, agent_id, phone_no, start_ts);
voltExecuteSQL(true);
return 0;
} } | public class class_name {
public long run(int agent_id, String phone_no, long call_id, TimestampType start_ts) {
voltQueueSQL(findOpenCall, EXPECT_ZERO_OR_ONE_ROW, call_id, agent_id, phone_no);
voltQueueSQL(findCompletedCall, EXPECT_ZERO_OR_ONE_ROW, call_id, agent_id, phone_no);
VoltTable[] results = voltExecuteSQL();
boolean completedCall = results[1].getRowCount() > 0;
if (completedCall) {
return -1; // depends on control dependency: [if], data = [none]
}
VoltTable openRowTable = results[0];
if (openRowTable.getRowCount() > 0) {
VoltTableRow existingCall = openRowTable.fetchRow(0);
// check if this is the second begin we've seen for this open call
existingCall.getTimestampAsTimestamp("start_ts"); // depends on control dependency: [if], data = [none]
if (existingCall.wasNull() == false) {
return -1; // depends on control dependency: [if], data = [none]
}
// check if this completes the call
TimestampType end_ts = existingCall.getTimestampAsTimestamp("end_ts");
if (existingCall.wasNull() == false) {
int durationms = (int) ((end_ts.getTime() - start_ts.getTime()) / 1000);
// update per-day running stddev calculation
computeRunningStdDev(agent_id, end_ts, durationms); // depends on control dependency: [if], data = [none]
// completes the call
voltQueueSQL(deleteOpenCall, EXPECT_SCALAR_MATCH(1),
call_id, agent_id, phone_no); // depends on control dependency: [if], data = [none]
voltQueueSQL(insertCompletedCall, EXPECT_SCALAR_MATCH(1),
call_id, agent_id, phone_no, start_ts, end_ts, durationms); // depends on control dependency: [if], data = [none]
voltExecuteSQL(true); // depends on control dependency: [if], data = [none]
return 0; // depends on control dependency: [if], data = [none]
}
}
voltQueueSQL(upsertOpenCall, EXPECT_SCALAR_MATCH(1), call_id, agent_id, phone_no, start_ts);
voltExecuteSQL(true);
return 0;
} } |
public class class_name {
private boolean isSharingEnabledForNode(BuildContext context, BaseNode node) {
if ( NodeTypeEnums.isLeftTupleSource( node )) {
return context.getKnowledgeBase().getConfiguration().isShareBetaNodes();
} else if ( NodeTypeEnums.isObjectSource( node ) ) {
return context.getKnowledgeBase().getConfiguration().isShareAlphaNodes();
}
return false;
} } | public class class_name {
private boolean isSharingEnabledForNode(BuildContext context, BaseNode node) {
if ( NodeTypeEnums.isLeftTupleSource( node )) {
return context.getKnowledgeBase().getConfiguration().isShareBetaNodes(); // depends on control dependency: [if], data = [none]
} else if ( NodeTypeEnums.isObjectSource( node ) ) {
return context.getKnowledgeBase().getConfiguration().isShareAlphaNodes(); // depends on control dependency: [if], data = [none]
}
return false;
} } |
public class class_name {
public static int readUntil (final StringBuilder out, final String in, final int start, final char... end)
{
int pos = start;
while (pos < in.length ())
{
final char ch = in.charAt (pos);
if (ch == '\\' && pos + 1 < in.length ())
{
pos = _escape (out, in.charAt (pos + 1), pos);
}
else
{
boolean endReached = false;
for (final char element : end)
{
if (ch == element)
{
endReached = true;
break;
}
}
if (endReached)
break;
out.append (ch);
}
pos++;
}
return pos == in.length () ? -1 : pos;
} } | public class class_name {
public static int readUntil (final StringBuilder out, final String in, final int start, final char... end)
{
int pos = start;
while (pos < in.length ())
{
final char ch = in.charAt (pos);
if (ch == '\\' && pos + 1 < in.length ())
{
pos = _escape (out, in.charAt (pos + 1), pos); // depends on control dependency: [if], data = [none]
}
else
{
boolean endReached = false;
for (final char element : end)
{
if (ch == element)
{
endReached = true; // depends on control dependency: [if], data = [none]
break;
}
}
if (endReached)
break;
out.append (ch); // depends on control dependency: [if], data = [(ch]
}
pos++; // depends on control dependency: [while], data = [none]
}
return pos == in.length () ? -1 : pos;
} } |
public class class_name {
private StreamBlock pollPersistentDeque(boolean actuallyPoll) {
BBContainer cont = null;
BBContainer schemaCont = null;
try {
// Start to read a new segment
if (m_reader.isStartOfSegment()) {
schemaCont = m_reader.getExtraHeader(-1);
}
cont = m_reader.poll(PersistentBinaryDeque.UNSAFE_CONTAINER_FACTORY);
} catch (IOException e) {
exportLog.error("Failed to poll from persistent binary deque:" + e);
}
if (cont == null) {
if (schemaCont != null) {
schemaCont.discard();
}
return null;
} else {
long segmentIndex = m_reader.getSegmentIndex();
cont.b().order(ByteOrder.LITTLE_ENDIAN);
//If the container is not null, unpack it.
final BBContainer fcont = cont;
long seqNo = cont.b().getLong(StreamBlock.SEQUENCE_NUMBER_OFFSET);
long committedSeqNo = cont.b().getLong(StreamBlock.COMMIT_SEQUENCE_NUMBER_OFFSET);
int tupleCount = cont.b().getInt(StreamBlock.ROW_NUMBER_OFFSET);
long uniqueId = cont.b().getLong(StreamBlock.UNIQUE_ID_OFFSET);
//Pass the stream block a subset of the bytes, provide
//a container that discards the original returned by the persistent deque
StreamBlock block = new StreamBlock( fcont,
schemaCont,
seqNo,
committedSeqNo,
tupleCount,
uniqueId,
segmentIndex,
true);
//Optionally store a reference to the block in the in memory deque
if (!actuallyPoll) {
m_memoryDeque.offer(block);
}
return block;
}
} } | public class class_name {
private StreamBlock pollPersistentDeque(boolean actuallyPoll) {
BBContainer cont = null;
BBContainer schemaCont = null;
try {
// Start to read a new segment
if (m_reader.isStartOfSegment()) {
schemaCont = m_reader.getExtraHeader(-1); // depends on control dependency: [if], data = [none]
}
cont = m_reader.poll(PersistentBinaryDeque.UNSAFE_CONTAINER_FACTORY); // depends on control dependency: [try], data = [none]
} catch (IOException e) {
exportLog.error("Failed to poll from persistent binary deque:" + e);
} // depends on control dependency: [catch], data = [none]
if (cont == null) {
if (schemaCont != null) {
schemaCont.discard(); // depends on control dependency: [if], data = [none]
}
return null; // depends on control dependency: [if], data = [none]
} else {
long segmentIndex = m_reader.getSegmentIndex();
cont.b().order(ByteOrder.LITTLE_ENDIAN); // depends on control dependency: [if], data = [none]
//If the container is not null, unpack it.
final BBContainer fcont = cont;
long seqNo = cont.b().getLong(StreamBlock.SEQUENCE_NUMBER_OFFSET);
long committedSeqNo = cont.b().getLong(StreamBlock.COMMIT_SEQUENCE_NUMBER_OFFSET);
int tupleCount = cont.b().getInt(StreamBlock.ROW_NUMBER_OFFSET);
long uniqueId = cont.b().getLong(StreamBlock.UNIQUE_ID_OFFSET);
//Pass the stream block a subset of the bytes, provide
//a container that discards the original returned by the persistent deque
StreamBlock block = new StreamBlock( fcont,
schemaCont,
seqNo,
committedSeqNo,
tupleCount,
uniqueId,
segmentIndex,
true);
//Optionally store a reference to the block in the in memory deque
if (!actuallyPoll) {
m_memoryDeque.offer(block); // depends on control dependency: [if], data = [none]
}
return block; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
protected ByteBuffer getByteBuffer(int bufferLength) {
if(_buffer == null) {
_buffer = ByteBuffer.wrap(new byte[bufferLength]);
_log.info("ByteBuffer allocated for buffering");
}
return _buffer;
} } | public class class_name {
protected ByteBuffer getByteBuffer(int bufferLength) {
if(_buffer == null) {
_buffer = ByteBuffer.wrap(new byte[bufferLength]); // depends on control dependency: [if], data = [none]
_log.info("ByteBuffer allocated for buffering"); // depends on control dependency: [if], data = [none]
}
return _buffer;
} } |
public class class_name {
public PortletDefinition getPortletDescriptor(PortletDefinitionForm form) {
final Tuple<String, String> portletDescriptorKeys = this.getPortletDescriptorKeys(form);
if (portletDescriptorKeys == null) {
return null;
}
final String portletAppId = portletDescriptorKeys.first;
final String portletName = portletDescriptorKeys.second;
final PortletRegistryService portletRegistryService =
portalDriverContainerServices.getPortletRegistryService();
try {
return portletRegistryService.getPortlet(portletAppId, portletName);
} catch (PortletContainerException e) {
e.printStackTrace();
return null;
}
} } | public class class_name {
public PortletDefinition getPortletDescriptor(PortletDefinitionForm form) {
final Tuple<String, String> portletDescriptorKeys = this.getPortletDescriptorKeys(form);
if (portletDescriptorKeys == null) {
return null; // depends on control dependency: [if], data = [none]
}
final String portletAppId = portletDescriptorKeys.first;
final String portletName = portletDescriptorKeys.second;
final PortletRegistryService portletRegistryService =
portalDriverContainerServices.getPortletRegistryService();
try {
return portletRegistryService.getPortlet(portletAppId, portletName); // depends on control dependency: [try], data = [none]
} catch (PortletContainerException e) {
e.printStackTrace();
return null;
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public static String feature2Dxf( FeatureMate featureMate, String layerName, String elevationAttrName, boolean suffix,
boolean force2CoordsToLine ) {
Geometry g = featureMate.getGeometry();
if (EGeometryType.isPoint(g)) {
return point2Dxf(featureMate, layerName, elevationAttrName);
} else if (EGeometryType.isLine(g)) {
return lineString2Dxf(featureMate, layerName, elevationAttrName, force2CoordsToLine);
} else if (EGeometryType.isPolygon(g)) {
return polygon2Dxf(featureMate, layerName, elevationAttrName, suffix);
} else if (g instanceof GeometryCollection) {
StringBuilder sb = new StringBuilder();
for( int i = 0; i < g.getNumGeometries(); i++ ) {
SimpleFeature ff = SimpleFeatureBuilder.copy(featureMate.getFeature());
ff.setDefaultGeometry(g.getGeometryN(i));
FeatureMate fm = new FeatureMate(ff);
sb.append(feature2Dxf(fm, layerName, elevationAttrName, suffix, force2CoordsToLine));
}
return sb.toString();
} else {
return null;
}
} } | public class class_name {
public static String feature2Dxf( FeatureMate featureMate, String layerName, String elevationAttrName, boolean suffix,
boolean force2CoordsToLine ) {
Geometry g = featureMate.getGeometry();
if (EGeometryType.isPoint(g)) {
return point2Dxf(featureMate, layerName, elevationAttrName); // depends on control dependency: [if], data = [none]
} else if (EGeometryType.isLine(g)) {
return lineString2Dxf(featureMate, layerName, elevationAttrName, force2CoordsToLine); // depends on control dependency: [if], data = [none]
} else if (EGeometryType.isPolygon(g)) {
return polygon2Dxf(featureMate, layerName, elevationAttrName, suffix); // depends on control dependency: [if], data = [none]
} else if (g instanceof GeometryCollection) {
StringBuilder sb = new StringBuilder();
for( int i = 0; i < g.getNumGeometries(); i++ ) {
SimpleFeature ff = SimpleFeatureBuilder.copy(featureMate.getFeature());
ff.setDefaultGeometry(g.getGeometryN(i)); // depends on control dependency: [for], data = [i]
FeatureMate fm = new FeatureMate(ff);
sb.append(feature2Dxf(fm, layerName, elevationAttrName, suffix, force2CoordsToLine)); // depends on control dependency: [for], data = [none]
}
return sb.toString(); // depends on control dependency: [if], data = [none]
} else {
return null; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public static XAnnotationsFactory init()
{
try
{
XAnnotationsFactory theXAnnotationsFactory = (XAnnotationsFactory)EPackage.Registry.INSTANCE.getEFactory(XAnnotationsPackage.eNS_URI);
if (theXAnnotationsFactory != null)
{
return theXAnnotationsFactory;
}
}
catch (Exception exception)
{
EcorePlugin.INSTANCE.log(exception);
}
return new XAnnotationsFactoryImpl();
} } | public class class_name {
public static XAnnotationsFactory init()
{
try
{
XAnnotationsFactory theXAnnotationsFactory = (XAnnotationsFactory)EPackage.Registry.INSTANCE.getEFactory(XAnnotationsPackage.eNS_URI);
if (theXAnnotationsFactory != null)
{
return theXAnnotationsFactory; // depends on control dependency: [if], data = [none]
}
}
catch (Exception exception)
{
EcorePlugin.INSTANCE.log(exception);
} // depends on control dependency: [catch], data = [none]
return new XAnnotationsFactoryImpl();
} } |
public class class_name {
public static Collection<Tuple> getTuples( List<VarDef> varDefs, int tupleSize)
{
if( tupleSize < 1)
{
tupleSize = varDefs.size();
}
int varEnd = varDefs.size() - tupleSize + 1;
if( varEnd <= 0)
{
throw new IllegalArgumentException( "Can't create " + tupleSize + "-tuples for " + varDefs.size() + " combined variables");
}
return getTuples( varDefs, 0, varEnd, tupleSize);
} } | public class class_name {
public static Collection<Tuple> getTuples( List<VarDef> varDefs, int tupleSize)
{
if( tupleSize < 1)
{
tupleSize = varDefs.size(); // depends on control dependency: [if], data = [none]
}
int varEnd = varDefs.size() - tupleSize + 1;
if( varEnd <= 0)
{
throw new IllegalArgumentException( "Can't create " + tupleSize + "-tuples for " + varDefs.size() + " combined variables");
}
return getTuples( varDefs, 0, varEnd, tupleSize);
} } |
public class class_name {
public static String toValidPackageName(String pkg)
{
if (pkg == null)
{
throw new IllegalArgumentException("Package should not be null");
}
// Sanitizing package name
StringBuilder sb = new StringBuilder(pkg.length());
for (int i = 0; i < pkg.length(); i++)
{
char c = pkg.charAt(i);
// remove dots from the beginning and the end of the package
if (c == '.' && (i == 0 || i == pkg.length() - 1))
{
continue;
}
if (c == '.' || Character.isJavaIdentifierPart(c))
{
sb.append(c);
}
}
String packageName = sb.toString();
StringBuilder result = new StringBuilder();
String[] tokens = packageName.split("[.]");
for (String token : tokens)
{
if (result.length() > 0 && result.charAt(result.length() - 1) != '.')
{
result.append('.');
}
if (JLSValidator.isReservedWord(token))
{
result.append(token).append('_');
}
else if (isNumber(token))
{
// skip tokens as numbers and remove the appended '.' if exist
if (result.length() > 0)
result.deleteCharAt(result.length() - 1);
}
else
{
result.append(token);
}
}
return result.toString();
} } | public class class_name {
public static String toValidPackageName(String pkg)
{
if (pkg == null)
{
throw new IllegalArgumentException("Package should not be null");
}
// Sanitizing package name
StringBuilder sb = new StringBuilder(pkg.length());
for (int i = 0; i < pkg.length(); i++)
{
char c = pkg.charAt(i);
// remove dots from the beginning and the end of the package
if (c == '.' && (i == 0 || i == pkg.length() - 1))
{
continue;
}
if (c == '.' || Character.isJavaIdentifierPart(c))
{
sb.append(c); // depends on control dependency: [if], data = [(c]
}
}
String packageName = sb.toString();
StringBuilder result = new StringBuilder();
String[] tokens = packageName.split("[.]");
for (String token : tokens)
{
if (result.length() > 0 && result.charAt(result.length() - 1) != '.')
{
result.append('.'); // depends on control dependency: [if], data = ['.')]
}
if (JLSValidator.isReservedWord(token))
{
result.append(token).append('_'); // depends on control dependency: [if], data = [none]
}
else if (isNumber(token))
{
// skip tokens as numbers and remove the appended '.' if exist
if (result.length() > 0)
result.deleteCharAt(result.length() - 1);
}
else
{
result.append(token); // depends on control dependency: [if], data = [none]
}
}
return result.toString();
} } |
public class class_name {
public java.util.List<DBSnapshotAttribute> getDBSnapshotAttributes() {
if (dBSnapshotAttributes == null) {
dBSnapshotAttributes = new com.amazonaws.internal.SdkInternalList<DBSnapshotAttribute>();
}
return dBSnapshotAttributes;
} } | public class class_name {
public java.util.List<DBSnapshotAttribute> getDBSnapshotAttributes() {
if (dBSnapshotAttributes == null) {
dBSnapshotAttributes = new com.amazonaws.internal.SdkInternalList<DBSnapshotAttribute>(); // depends on control dependency: [if], data = [none]
}
return dBSnapshotAttributes;
} } |
public class class_name {
public String getListOfProvidersFromIdentities()
{
if(this.getIdentities() == null || this.getIdentities().isEmpty())
{
return "";
}
StringBuilder returnVal = new StringBuilder();
for(Client client : this.getIdentities())
{
returnVal.append(client.getProvider());
returnVal.append(",");
}
String toString = returnVal.toString();
return toString.substring(0,toString.length() - 1);
} } | public class class_name {
public String getListOfProvidersFromIdentities()
{
if(this.getIdentities() == null || this.getIdentities().isEmpty())
{
return ""; // depends on control dependency: [if], data = [none]
}
StringBuilder returnVal = new StringBuilder();
for(Client client : this.getIdentities())
{
returnVal.append(client.getProvider()); // depends on control dependency: [for], data = [client]
returnVal.append(","); // depends on control dependency: [for], data = [none]
}
String toString = returnVal.toString();
return toString.substring(0,toString.length() - 1);
} } |
public class class_name {
public static Organisasjonsnummer getAndForceValidOrganisasjonsnummer(String organisasjonsnummer) {
validateSyntax(organisasjonsnummer);
try {
validateChecksum(organisasjonsnummer);
} catch (IllegalArgumentException iae) {
Organisasjonsnummer onr = new Organisasjonsnummer(organisasjonsnummer);
int checksum = calculateMod11CheckSum(getMod11Weights(onr), onr);
organisasjonsnummer = organisasjonsnummer.substring(0, LENGTH - 1) + checksum;
}
return new Organisasjonsnummer(organisasjonsnummer);
} } | public class class_name {
public static Organisasjonsnummer getAndForceValidOrganisasjonsnummer(String organisasjonsnummer) {
validateSyntax(organisasjonsnummer);
try {
validateChecksum(organisasjonsnummer); // depends on control dependency: [try], data = [none]
} catch (IllegalArgumentException iae) {
Organisasjonsnummer onr = new Organisasjonsnummer(organisasjonsnummer);
int checksum = calculateMod11CheckSum(getMod11Weights(onr), onr);
organisasjonsnummer = organisasjonsnummer.substring(0, LENGTH - 1) + checksum;
} // depends on control dependency: [catch], data = [none]
return new Organisasjonsnummer(organisasjonsnummer);
} } |
public class class_name {
public boolean isExpectedResponseStatusCode(int responseStatusCode, int[] additionalAllowedStatusCodes) {
boolean result;
if (expectedStatusCodes == null) {
result = (responseStatusCode < 400);
} else {
result = contains(expectedStatusCodes, responseStatusCode)
|| contains(additionalAllowedStatusCodes, responseStatusCode);
}
return result;
} } | public class class_name {
public boolean isExpectedResponseStatusCode(int responseStatusCode, int[] additionalAllowedStatusCodes) {
boolean result;
if (expectedStatusCodes == null) {
result = (responseStatusCode < 400); // depends on control dependency: [if], data = [none]
} else {
result = contains(expectedStatusCodes, responseStatusCode)
|| contains(additionalAllowedStatusCodes, responseStatusCode); // depends on control dependency: [if], data = [(expectedStatusCodes]
}
return result;
} } |
public class class_name {
private JobSubmissionProtocol checkClient() throws IOException {
synchronized (this) {
while (client == null) {
try {
if (remoteJTStatus == RemoteJTStatus.FAILURE) {
throw new IOException("Remote Job Tracker is not available");
}
this.wait(1000);
} catch (InterruptedException e) {
throw new IOException(e);
}
}
return client;
}
} } | public class class_name {
private JobSubmissionProtocol checkClient() throws IOException {
synchronized (this) {
while (client == null) {
try {
if (remoteJTStatus == RemoteJTStatus.FAILURE) {
throw new IOException("Remote Job Tracker is not available");
}
this.wait(1000); // depends on control dependency: [try], data = [none]
} catch (InterruptedException e) {
throw new IOException(e);
} // depends on control dependency: [catch], data = [none]
}
return client;
}
} } |
public class class_name {
public void addImagesToImageAttachmentBand(final List<ImageItem> imagesToAttach) {
if (imagesToAttach == null || imagesToAttach.size() == 0) {
return;
}
attachments.setupLayoutListener();
attachments.setVisibility(View.VISIBLE);
images.addAll(imagesToAttach);
setAttachButtonState();
addAdditionalAttachItem();
attachments.notifyDataSetChanged();
} } | public class class_name {
public void addImagesToImageAttachmentBand(final List<ImageItem> imagesToAttach) {
if (imagesToAttach == null || imagesToAttach.size() == 0) {
return; // depends on control dependency: [if], data = [none]
}
attachments.setupLayoutListener();
attachments.setVisibility(View.VISIBLE);
images.addAll(imagesToAttach);
setAttachButtonState();
addAdditionalAttachItem();
attachments.notifyDataSetChanged();
} } |
public class class_name {
public void marshall(DomainName domainName, ProtocolMarshaller protocolMarshaller) {
if (domainName == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(domainName.getDomainName(), DOMAINNAME_BINDING);
protocolMarshaller.marshall(domainName.getCertificateName(), CERTIFICATENAME_BINDING);
protocolMarshaller.marshall(domainName.getCertificateArn(), CERTIFICATEARN_BINDING);
protocolMarshaller.marshall(domainName.getCertificateUploadDate(), CERTIFICATEUPLOADDATE_BINDING);
protocolMarshaller.marshall(domainName.getRegionalDomainName(), REGIONALDOMAINNAME_BINDING);
protocolMarshaller.marshall(domainName.getRegionalHostedZoneId(), REGIONALHOSTEDZONEID_BINDING);
protocolMarshaller.marshall(domainName.getRegionalCertificateName(), REGIONALCERTIFICATENAME_BINDING);
protocolMarshaller.marshall(domainName.getRegionalCertificateArn(), REGIONALCERTIFICATEARN_BINDING);
protocolMarshaller.marshall(domainName.getDistributionDomainName(), DISTRIBUTIONDOMAINNAME_BINDING);
protocolMarshaller.marshall(domainName.getDistributionHostedZoneId(), DISTRIBUTIONHOSTEDZONEID_BINDING);
protocolMarshaller.marshall(domainName.getEndpointConfiguration(), ENDPOINTCONFIGURATION_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(DomainName domainName, ProtocolMarshaller protocolMarshaller) {
if (domainName == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(domainName.getDomainName(), DOMAINNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(domainName.getCertificateName(), CERTIFICATENAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(domainName.getCertificateArn(), CERTIFICATEARN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(domainName.getCertificateUploadDate(), CERTIFICATEUPLOADDATE_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(domainName.getRegionalDomainName(), REGIONALDOMAINNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(domainName.getRegionalHostedZoneId(), REGIONALHOSTEDZONEID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(domainName.getRegionalCertificateName(), REGIONALCERTIFICATENAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(domainName.getRegionalCertificateArn(), REGIONALCERTIFICATEARN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(domainName.getDistributionDomainName(), DISTRIBUTIONDOMAINNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(domainName.getDistributionHostedZoneId(), DISTRIBUTIONHOSTEDZONEID_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(domainName.getEndpointConfiguration(), ENDPOINTCONFIGURATION_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
protected void appendSyntheticDefaultValuedParameterMethods(
XtendTypeDeclaration source,
JvmDeclaredType target,
GenerationContext context) {
// Generate the different operations.
final Iterator<Runnable> differedGeneration = context.getPreFinalizationElements().iterator();
while (differedGeneration.hasNext()) {
final Runnable runnable = differedGeneration.next();
differedGeneration.remove();
runnable.run();
}
// Generated the missed functions that are the result of the generation of operations
// with default values.
int actIndex = context.getActionIndex();
for (final Entry<ActionPrototype, JvmOperation> missedOperation : context.getInheritedOperationsToImplement()
.entrySet()) {
final String originalSignature = this.annotationUtils.findStringValue(
missedOperation.getValue(), DefaultValueUse.class);
if (!Strings.isNullOrEmpty(originalSignature)) {
// Find the definition of the operation from the inheritance context.
final JvmOperation redefinedOperation = context.getInheritedOverridableOperations().get(
this.sarlSignatureProvider.createActionPrototype(
missedOperation.getKey().getActionName(),
this.sarlSignatureProvider.createParameterTypesFromString(originalSignature)));
if (redefinedOperation != null) {
final ActionParameterTypes parameterTypes = this.sarlSignatureProvider.createParameterTypesFromJvmModel(
redefinedOperation.isVarArgs(), redefinedOperation.getParameters());
final QualifiedActionName qualifiedActionName = this.sarlSignatureProvider.createQualifiedActionName(
missedOperation.getValue().getDeclaringType(),
redefinedOperation.getSimpleName());
// Retreive the inferred prototype (including the prototypes with optional arguments)
InferredPrototype redefinedPrototype = this.sarlSignatureProvider.getPrototypes(
qualifiedActionName, parameterTypes);
if (redefinedPrototype == null) {
// The original operation was not parsed by the SARL compiler in the current run-time context.
redefinedPrototype = this.sarlSignatureProvider.createPrototypeFromJvmModel(
qualifiedActionName, redefinedOperation.isVarArgs(),
redefinedOperation.getParameters());
}
// Retreive the specification of the formal parameters that will be used for
// determining the calling arguments.
final List<InferredStandardParameter> argumentSpec = redefinedPrototype.getInferredParameterTypes().get(
missedOperation.getKey().getParametersTypes());
// Create the missed java operation.
final JvmOperation op = this.typeBuilder.toMethod(
source,
missedOperation.getValue().getSimpleName(),
missedOperation.getValue().getReturnType(),
null);
op.setVarArgs(missedOperation.getValue().isVarArgs());
op.setFinal(true);
final List<String> arguments = new ArrayList<>();
// Create the formal parameters.
for (final InferredStandardParameter parameter : argumentSpec) {
if (parameter instanceof InferredValuedParameter) {
final InferredValuedParameter inferredParameter = (InferredValuedParameter) parameter;
arguments.add(this.sarlSignatureProvider.toJavaArgument(
target.getIdentifier(), inferredParameter.getCallingArgument()));
} else {
arguments.add(parameter.getName());
final JvmFormalParameter jvmParam = this.typesFactory.createJvmFormalParameter();
jvmParam.setName(parameter.getName());
jvmParam.setParameterType(this.typeBuilder.cloneWithProxies(parameter.getType()));
this.associator.associate(parameter.getParameter(), jvmParam);
op.getParameters().add(jvmParam);
}
}
// Create the body
setBody(op,
it -> {
it.append(redefinedOperation.getSimpleName());
it.append("("); //$NON-NLS-1$
it.append(IterableExtensions.join(arguments, ", ")); //$NON-NLS-1$
it.append(");"); //$NON-NLS-1$
});
// Add the annotations.
addAnnotationSafe(op, DefaultValueUse.class, originalSignature);
appendGeneratedAnnotation(op, context);
// Add the operation in the container.
target.getMembers().add(op);
++actIndex;
}
}
}
context.setActionIndex(actIndex);
} } | public class class_name {
protected void appendSyntheticDefaultValuedParameterMethods(
XtendTypeDeclaration source,
JvmDeclaredType target,
GenerationContext context) {
// Generate the different operations.
final Iterator<Runnable> differedGeneration = context.getPreFinalizationElements().iterator();
while (differedGeneration.hasNext()) {
final Runnable runnable = differedGeneration.next();
differedGeneration.remove(); // depends on control dependency: [while], data = [none]
runnable.run(); // depends on control dependency: [while], data = [none]
}
// Generated the missed functions that are the result of the generation of operations
// with default values.
int actIndex = context.getActionIndex();
for (final Entry<ActionPrototype, JvmOperation> missedOperation : context.getInheritedOperationsToImplement()
.entrySet()) {
final String originalSignature = this.annotationUtils.findStringValue(
missedOperation.getValue(), DefaultValueUse.class);
if (!Strings.isNullOrEmpty(originalSignature)) {
// Find the definition of the operation from the inheritance context.
final JvmOperation redefinedOperation = context.getInheritedOverridableOperations().get(
this.sarlSignatureProvider.createActionPrototype(
missedOperation.getKey().getActionName(),
this.sarlSignatureProvider.createParameterTypesFromString(originalSignature)));
if (redefinedOperation != null) {
final ActionParameterTypes parameterTypes = this.sarlSignatureProvider.createParameterTypesFromJvmModel(
redefinedOperation.isVarArgs(), redefinedOperation.getParameters());
final QualifiedActionName qualifiedActionName = this.sarlSignatureProvider.createQualifiedActionName(
missedOperation.getValue().getDeclaringType(),
redefinedOperation.getSimpleName());
// Retreive the inferred prototype (including the prototypes with optional arguments)
InferredPrototype redefinedPrototype = this.sarlSignatureProvider.getPrototypes(
qualifiedActionName, parameterTypes);
if (redefinedPrototype == null) {
// The original operation was not parsed by the SARL compiler in the current run-time context.
redefinedPrototype = this.sarlSignatureProvider.createPrototypeFromJvmModel(
qualifiedActionName, redefinedOperation.isVarArgs(),
redefinedOperation.getParameters()); // depends on control dependency: [if], data = [none]
}
// Retreive the specification of the formal parameters that will be used for
// determining the calling arguments.
final List<InferredStandardParameter> argumentSpec = redefinedPrototype.getInferredParameterTypes().get(
missedOperation.getKey().getParametersTypes());
// Create the missed java operation.
final JvmOperation op = this.typeBuilder.toMethod(
source,
missedOperation.getValue().getSimpleName(),
missedOperation.getValue().getReturnType(),
null);
op.setVarArgs(missedOperation.getValue().isVarArgs()); // depends on control dependency: [if], data = [none]
op.setFinal(true); // depends on control dependency: [if], data = [none]
final List<String> arguments = new ArrayList<>();
// Create the formal parameters.
for (final InferredStandardParameter parameter : argumentSpec) {
if (parameter instanceof InferredValuedParameter) {
final InferredValuedParameter inferredParameter = (InferredValuedParameter) parameter;
arguments.add(this.sarlSignatureProvider.toJavaArgument(
target.getIdentifier(), inferredParameter.getCallingArgument())); // depends on control dependency: [if], data = [none]
} else {
arguments.add(parameter.getName()); // depends on control dependency: [if], data = [none]
final JvmFormalParameter jvmParam = this.typesFactory.createJvmFormalParameter();
jvmParam.setName(parameter.getName()); // depends on control dependency: [if], data = [none]
jvmParam.setParameterType(this.typeBuilder.cloneWithProxies(parameter.getType())); // depends on control dependency: [if], data = [none]
this.associator.associate(parameter.getParameter(), jvmParam); // depends on control dependency: [if], data = [none]
op.getParameters().add(jvmParam); // depends on control dependency: [if], data = [none]
}
}
// Create the body
setBody(op,
it -> {
it.append(redefinedOperation.getSimpleName()); // depends on control dependency: [if], data = [none]
it.append("("); //$NON-NLS-1$ // depends on control dependency: [if], data = [none]
it.append(IterableExtensions.join(arguments, ", ")); //$NON-NLS-1$ // depends on control dependency: [if], data = [none]
it.append(");"); //$NON-NLS-1$ // depends on control dependency: [if], data = [none]
});
// Add the annotations.
addAnnotationSafe(op, DefaultValueUse.class, originalSignature); // depends on control dependency: [if], data = [none]
appendGeneratedAnnotation(op, context); // depends on control dependency: [if], data = [none]
// Add the operation in the container.
target.getMembers().add(op); // depends on control dependency: [if], data = [none]
++actIndex; // depends on control dependency: [if], data = [none]
}
}
}
context.setActionIndex(actIndex);
} } |
public class class_name {
private Stmt.Return parseReturnStatement(EnclosingScope scope) {
int start = index;
match(Return);
// A return statement may optionally have one or more return
// expressions. Therefore, we first skip all whitespace on the given
// line.
int next = skipLineSpace(index);
// Then, we check whether or not we reached the end of the line. If not,
// then we assume what's remaining is the returned expression. This
// means expressions must start on the same line as a return. Otherwise,
// a potentially cryptic error message will be given.
Tuple<Expr> returns;
if (next < tokens.size() && tokens.get(next).kind != NewLine) {
returns = parseExpressions(scope, false);
} else {
returns = new Tuple<>();
}
// Finally, at this point we are expecting a new-line to signal the
// end-of-statement.
int end = index;
matchEndLine();
// Done.
return annotateSourceLocation(new Stmt.Return(returns), start, end-1);
} } | public class class_name {
private Stmt.Return parseReturnStatement(EnclosingScope scope) {
int start = index;
match(Return);
// A return statement may optionally have one or more return
// expressions. Therefore, we first skip all whitespace on the given
// line.
int next = skipLineSpace(index);
// Then, we check whether or not we reached the end of the line. If not,
// then we assume what's remaining is the returned expression. This
// means expressions must start on the same line as a return. Otherwise,
// a potentially cryptic error message will be given.
Tuple<Expr> returns;
if (next < tokens.size() && tokens.get(next).kind != NewLine) {
returns = parseExpressions(scope, false); // depends on control dependency: [if], data = [none]
} else {
returns = new Tuple<>(); // depends on control dependency: [if], data = [none]
}
// Finally, at this point we are expecting a new-line to signal the
// end-of-statement.
int end = index;
matchEndLine();
// Done.
return annotateSourceLocation(new Stmt.Return(returns), start, end-1);
} } |
public class class_name {
public static <E extends Enum<E>> Flags<E> valueOf(Class<E> type, String values) {
Flags<E> flags = new Flags<E>(type);
for (String text : values.trim().split(MULTI_VALUE_SEPARATOR)) {
flags.set(Enum.valueOf(type, text));
}
return flags;
} } | public class class_name {
public static <E extends Enum<E>> Flags<E> valueOf(Class<E> type, String values) {
Flags<E> flags = new Flags<E>(type);
for (String text : values.trim().split(MULTI_VALUE_SEPARATOR)) {
flags.set(Enum.valueOf(type, text)); // depends on control dependency: [for], data = [text]
}
return flags;
} } |
public class class_name {
public void setResourceShareInvitationArns(java.util.Collection<String> resourceShareInvitationArns) {
if (resourceShareInvitationArns == null) {
this.resourceShareInvitationArns = null;
return;
}
this.resourceShareInvitationArns = new java.util.ArrayList<String>(resourceShareInvitationArns);
} } | public class class_name {
public void setResourceShareInvitationArns(java.util.Collection<String> resourceShareInvitationArns) {
if (resourceShareInvitationArns == null) {
this.resourceShareInvitationArns = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.resourceShareInvitationArns = new java.util.ArrayList<String>(resourceShareInvitationArns);
} } |
public class class_name {
public void setResourceArns(java.util.Collection<String> resourceArns) {
if (resourceArns == null) {
this.resourceArns = null;
return;
}
this.resourceArns = new java.util.ArrayList<String>(resourceArns);
} } | public class class_name {
public void setResourceArns(java.util.Collection<String> resourceArns) {
if (resourceArns == null) {
this.resourceArns = null; // depends on control dependency: [if], data = [none]
return; // depends on control dependency: [if], data = [none]
}
this.resourceArns = new java.util.ArrayList<String>(resourceArns);
} } |
public class class_name {
private void remotePut(
MessageItem msg,
SIBUuid8 sourceMEUuid)
throws
SIResourceException,
SIDiscriminatorSyntaxException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(
tc,
"remotePut",
new Object[] { msg, sourceMEUuid });
// Update the origin map if this is a new stream.
// This unsynchronized update is ok until multiple paths
// are possible (in which case there could be a race
// for the same stream on this method).
SIBUuid12 stream = msg.getMessage().getGuaranteedStreamUUID();
if (!_originStreamMap.containsKey(stream))
_originStreamMap.put(stream, sourceMEUuid);
// First get matches
// Match Consumers is only called for PubSub targets.
MessageProcessorSearchResults searchResults = matchMessage(msg);
String topic = msg.getMessage().getDiscriminator();
//First the remote to remote case (forwarding)
HashMap allPubSubOutputHandlers = _destination.getAllPubSubOutputHandlers();
List matchingPubsubOutputHandlers = searchResults.getPubSubOutputHandlers(topic);
// Check to see if we have any Neighbours
if (allPubSubOutputHandlers != null &&
allPubSubOutputHandlers.size() > 0)
{
remoteToRemotePut(msg, allPubSubOutputHandlers, matchingPubsubOutputHandlers);
}
// Calling getAllPubSubOutputHandlers() locks the handlers
// so now we have finished we need to unlock
_destination.unlockPubsubOutputHandlers();
// Now handle remote to local case
// If there are any ConsumerDispatchers we will need to save the
// list in the Targetstream with the message
Set consumerDispatchers = searchResults.getConsumerDispatchers(topic);
// Check to see if we have any matching Neighbours
if (consumerDispatchers != null &&
consumerDispatchers.size() > 0)
{
// Add the list of consumerDispatchers to the MessageItem
// as we will need it in DeliverOrdered messages
msg.setSearchResults(searchResults);
// This will add the message to the TargetStream
remoteToLocalPut(msg);
}
else
{
// This will add Silence to the TargetStream
remoteToLocalPutSilence(msg);
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "remotePut");
} } | public class class_name {
private void remotePut(
MessageItem msg,
SIBUuid8 sourceMEUuid)
throws
SIResourceException,
SIDiscriminatorSyntaxException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(
tc,
"remotePut",
new Object[] { msg, sourceMEUuid });
// Update the origin map if this is a new stream.
// This unsynchronized update is ok until multiple paths
// are possible (in which case there could be a race
// for the same stream on this method).
SIBUuid12 stream = msg.getMessage().getGuaranteedStreamUUID();
if (!_originStreamMap.containsKey(stream))
_originStreamMap.put(stream, sourceMEUuid);
// First get matches
// Match Consumers is only called for PubSub targets.
MessageProcessorSearchResults searchResults = matchMessage(msg);
String topic = msg.getMessage().getDiscriminator();
//First the remote to remote case (forwarding)
HashMap allPubSubOutputHandlers = _destination.getAllPubSubOutputHandlers();
List matchingPubsubOutputHandlers = searchResults.getPubSubOutputHandlers(topic);
// Check to see if we have any Neighbours
if (allPubSubOutputHandlers != null &&
allPubSubOutputHandlers.size() > 0)
{
remoteToRemotePut(msg, allPubSubOutputHandlers, matchingPubsubOutputHandlers); // depends on control dependency: [if], data = [none]
}
// Calling getAllPubSubOutputHandlers() locks the handlers
// so now we have finished we need to unlock
_destination.unlockPubsubOutputHandlers();
// Now handle remote to local case
// If there are any ConsumerDispatchers we will need to save the
// list in the Targetstream with the message
Set consumerDispatchers = searchResults.getConsumerDispatchers(topic);
// Check to see if we have any matching Neighbours
if (consumerDispatchers != null &&
consumerDispatchers.size() > 0)
{
// Add the list of consumerDispatchers to the MessageItem
// as we will need it in DeliverOrdered messages
msg.setSearchResults(searchResults); // depends on control dependency: [if], data = [none]
// This will add the message to the TargetStream
remoteToLocalPut(msg); // depends on control dependency: [if], data = [none]
}
else
{
// This will add Silence to the TargetStream
remoteToLocalPutSilence(msg); // depends on control dependency: [if], data = [none]
}
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(tc, "remotePut");
} } |
public class class_name {
private static boolean localVariableMatches(VariableTree tree, VisitorState state) {
ExpressionTree expression = tree.getInitializer();
if (expression == null) {
Tree leaf = state.getPath().getParentPath().getLeaf();
if (!(leaf instanceof EnhancedForLoopTree)) {
return true;
}
EnhancedForLoopTree node = (EnhancedForLoopTree) leaf;
Type expressionType = ASTHelpers.getType(node.getExpression());
if (expressionType == null) {
return false;
}
Type elemtype = state.getTypes().elemtype(expressionType);
// Be conservative - if elemtype is null, treat it as if it is a loop over a wrapped type.
return elemtype != null && elemtype.isPrimitive();
}
Type initializerType = ASTHelpers.getType(expression);
if (initializerType == null) {
return false;
}
if (initializerType.isPrimitive()) {
return true;
}
// Don't count X.valueOf(...) as a boxed usage, since it can be replaced with X.parseX.
return VALUE_OF_MATCHER.matches(expression, state);
} } | public class class_name {
private static boolean localVariableMatches(VariableTree tree, VisitorState state) {
ExpressionTree expression = tree.getInitializer();
if (expression == null) {
Tree leaf = state.getPath().getParentPath().getLeaf();
if (!(leaf instanceof EnhancedForLoopTree)) {
return true; // depends on control dependency: [if], data = [none]
}
EnhancedForLoopTree node = (EnhancedForLoopTree) leaf;
Type expressionType = ASTHelpers.getType(node.getExpression());
if (expressionType == null) {
return false; // depends on control dependency: [if], data = [none]
}
Type elemtype = state.getTypes().elemtype(expressionType);
// Be conservative - if elemtype is null, treat it as if it is a loop over a wrapped type.
return elemtype != null && elemtype.isPrimitive(); // depends on control dependency: [if], data = [none]
}
Type initializerType = ASTHelpers.getType(expression);
if (initializerType == null) {
return false; // depends on control dependency: [if], data = [none]
}
if (initializerType.isPrimitive()) {
return true; // depends on control dependency: [if], data = [none]
}
// Don't count X.valueOf(...) as a boxed usage, since it can be replaced with X.parseX.
return VALUE_OF_MATCHER.matches(expression, state);
} } |
public class class_name {
@Override
protected StringBuffer doPostProcessBundle(BundleProcessingStatus status, StringBuffer bundleData)
throws IOException {
if(status.getProcessingType().equals(BundleProcessingStatus.FILE_PROCESSING_TYPE)
&& status.getJawrConfig().getResourceType().equals(JawrConstant.JS_TYPE)){
if (bundleData.toString().trim().endsWith(")")) {
bundleData.append(";");
}
}
return bundleData;
} } | public class class_name {
@Override
protected StringBuffer doPostProcessBundle(BundleProcessingStatus status, StringBuffer bundleData)
throws IOException {
if(status.getProcessingType().equals(BundleProcessingStatus.FILE_PROCESSING_TYPE)
&& status.getJawrConfig().getResourceType().equals(JawrConstant.JS_TYPE)){
if (bundleData.toString().trim().endsWith(")")) {
bundleData.append(";"); // depends on control dependency: [if], data = [none]
}
}
return bundleData;
} } |
public class class_name {
int getInt(String[] args, int index) {
int result = -1;
if(index >= 0 && index < args.length) {
try {
result = Integer.parseInt(args[index]);
}catch(NumberFormatException e) {
result = -1;
}
}
return result;
} } | public class class_name {
int getInt(String[] args, int index) {
int result = -1;
if(index >= 0 && index < args.length) {
try {
result = Integer.parseInt(args[index]); // depends on control dependency: [try], data = [none]
}catch(NumberFormatException e) {
result = -1;
} // depends on control dependency: [catch], data = [none]
}
return result;
} } |
public class class_name {
private MessageProcessorSearchResults matchMessage(MessageItem msg)
throws SIDiscriminatorSyntaxException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(
tc,
"matchMessage",
new Object[] { msg });
//Extract the message from the MessageItem
JsMessage jsMsg = msg.getMessage();
// Match Consumers is only called for PubSub targets.
TopicAuthorization topicAuth = _messageProcessor.getDiscriminatorAccessChecker();
MessageProcessorSearchResults searchResults = new MessageProcessorSearchResults(topicAuth);
// Defect 382250, set the unlockCount from MsgStore into the message
// in the case where the message is being redelivered.
int redelCount = msg.guessRedeliveredCount();
if (redelCount > 0)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
SibTr.debug(tc, "Set deliverycount into message: " + redelCount);
jsMsg.setDeliveryCount(redelCount);
}
// Get the matching consumers from the matchspace
_matchspace.retrieveMatchingOutputHandlers(
_destination,
jsMsg.getDiscriminator(),
(MatchSpaceKey) jsMsg,
searchResults);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(
tc,
"matchMessage",
new Object[] { searchResults });
return searchResults;
} } | public class class_name {
private MessageProcessorSearchResults matchMessage(MessageItem msg)
throws SIDiscriminatorSyntaxException
{
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.entry(
tc,
"matchMessage",
new Object[] { msg });
//Extract the message from the MessageItem
JsMessage jsMsg = msg.getMessage();
// Match Consumers is only called for PubSub targets.
TopicAuthorization topicAuth = _messageProcessor.getDiscriminatorAccessChecker();
MessageProcessorSearchResults searchResults = new MessageProcessorSearchResults(topicAuth);
// Defect 382250, set the unlockCount from MsgStore into the message
// in the case where the message is being redelivered.
int redelCount = msg.guessRedeliveredCount();
if (redelCount > 0)
{
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
SibTr.debug(tc, "Set deliverycount into message: " + redelCount);
jsMsg.setDeliveryCount(redelCount); // depends on control dependency: [if], data = [(redelCount]
}
// Get the matching consumers from the matchspace
_matchspace.retrieveMatchingOutputHandlers(
_destination,
jsMsg.getDiscriminator(),
(MatchSpaceKey) jsMsg,
searchResults);
if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
SibTr.exit(
tc,
"matchMessage",
new Object[] { searchResults });
return searchResults;
} } |
public class class_name {
private void associateL2R( T left , T right ) {
// make the previous new observations into the new old ones
ImageInfo<TD> tmp = featsLeft1;
featsLeft1 = featsLeft0; featsLeft0 = tmp;
tmp = featsRight1;
featsRight1 = featsRight0; featsRight0 = tmp;
// detect and associate features in the two images
featsLeft1.reset();
featsRight1.reset();
// long time0 = System.currentTimeMillis();
describeImage(left,featsLeft1);
describeImage(right,featsRight1);
// long time1 = System.currentTimeMillis();
// detect and associate features in the current stereo pair
for( int i = 0; i < detector.getNumberOfSets(); i++ ) {
SetMatches matches = setMatches[i];
matches.swap();
matches.match2to3.reset();
FastQueue<Point2D_F64> leftLoc = featsLeft1.location[i];
FastQueue<Point2D_F64> rightLoc = featsRight1.location[i];
assocL2R.setSource(leftLoc,featsLeft1.description[i]);
assocL2R.setDestination(rightLoc, featsRight1.description[i]);
assocL2R.associate();
FastQueue<AssociatedIndex> found = assocL2R.getMatches();
// removeUnassociated(leftLoc,featsLeft1.description[i],rightLoc,featsRight1.description[i],found);
setMatches(matches.match2to3, found, leftLoc.size);
}
// long time2 = System.currentTimeMillis();
// System.out.println(" desc "+(time1-time0)+" assoc "+(time2-time1));
} } | public class class_name {
private void associateL2R( T left , T right ) {
// make the previous new observations into the new old ones
ImageInfo<TD> tmp = featsLeft1;
featsLeft1 = featsLeft0; featsLeft0 = tmp;
tmp = featsRight1;
featsRight1 = featsRight0; featsRight0 = tmp;
// detect and associate features in the two images
featsLeft1.reset();
featsRight1.reset();
// long time0 = System.currentTimeMillis();
describeImage(left,featsLeft1);
describeImage(right,featsRight1);
// long time1 = System.currentTimeMillis();
// detect and associate features in the current stereo pair
for( int i = 0; i < detector.getNumberOfSets(); i++ ) {
SetMatches matches = setMatches[i];
matches.swap(); // depends on control dependency: [for], data = [none]
matches.match2to3.reset(); // depends on control dependency: [for], data = [none]
FastQueue<Point2D_F64> leftLoc = featsLeft1.location[i];
FastQueue<Point2D_F64> rightLoc = featsRight1.location[i];
assocL2R.setSource(leftLoc,featsLeft1.description[i]); // depends on control dependency: [for], data = [i]
assocL2R.setDestination(rightLoc, featsRight1.description[i]); // depends on control dependency: [for], data = [i]
assocL2R.associate(); // depends on control dependency: [for], data = [none]
FastQueue<AssociatedIndex> found = assocL2R.getMatches();
// removeUnassociated(leftLoc,featsLeft1.description[i],rightLoc,featsRight1.description[i],found);
setMatches(matches.match2to3, found, leftLoc.size); // depends on control dependency: [for], data = [none]
}
// long time2 = System.currentTimeMillis();
// System.out.println(" desc "+(time1-time0)+" assoc "+(time2-time1));
} } |
public class class_name {
public final PostAggItem constantAccess() throws RecognitionException {
PostAggItem postAggItem = null;
Token a=null;
postAggItem = new PostAggItem("constant");
try {
// druidG.g:527:2: ( ( (a= FLOAT |a= LONG ) ( WS postAggLabel[postAggItem] )? ) )
// druidG.g:527:4: ( (a= FLOAT |a= LONG ) ( WS postAggLabel[postAggItem] )? )
{
// druidG.g:527:4: ( (a= FLOAT |a= LONG ) ( WS postAggLabel[postAggItem] )? )
// druidG.g:527:5: (a= FLOAT |a= LONG ) ( WS postAggLabel[postAggItem] )?
{
// druidG.g:527:5: (a= FLOAT |a= LONG )
int alt214=2;
int LA214_0 = input.LA(1);
if ( (LA214_0==FLOAT) ) {
alt214=1;
}
else if ( (LA214_0==LONG) ) {
alt214=2;
}
else {
NoViableAltException nvae =
new NoViableAltException("", 214, 0, input);
throw nvae;
}
switch (alt214) {
case 1 :
// druidG.g:527:6: a= FLOAT
{
a=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_constantAccess3435);
}
break;
case 2 :
// druidG.g:527:16: a= LONG
{
a=(Token)match(input,LONG,FOLLOW_LONG_in_constantAccess3441);
}
break;
}
postAggItem.constantValue = Double.valueOf((a!=null?a.getText():null));
// druidG.g:529:5: ( WS postAggLabel[postAggItem] )?
int alt215=2;
int LA215_0 = input.LA(1);
if ( (LA215_0==WS) ) {
int LA215_1 = input.LA(2);
if ( (LA215_1==AS) ) {
alt215=1;
}
}
switch (alt215) {
case 1 :
// druidG.g:529:6: WS postAggLabel[postAggItem]
{
match(input,WS,FOLLOW_WS_in_constantAccess3454);
pushFollow(FOLLOW_postAggLabel_in_constantAccess3456);
postAggLabel(postAggItem);
state._fsp--;
}
break;
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
// do for sure before leaving
}
return postAggItem;
} } | public class class_name {
public final PostAggItem constantAccess() throws RecognitionException {
PostAggItem postAggItem = null;
Token a=null;
postAggItem = new PostAggItem("constant");
try {
// druidG.g:527:2: ( ( (a= FLOAT |a= LONG ) ( WS postAggLabel[postAggItem] )? ) )
// druidG.g:527:4: ( (a= FLOAT |a= LONG ) ( WS postAggLabel[postAggItem] )? )
{
// druidG.g:527:4: ( (a= FLOAT |a= LONG ) ( WS postAggLabel[postAggItem] )? )
// druidG.g:527:5: (a= FLOAT |a= LONG ) ( WS postAggLabel[postAggItem] )?
{
// druidG.g:527:5: (a= FLOAT |a= LONG )
int alt214=2;
int LA214_0 = input.LA(1);
if ( (LA214_0==FLOAT) ) {
alt214=1; // depends on control dependency: [if], data = [none]
}
else if ( (LA214_0==LONG) ) {
alt214=2; // depends on control dependency: [if], data = [none]
}
else {
NoViableAltException nvae =
new NoViableAltException("", 214, 0, input);
throw nvae;
}
switch (alt214) {
case 1 :
// druidG.g:527:6: a= FLOAT
{
a=(Token)match(input,FLOAT,FOLLOW_FLOAT_in_constantAccess3435);
}
break;
case 2 :
// druidG.g:527:16: a= LONG
{
a=(Token)match(input,LONG,FOLLOW_LONG_in_constantAccess3441);
}
break;
}
postAggItem.constantValue = Double.valueOf((a!=null?a.getText():null));
// druidG.g:529:5: ( WS postAggLabel[postAggItem] )?
int alt215=2;
int LA215_0 = input.LA(1);
if ( (LA215_0==WS) ) {
int LA215_1 = input.LA(2);
if ( (LA215_1==AS) ) {
alt215=1; // depends on control dependency: [if], data = [none]
}
}
switch (alt215) {
case 1 :
// druidG.g:529:6: WS postAggLabel[postAggItem]
{
match(input,WS,FOLLOW_WS_in_constantAccess3454);
pushFollow(FOLLOW_postAggLabel_in_constantAccess3456);
postAggLabel(postAggItem);
state._fsp--;
}
break;
}
}
}
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
}
finally {
// do for sure before leaving
}
return postAggItem;
} } |
public class class_name {
@Override
public EClass getIfcEnergyConversionDevice() {
if (ifcEnergyConversionDeviceEClass == null) {
ifcEnergyConversionDeviceEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(231);
}
return ifcEnergyConversionDeviceEClass;
} } | public class class_name {
@Override
public EClass getIfcEnergyConversionDevice() {
if (ifcEnergyConversionDeviceEClass == null) {
ifcEnergyConversionDeviceEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
.getEClassifiers().get(231);
// depends on control dependency: [if], data = [none]
}
return ifcEnergyConversionDeviceEClass;
} } |
public class class_name {
@Override
@SuppressFBWarnings("SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE")
public void deleteAll(final Connection _con)
throws SQLException
{
final Statement stmtSel = _con.createStatement();
final Statement stmtExec = _con.createStatement();
try {
// remove all views
if (OracleDatabase.LOG.isInfoEnabled()) {
OracleDatabase.LOG.info("Remove all Views");
}
ResultSet rs = stmtSel.executeQuery("select VIEW_NAME from USER_VIEWS");
while (rs.next()) {
final String viewName = rs.getString(1);
if (OracleDatabase.LOG.isDebugEnabled()) {
OracleDatabase.LOG.debug(" - View '" + viewName + "'");
}
stmtExec.execute("drop view " + viewName);
}
rs.close();
// remove all tables
if (OracleDatabase.LOG.isInfoEnabled()) {
OracleDatabase.LOG.info("Remove all Tables");
}
rs = stmtSel.executeQuery("select TABLE_NAME from USER_TABLES");
while (rs.next()) {
final String tableName = rs.getString(1);
if (OracleDatabase.LOG.isDebugEnabled()) {
OracleDatabase.LOG.debug(" - Table '" + tableName + "'");
}
stmtExec.execute("drop table " + tableName + " cascade constraints");
}
rs.close();
// remove all sequences
if (OracleDatabase.LOG.isInfoEnabled()) {
OracleDatabase.LOG.info("Remove all Sequences");
}
rs = stmtSel.executeQuery("select SEQUENCE_NAME from USER_SEQUENCES");
while (rs.next()) {
final String seqName = rs.getString(1);
if (OracleDatabase.LOG.isDebugEnabled()) {
OracleDatabase.LOG.debug(" - Sequence '" + seqName + "'");
}
stmtExec.execute("drop sequence " + seqName);
}
rs.close();
} finally {
stmtSel.close();
stmtExec.close();
}
} } | public class class_name {
@Override
@SuppressFBWarnings("SQL_NONCONSTANT_STRING_PASSED_TO_EXECUTE")
public void deleteAll(final Connection _con)
throws SQLException
{
final Statement stmtSel = _con.createStatement();
final Statement stmtExec = _con.createStatement();
try {
// remove all views
if (OracleDatabase.LOG.isInfoEnabled()) {
OracleDatabase.LOG.info("Remove all Views"); // depends on control dependency: [if], data = [none]
}
ResultSet rs = stmtSel.executeQuery("select VIEW_NAME from USER_VIEWS");
while (rs.next()) {
final String viewName = rs.getString(1);
if (OracleDatabase.LOG.isDebugEnabled()) {
OracleDatabase.LOG.debug(" - View '" + viewName + "'"); // depends on control dependency: [if], data = [none]
}
stmtExec.execute("drop view " + viewName); // depends on control dependency: [while], data = [none]
}
rs.close();
// remove all tables
if (OracleDatabase.LOG.isInfoEnabled()) {
OracleDatabase.LOG.info("Remove all Tables"); // depends on control dependency: [if], data = [none]
}
rs = stmtSel.executeQuery("select TABLE_NAME from USER_TABLES");
while (rs.next()) {
final String tableName = rs.getString(1);
if (OracleDatabase.LOG.isDebugEnabled()) {
OracleDatabase.LOG.debug(" - Table '" + tableName + "'"); // depends on control dependency: [if], data = [none]
}
stmtExec.execute("drop table " + tableName + " cascade constraints"); // depends on control dependency: [while], data = [none]
}
rs.close();
// remove all sequences
if (OracleDatabase.LOG.isInfoEnabled()) {
OracleDatabase.LOG.info("Remove all Sequences"); // depends on control dependency: [if], data = [none]
}
rs = stmtSel.executeQuery("select SEQUENCE_NAME from USER_SEQUENCES");
while (rs.next()) {
final String seqName = rs.getString(1);
if (OracleDatabase.LOG.isDebugEnabled()) {
OracleDatabase.LOG.debug(" - Sequence '" + seqName + "'"); // depends on control dependency: [if], data = [none]
}
stmtExec.execute("drop sequence " + seqName); // depends on control dependency: [while], data = [none]
}
rs.close();
} finally {
stmtSel.close();
stmtExec.close();
}
} } |
public class class_name {
private void processLocalComponentClass(LocalComponents localComponents,
TypeElement localComponentType) {
String localComponentTagName;
try {
localComponentTagName = componentToTagName(localComponentType);
} catch (MissingComponentAnnotationException e) {
e.printStackTrace();
messager.printMessage(Kind.ERROR,
"Missing @Component or @JsComponent annotation on imported component: "
+ localComponentType.toString(), localComponentType);
return;
}
if (localComponents.hasLocalComponent(localComponentTagName)) {
return;
}
LocalComponent localComponent = localComponents
.addLocalComponent(localComponentTagName, localComponentType.asType());
ElementFilter.fieldsIn(localComponentType.getEnclosedElements()).forEach(field -> {
Prop propAnnotation = field.getAnnotation(Prop.class);
if (propAnnotation != null) {
localComponent.addProp(field.getSimpleName().toString(),
TypeName.get(field.asType()),
propAnnotation.required());
}
});
} } | public class class_name {
private void processLocalComponentClass(LocalComponents localComponents,
TypeElement localComponentType) {
String localComponentTagName;
try {
localComponentTagName = componentToTagName(localComponentType); // depends on control dependency: [try], data = [none]
} catch (MissingComponentAnnotationException e) {
e.printStackTrace();
messager.printMessage(Kind.ERROR,
"Missing @Component or @JsComponent annotation on imported component: "
+ localComponentType.toString(), localComponentType);
return;
} // depends on control dependency: [catch], data = [none]
if (localComponents.hasLocalComponent(localComponentTagName)) {
return; // depends on control dependency: [if], data = [none]
}
LocalComponent localComponent = localComponents
.addLocalComponent(localComponentTagName, localComponentType.asType());
ElementFilter.fieldsIn(localComponentType.getEnclosedElements()).forEach(field -> {
Prop propAnnotation = field.getAnnotation(Prop.class);
if (propAnnotation != null) {
localComponent.addProp(field.getSimpleName().toString(),
TypeName.get(field.asType()),
propAnnotation.required()); // depends on control dependency: [if], data = [none]
}
});
} } |
public class class_name {
@Override
protected UniversalIdIntQueueMessage readFromEphemeralStorage(Connection conn,
IQueueMessage<Long, byte[]> msg) {
Map<String, Object> dbRow = getJdbcHelper().executeSelectOne(conn, SQL_READ_FROM_EPHEMERAL,
msg.getId());
if (dbRow != null) {
UniversalIdIntQueueMessage myMsg = new UniversalIdIntQueueMessage();
return myMsg.fromMap(dbRow);
}
return null;
} } | public class class_name {
@Override
protected UniversalIdIntQueueMessage readFromEphemeralStorage(Connection conn,
IQueueMessage<Long, byte[]> msg) {
Map<String, Object> dbRow = getJdbcHelper().executeSelectOne(conn, SQL_READ_FROM_EPHEMERAL,
msg.getId());
if (dbRow != null) {
UniversalIdIntQueueMessage myMsg = new UniversalIdIntQueueMessage();
return myMsg.fromMap(dbRow); // depends on control dependency: [if], data = [(dbRow]
}
return null;
} } |
public class class_name {
private void updateCountSpan() {
//No count span with free form text
if (!preventFreeFormText) { return; }
Editable text = getText();
int visibleCount = getText().getSpans(0, getText().length(), TokenImageSpan.class).length;
countSpan.setCount(getObjects().size() - visibleCount);
SpannableStringBuilder spannedCountText = new SpannableStringBuilder(countSpan.getCountText());
spannedCountText.setSpan(countSpan, 0, spannedCountText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
internalEditInProgress = true;
int countStart = text.getSpanStart(countSpan);
if (countStart != -1) {
//Span is in the text, replace existing text
//This will also remove the span if the count is 0
text.replace(countStart, text.getSpanEnd(countSpan), spannedCountText);
} else {
text.append(spannedCountText);
}
internalEditInProgress = false;
} } | public class class_name {
private void updateCountSpan() {
//No count span with free form text
if (!preventFreeFormText) { return; } // depends on control dependency: [if], data = [none]
Editable text = getText();
int visibleCount = getText().getSpans(0, getText().length(), TokenImageSpan.class).length;
countSpan.setCount(getObjects().size() - visibleCount);
SpannableStringBuilder spannedCountText = new SpannableStringBuilder(countSpan.getCountText());
spannedCountText.setSpan(countSpan, 0, spannedCountText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
internalEditInProgress = true;
int countStart = text.getSpanStart(countSpan);
if (countStart != -1) {
//Span is in the text, replace existing text
//This will also remove the span if the count is 0
text.replace(countStart, text.getSpanEnd(countSpan), spannedCountText); // depends on control dependency: [if], data = [(countStart]
} else {
text.append(spannedCountText); // depends on control dependency: [if], data = [none]
}
internalEditInProgress = false;
} } |
public class class_name {
public void paint (Graphics2D gfx, int x, int y)
{
// Paint everyone.
for (Mirage m : _mirages) {
m.paint(gfx, x, y);
}
} } | public class class_name {
public void paint (Graphics2D gfx, int x, int y)
{
// Paint everyone.
for (Mirage m : _mirages) {
m.paint(gfx, x, y); // depends on control dependency: [for], data = [m]
}
} } |
public class class_name {
private static void compareMaps(Delta delta, Collection deltas, LinkedList stack, ID idFetcher)
{
Map<Object, Object> srcMap = (Map<Object, Object>) delta.srcValue;
Map<Object, Object> targetMap = (Map<Object, Object>) delta.targetValue;
// Walk source Map keys and see if they exist in target map. If not, that entry needs to be removed.
// If the key exists in both, then the value must tested for equivalence. If !equal, then a PUT command
// is created to re-associate target value to key.
final String sysId = "(" + System.identityHashCode(srcMap) + ')';
for (Map.Entry entry : srcMap.entrySet())
{
Object srcKey = entry.getKey();
Object srcValue = entry.getValue();
String srcPtr = sysId + "['" + System.identityHashCode(srcKey) + "']";
if (targetMap.containsKey(srcKey))
{
Object targetValue = targetMap.get(srcKey);
if (srcValue == null || targetValue == null)
{ // Null value in either source or target
if (srcValue != targetValue)
{ // Value differed, must create PUT command to overwrite source value associated to key
addMapPutDelta(delta, deltas, srcPtr, targetValue, srcKey);
}
}
else if (isIdObject(srcValue, idFetcher) && isIdObject(targetValue, idFetcher))
{ // Both source and destination have same object (by id) as the value, add delta to stack (field-by-field check for item).
if (idFetcher.getId(srcValue).equals(idFetcher.getId(targetValue)))
{
stack.push(new Delta(delta.id, delta.fieldName, srcPtr, srcValue, targetValue, null));
}
else
{ // Different ID associated to same key, must create PUT command to overwrite source value associated to key
addMapPutDelta(delta, deltas, srcPtr, targetValue, srcKey);
}
}
else if (!DeepEquals.deepEquals(srcValue, targetValue))
{ // Non-null, non-ID value associated to key, and the two values are not equal. Create PUT command to overwrite.
addMapPutDelta(delta, deltas, srcPtr, targetValue, srcKey);
}
}
else
{ // target does not have this Key in it's map, therefore create REMOVE command to remove it from source map.
Delta removeDelta = new Delta(delta.id, delta.fieldName, srcPtr, srcValue, null, srcKey);
removeDelta.setCmd(MAP_REMOVE);
deltas.add(removeDelta);
}
}
for (Map.Entry entry : targetMap.entrySet())
{
Object targetKey = entry.getKey();
String srcPtr = sysId + "['" + System.identityHashCode(targetKey) + "']";
if (!srcMap.containsKey(targetKey))
{ // Add Delta command map.put
Delta putDelta = new Delta(delta.id, delta.fieldName, srcPtr, null, entry.getValue(), targetKey);
putDelta.setCmd(MAP_PUT);
deltas.add(putDelta);
}
}
// TODO: If LinkedHashMap, may need to issue commands to reorder...
} } | public class class_name {
private static void compareMaps(Delta delta, Collection deltas, LinkedList stack, ID idFetcher)
{
Map<Object, Object> srcMap = (Map<Object, Object>) delta.srcValue;
Map<Object, Object> targetMap = (Map<Object, Object>) delta.targetValue;
// Walk source Map keys and see if they exist in target map. If not, that entry needs to be removed.
// If the key exists in both, then the value must tested for equivalence. If !equal, then a PUT command
// is created to re-associate target value to key.
final String sysId = "(" + System.identityHashCode(srcMap) + ')';
for (Map.Entry entry : srcMap.entrySet())
{
Object srcKey = entry.getKey();
Object srcValue = entry.getValue();
String srcPtr = sysId + "['" + System.identityHashCode(srcKey) + "']";
if (targetMap.containsKey(srcKey))
{
Object targetValue = targetMap.get(srcKey);
if (srcValue == null || targetValue == null)
{ // Null value in either source or target
if (srcValue != targetValue)
{ // Value differed, must create PUT command to overwrite source value associated to key
addMapPutDelta(delta, deltas, srcPtr, targetValue, srcKey); // depends on control dependency: [if], data = [none]
}
}
else if (isIdObject(srcValue, idFetcher) && isIdObject(targetValue, idFetcher))
{ // Both source and destination have same object (by id) as the value, add delta to stack (field-by-field check for item).
if (idFetcher.getId(srcValue).equals(idFetcher.getId(targetValue)))
{
stack.push(new Delta(delta.id, delta.fieldName, srcPtr, srcValue, targetValue, null)); // depends on control dependency: [if], data = [none]
}
else
{ // Different ID associated to same key, must create PUT command to overwrite source value associated to key
addMapPutDelta(delta, deltas, srcPtr, targetValue, srcKey); // depends on control dependency: [if], data = [none]
}
}
else if (!DeepEquals.deepEquals(srcValue, targetValue))
{ // Non-null, non-ID value associated to key, and the two values are not equal. Create PUT command to overwrite.
addMapPutDelta(delta, deltas, srcPtr, targetValue, srcKey); // depends on control dependency: [if], data = [none]
}
}
else
{ // target does not have this Key in it's map, therefore create REMOVE command to remove it from source map.
Delta removeDelta = new Delta(delta.id, delta.fieldName, srcPtr, srcValue, null, srcKey);
removeDelta.setCmd(MAP_REMOVE); // depends on control dependency: [if], data = [none]
deltas.add(removeDelta); // depends on control dependency: [if], data = [none]
}
}
for (Map.Entry entry : targetMap.entrySet())
{
Object targetKey = entry.getKey();
String srcPtr = sysId + "['" + System.identityHashCode(targetKey) + "']";
if (!srcMap.containsKey(targetKey))
{ // Add Delta command map.put
Delta putDelta = new Delta(delta.id, delta.fieldName, srcPtr, null, entry.getValue(), targetKey);
putDelta.setCmd(MAP_PUT); // depends on control dependency: [if], data = [none]
deltas.add(putDelta); // depends on control dependency: [if], data = [none]
}
}
// TODO: If LinkedHashMap, may need to issue commands to reorder...
} } |
public class class_name {
private boolean isSatisfied() {
if(pipelineData.getZonesRequired() != null) {
return ((pipelineData.getSuccesses() >= required) && (pipelineData.getZoneResponses()
.size() >= (pipelineData.getZonesRequired() + 1)));
} else {
return pipelineData.getSuccesses() >= required;
}
} } | public class class_name {
private boolean isSatisfied() {
if(pipelineData.getZonesRequired() != null) {
return ((pipelineData.getSuccesses() >= required) && (pipelineData.getZoneResponses()
.size() >= (pipelineData.getZonesRequired() + 1))); // depends on control dependency: [if], data = [none]
} else {
return pipelineData.getSuccesses() >= required; // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
public File transform(File inputFile,
File outFile,
GlobalTransform transform) {
try {
BufferedReader br = new BufferedReader(new FileReader(inputFile));
PrintWriter writer = new PrintWriter(new BufferedWriter(
new FileWriter(outFile)));
// Read in the header for the matrix.
String line = br.readLine();
String[] rowCol = line.split("\\s+");
int numRows = Integer.parseInt(rowCol[0]);
int numCols = Integer.parseInt(rowCol[1]);
// Write out the header for the matrix.
writer.printf("%d %d\n", numRows, numCols);
// Traverse each row.
for (int row = 0; (line = br.readLine()) != null &&
row < numRows; ++row) {
// Traverse each entry in the matrix and transform the value for
// the new matrix.
String[] values = line.split("\\s+");
StringBuilder sb = new StringBuilder(values.length * 4);
for (int col = 0; col < numCols; ++col) {
double value = Double.parseDouble(values[col]);
sb.append(transform.transform(row, col, value)).append(" ");
}
writer.println(sb.toString());
}
writer.close();
} catch (IOException ioe) {
throw new IOError(ioe);
}
return outFile;
} } | public class class_name {
public File transform(File inputFile,
File outFile,
GlobalTransform transform) {
try {
BufferedReader br = new BufferedReader(new FileReader(inputFile));
PrintWriter writer = new PrintWriter(new BufferedWriter(
new FileWriter(outFile)));
// Read in the header for the matrix.
String line = br.readLine();
String[] rowCol = line.split("\\s+");
int numRows = Integer.parseInt(rowCol[0]);
int numCols = Integer.parseInt(rowCol[1]);
// Write out the header for the matrix.
writer.printf("%d %d\n", numRows, numCols); // depends on control dependency: [try], data = [none]
// Traverse each row.
for (int row = 0; (line = br.readLine()) != null &&
row < numRows; ++row) {
// Traverse each entry in the matrix and transform the value for
// the new matrix.
String[] values = line.split("\\s+");
StringBuilder sb = new StringBuilder(values.length * 4);
for (int col = 0; col < numCols; ++col) {
double value = Double.parseDouble(values[col]);
sb.append(transform.transform(row, col, value)).append(" "); // depends on control dependency: [for], data = [col]
}
writer.println(sb.toString()); // depends on control dependency: [for], data = [none]
}
writer.close(); // depends on control dependency: [try], data = [none]
} catch (IOException ioe) {
throw new IOError(ioe);
} // depends on control dependency: [catch], data = [none]
return outFile;
} } |
public class class_name {
public Object[] getAnnotations() {
if (annotations == null) {
try {
annotations = getCtClass().getAvailableAnnotations();
} catch (Exception | Error e) {
return new Object[0];
}
}
return annotations;
} } | public class class_name {
public Object[] getAnnotations() {
if (annotations == null) {
try {
annotations = getCtClass().getAvailableAnnotations(); // depends on control dependency: [try], data = [none]
} catch (Exception | Error e) {
return new Object[0];
} // depends on control dependency: [catch], data = [none]
}
return annotations;
} } |
public class class_name {
@Override
public void start() {
// Get IPs
DnsResolve dns = new DnsResolve(mTarget);
dns.start();
List<String> ips = dns.getAddresses();
if (dns.getError() != Cmd.SUCCEED || ips == null || ips.size() == 0)
return;
mIP = ips.get(0);
// Cmd List
routeContainers = new ArrayList<>();
threads = new ArrayList<>(ONCE_COUNT);
// Loop
for (int i = 0; i < LOOP_COUNT; i++) {
countDownLatch = new CountDownLatch(ONCE_COUNT);
synchronized (mLock) {
for (int j = 1; j <= ONCE_COUNT; j++) {
// Get ttl
final int ttl = i * ONCE_COUNT + j;
// Thread run get tp ttl ping information
threads.add(new TraceRouteThread(mIP, ttl, this));
}
}
// Await 40 seconds long time
try {
countDownLatch.await(40, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
// End
if (countDownLatch.getCount() > 0) {
clear();
}
// Clear
countDownLatch = null;
synchronized (mLock) {
threads.clear();
}
// Break Loop
if (isDone || isArrived || errorCount > 3)
break;
}
// Set Result
if (routeContainers.size() > 0) {
// Sort
Collections.sort(routeContainers, new TraceRouteContainer.TraceRouteContainerComparator());
// Set values
ArrayList<String> routes = new ArrayList<>();
int size = routeContainers.size();
String prevIP = null;
// For
for (int s = 0; s < size; s++) {
TraceRouteContainer container = routeContainers.get(s);
if (prevIP != null && container.mIP.equals(prevIP)) {
break;
} else {
routes.add(container.toString());
prevIP = container.mIP;
}
}
routes.trimToSize();
mRoutes = routes;
}
// Clear
routeContainers = null;
threads = null;
} } | public class class_name {
@Override
public void start() {
// Get IPs
DnsResolve dns = new DnsResolve(mTarget);
dns.start();
List<String> ips = dns.getAddresses();
if (dns.getError() != Cmd.SUCCEED || ips == null || ips.size() == 0)
return;
mIP = ips.get(0);
// Cmd List
routeContainers = new ArrayList<>();
threads = new ArrayList<>(ONCE_COUNT);
// Loop
for (int i = 0; i < LOOP_COUNT; i++) {
countDownLatch = new CountDownLatch(ONCE_COUNT); // depends on control dependency: [for], data = [none]
synchronized (mLock) { // depends on control dependency: [for], data = [none]
for (int j = 1; j <= ONCE_COUNT; j++) {
// Get ttl
final int ttl = i * ONCE_COUNT + j;
// Thread run get tp ttl ping information
threads.add(new TraceRouteThread(mIP, ttl, this)); // depends on control dependency: [for], data = [none]
}
}
// Await 40 seconds long time
try {
countDownLatch.await(40, TimeUnit.SECONDS); // depends on control dependency: [try], data = [none]
} catch (InterruptedException e) {
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
// End
if (countDownLatch.getCount() > 0) {
clear(); // depends on control dependency: [if], data = [none]
}
// Clear
countDownLatch = null; // depends on control dependency: [for], data = [none]
synchronized (mLock) { // depends on control dependency: [for], data = [none]
threads.clear();
}
// Break Loop
if (isDone || isArrived || errorCount > 3)
break;
}
// Set Result
if (routeContainers.size() > 0) {
// Sort
Collections.sort(routeContainers, new TraceRouteContainer.TraceRouteContainerComparator()); // depends on control dependency: [if], data = [none]
// Set values
ArrayList<String> routes = new ArrayList<>();
int size = routeContainers.size();
String prevIP = null;
// For
for (int s = 0; s < size; s++) {
TraceRouteContainer container = routeContainers.get(s);
if (prevIP != null && container.mIP.equals(prevIP)) {
break;
} else {
routes.add(container.toString()); // depends on control dependency: [if], data = [none]
prevIP = container.mIP; // depends on control dependency: [if], data = [none]
}
}
routes.trimToSize(); // depends on control dependency: [if], data = [none]
mRoutes = routes; // depends on control dependency: [if], data = [none]
}
// Clear
routeContainers = null;
threads = null;
} } |
public class class_name {
private void initializeCaches(Map<String, Object> configProps) {
final String METHODNAME = "initializeCaches(DataObject)";
/*
* initialize the cache pool names
*/
iAttrsCacheName = iReposId + "/" + iAttrsCacheName;
iSearchResultsCacheName = iReposId + "/" + iSearchResultsCacheName;
List<Map<String, Object>> cacheConfigs = Nester.nest(CACHE_CONFIG, configProps);
Map<String, Object> attrCacheConfig = null;
Map<String, Object> searchResultsCacheConfig = null;
if (!cacheConfigs.isEmpty()) {
Map<String, Object> cacheConfig = cacheConfigs.get(0);
Map<String, List<Map<String, Object>>> cacheInfo = Nester.nest(cacheConfig, ATTRIBUTES_CACHE_CONFIG, SEARCH_CACHE_CONFIG);
List<Map<String, Object>> attrList = cacheInfo.get(ATTRIBUTES_CACHE_CONFIG);
if (!attrList.isEmpty()) {
attrCacheConfig = attrList.get(0);
}
List<Map<String, Object>> searchList = cacheInfo.get(SEARCH_CACHE_CONFIG);
if (!searchList.isEmpty()) {
searchResultsCacheConfig = searchList.get(0);
}
if (attrCacheConfig != null) {
iAttrsCacheEnabled = (Boolean) attrCacheConfig.get(CONFIG_PROP_ENABLED);
if (iAttrsCacheEnabled) {
// Initialize the Attributes Cache size
iAttrsCacheSize = (Integer) attrCacheConfig.get(CONFIG_PROP_CACHE_SIZE);
iAttrsCacheTimeOut = (Long) attrCacheConfig.get(CONFIG_PROP_CACHE_TIME_OUT);
iAttrsSizeLmit = (Integer) attrCacheConfig.get(CONFIG_PROP_ATTRIBUTE_SIZE_LIMIT);
/*
* TODO:: Cache Distribution is not yet needed.
* String cacheDistPolicy = attrCacheConfig.getString(CONFIG_PROP_CACHE_DIST_POLICY);
* if (cacheDistPolicy != null) {
* iAttrsCacheDistPolicy = LdapHelper.getCacheDistPolicyInt(cacheDistPolicy);
* }
*/
}
}
if (searchResultsCacheConfig != null) {
iSearchResultsCacheEnabled = (Boolean) searchResultsCacheConfig.get(CONFIG_PROP_ENABLED);
if (iSearchResultsCacheEnabled) {
// Initialize the Search Results Cache size
iSearchResultsCacheSize = (Integer) searchResultsCacheConfig.get(CONFIG_PROP_CACHE_SIZE);
iSearchResultsCacheTimeOut = (Long) searchResultsCacheConfig.get(CONFIG_PROP_CACHE_TIME_OUT);
iSearchResultSizeLmit = (Integer) searchResultsCacheConfig.get(CONFIG_PROP_SEARCH_RESULTS_SIZE_LIMIT);
/*
* TODO:: Cache Distribution is not yet needed.
* String cacheDistPolicy = searchResultsCacheConfig.getProperties().get(ConfigConstants.CONFIG_PROP_CACHE_DIST_POLICY);
* if (cacheDistPolicy != null) {
* iSearchResultsCacheDistPolicy = LdapHelper.getCacheDistPolicyInt(cacheDistPolicy);
* }
*/
}
}
}
if (iAttrsCacheEnabled) {
createAttributesCache();
if (iAttrsCache == null) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, METHODNAME + " Attributes Cache: " + iAttrsCacheName + " is not available because cache is not available yet.");
}
}
} else {
if (tc.isDebugEnabled()) {
Tr.debug(tc, METHODNAME + " Attributes Cache: " + iAttrsCacheName + " is disabled.");
}
}
if (iSearchResultsCacheEnabled) {
createSearchResultsCache();
if (iSearchResultsCache == null) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, METHODNAME + " Search Results Cache: " + iSearchResultsCacheName + " is not available because cache is not available yet.");
}
}
} else {
if (tc.isDebugEnabled()) {
Tr.debug(tc, METHODNAME + " Search Results Cache: " + iSearchResultsCacheName + " is disabled.");
}
}
} } | public class class_name {
private void initializeCaches(Map<String, Object> configProps) {
final String METHODNAME = "initializeCaches(DataObject)";
/*
* initialize the cache pool names
*/
iAttrsCacheName = iReposId + "/" + iAttrsCacheName;
iSearchResultsCacheName = iReposId + "/" + iSearchResultsCacheName;
List<Map<String, Object>> cacheConfigs = Nester.nest(CACHE_CONFIG, configProps);
Map<String, Object> attrCacheConfig = null;
Map<String, Object> searchResultsCacheConfig = null;
if (!cacheConfigs.isEmpty()) {
Map<String, Object> cacheConfig = cacheConfigs.get(0);
Map<String, List<Map<String, Object>>> cacheInfo = Nester.nest(cacheConfig, ATTRIBUTES_CACHE_CONFIG, SEARCH_CACHE_CONFIG);
List<Map<String, Object>> attrList = cacheInfo.get(ATTRIBUTES_CACHE_CONFIG);
if (!attrList.isEmpty()) {
attrCacheConfig = attrList.get(0); // depends on control dependency: [if], data = [none]
}
List<Map<String, Object>> searchList = cacheInfo.get(SEARCH_CACHE_CONFIG);
if (!searchList.isEmpty()) {
searchResultsCacheConfig = searchList.get(0); // depends on control dependency: [if], data = [none]
}
if (attrCacheConfig != null) {
iAttrsCacheEnabled = (Boolean) attrCacheConfig.get(CONFIG_PROP_ENABLED); // depends on control dependency: [if], data = [none]
if (iAttrsCacheEnabled) {
// Initialize the Attributes Cache size
iAttrsCacheSize = (Integer) attrCacheConfig.get(CONFIG_PROP_CACHE_SIZE); // depends on control dependency: [if], data = [none]
iAttrsCacheTimeOut = (Long) attrCacheConfig.get(CONFIG_PROP_CACHE_TIME_OUT); // depends on control dependency: [if], data = [none]
iAttrsSizeLmit = (Integer) attrCacheConfig.get(CONFIG_PROP_ATTRIBUTE_SIZE_LIMIT); // depends on control dependency: [if], data = [none]
/*
* TODO:: Cache Distribution is not yet needed.
* String cacheDistPolicy = attrCacheConfig.getString(CONFIG_PROP_CACHE_DIST_POLICY);
* if (cacheDistPolicy != null) {
* iAttrsCacheDistPolicy = LdapHelper.getCacheDistPolicyInt(cacheDistPolicy);
* }
*/
}
}
if (searchResultsCacheConfig != null) {
iSearchResultsCacheEnabled = (Boolean) searchResultsCacheConfig.get(CONFIG_PROP_ENABLED); // depends on control dependency: [if], data = [none]
if (iSearchResultsCacheEnabled) {
// Initialize the Search Results Cache size
iSearchResultsCacheSize = (Integer) searchResultsCacheConfig.get(CONFIG_PROP_CACHE_SIZE); // depends on control dependency: [if], data = [none]
iSearchResultsCacheTimeOut = (Long) searchResultsCacheConfig.get(CONFIG_PROP_CACHE_TIME_OUT); // depends on control dependency: [if], data = [none]
iSearchResultSizeLmit = (Integer) searchResultsCacheConfig.get(CONFIG_PROP_SEARCH_RESULTS_SIZE_LIMIT); // depends on control dependency: [if], data = [none]
/*
* TODO:: Cache Distribution is not yet needed.
* String cacheDistPolicy = searchResultsCacheConfig.getProperties().get(ConfigConstants.CONFIG_PROP_CACHE_DIST_POLICY);
* if (cacheDistPolicy != null) {
* iSearchResultsCacheDistPolicy = LdapHelper.getCacheDistPolicyInt(cacheDistPolicy);
* }
*/
}
}
}
if (iAttrsCacheEnabled) {
createAttributesCache(); // depends on control dependency: [if], data = [none]
if (iAttrsCache == null) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, METHODNAME + " Attributes Cache: " + iAttrsCacheName + " is not available because cache is not available yet."); // depends on control dependency: [if], data = [none]
}
}
} else {
if (tc.isDebugEnabled()) {
Tr.debug(tc, METHODNAME + " Attributes Cache: " + iAttrsCacheName + " is disabled."); // depends on control dependency: [if], data = [none]
}
}
if (iSearchResultsCacheEnabled) {
createSearchResultsCache(); // depends on control dependency: [if], data = [none]
if (iSearchResultsCache == null) {
if (tc.isDebugEnabled()) {
Tr.debug(tc, METHODNAME + " Search Results Cache: " + iSearchResultsCacheName + " is not available because cache is not available yet."); // depends on control dependency: [if], data = [none]
}
}
} else {
if (tc.isDebugEnabled()) {
Tr.debug(tc, METHODNAME + " Search Results Cache: " + iSearchResultsCacheName + " is disabled."); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
@Override
public List<Instance> listChildrenInstances( String applicationName, String instancePath, boolean allChildren ) {
List<Instance> result = new ArrayList<> ();
Application app = this.manager.applicationMngr().findApplicationByName( applicationName );
// Log
if( instancePath == null )
this.logger.fine( "Request: list " + (allChildren ? "all" : "root") + " instances for " + applicationName + "." );
else
this.logger.fine( "Request: list " + (allChildren ? "all" : "direct") + " children instances for " + instancePath + " in " + applicationName + "." );
// Find the instances
Instance inst;
if( app != null ) {
if( instancePath == null ) {
if( allChildren )
result.addAll( InstanceHelpers.getAllInstances( app ));
else
result.addAll( app.getRootInstances());
}
else if(( inst = InstanceHelpers.findInstanceByPath( app, instancePath )) != null ) {
if( allChildren ) {
result.addAll( InstanceHelpers.buildHierarchicalList( inst ));
result.remove( inst );
} else {
result.addAll( inst.getChildren());
}
}
}
// Bug #64: sort instance paths for the clients
Collections.sort( result, new InstanceComparator());
return result;
} } | public class class_name {
@Override
public List<Instance> listChildrenInstances( String applicationName, String instancePath, boolean allChildren ) {
List<Instance> result = new ArrayList<> ();
Application app = this.manager.applicationMngr().findApplicationByName( applicationName );
// Log
if( instancePath == null )
this.logger.fine( "Request: list " + (allChildren ? "all" : "root") + " instances for " + applicationName + "." );
else
this.logger.fine( "Request: list " + (allChildren ? "all" : "direct") + " children instances for " + instancePath + " in " + applicationName + "." );
// Find the instances
Instance inst;
if( app != null ) {
if( instancePath == null ) {
if( allChildren )
result.addAll( InstanceHelpers.getAllInstances( app ));
else
result.addAll( app.getRootInstances());
}
else if(( inst = InstanceHelpers.findInstanceByPath( app, instancePath )) != null ) {
if( allChildren ) {
result.addAll( InstanceHelpers.buildHierarchicalList( inst )); // depends on control dependency: [if], data = [none]
result.remove( inst ); // depends on control dependency: [if], data = [none]
} else {
result.addAll( inst.getChildren()); // depends on control dependency: [if], data = [none]
}
}
}
// Bug #64: sort instance paths for the clients
Collections.sort( result, new InstanceComparator());
return result;
} } |
public class class_name {
@Override
public String addContent(String spaceID,
String contentID,
InputStream content,
String contentMimeType,
Map<String, String> userProperties,
long contentSize,
String checksum,
String storeID)
throws ResourceException, InvalidIdException, ResourcePropertiesInvalidException {
IdUtil.validateContentId(contentID);
validateProperties(userProperties, "add content", spaceID, contentID);
try {
StorageProvider storage =
storageProviderFactory.getStorageProvider(storeID);
try {
// overlay new properties on top of older extended properties
// so that old tags and custom properties are preserved.
// c.f. https://jira.duraspace.org/browse/DURACLOUD-757
Map<String, String> oldUserProperties =
storage.getContentProperties(spaceID, contentID);
//remove all non extended properties
if (userProperties != null) {
oldUserProperties.putAll(userProperties);
//use old mimetype if none specified.
String oldMimetype =
oldUserProperties.remove(StorageProvider.PROPERTIES_CONTENT_MIMETYPE);
if (contentMimeType == null || contentMimeType.trim() == "") {
contentMimeType = oldMimetype;
}
oldUserProperties = StorageProviderUtil.removeCalculatedProperties(oldUserProperties);
}
userProperties = oldUserProperties;
} catch (NotFoundException ex) {
// do nothing - no properties to update
// since file did not previous exist.
}
return storage.addContent(spaceID,
contentID,
contentMimeType,
userProperties,
contentSize,
checksum,
content);
} catch (NotFoundException e) {
throw new ResourceNotFoundException("add content",
spaceID,
contentID,
e);
} catch (ChecksumMismatchException e) {
throw new ResourceChecksumException("add content",
spaceID,
contentID,
e);
} catch (Exception e) {
storageProviderFactory.expireStorageProvider(storeID);
throw new ResourceException("add content", spaceID, contentID, e);
}
} } | public class class_name {
@Override
public String addContent(String spaceID,
String contentID,
InputStream content,
String contentMimeType,
Map<String, String> userProperties,
long contentSize,
String checksum,
String storeID)
throws ResourceException, InvalidIdException, ResourcePropertiesInvalidException {
IdUtil.validateContentId(contentID);
validateProperties(userProperties, "add content", spaceID, contentID);
try {
StorageProvider storage =
storageProviderFactory.getStorageProvider(storeID);
try {
// overlay new properties on top of older extended properties
// so that old tags and custom properties are preserved.
// c.f. https://jira.duraspace.org/browse/DURACLOUD-757
Map<String, String> oldUserProperties =
storage.getContentProperties(spaceID, contentID);
//remove all non extended properties
if (userProperties != null) {
oldUserProperties.putAll(userProperties); // depends on control dependency: [if], data = [(userProperties]
//use old mimetype if none specified.
String oldMimetype =
oldUserProperties.remove(StorageProvider.PROPERTIES_CONTENT_MIMETYPE);
if (contentMimeType == null || contentMimeType.trim() == "") {
contentMimeType = oldMimetype; // depends on control dependency: [if], data = [none]
}
oldUserProperties = StorageProviderUtil.removeCalculatedProperties(oldUserProperties); // depends on control dependency: [if], data = [none]
}
userProperties = oldUserProperties; // depends on control dependency: [try], data = [none]
} catch (NotFoundException ex) {
// do nothing - no properties to update
// since file did not previous exist.
} // depends on control dependency: [catch], data = [none]
return storage.addContent(spaceID,
contentID,
contentMimeType,
userProperties,
contentSize,
checksum,
content);
} catch (NotFoundException e) {
throw new ResourceNotFoundException("add content",
spaceID,
contentID,
e);
} catch (ChecksumMismatchException e) {
throw new ResourceChecksumException("add content",
spaceID,
contentID,
e);
} catch (Exception e) {
storageProviderFactory.expireStorageProvider(storeID);
throw new ResourceException("add content", spaceID, contentID, e);
}
} } |
public class class_name {
public void init(ServletConfig servletConfig) throws ServletException {
// Save our ServletConfig instance
this.servletConfig = servletConfig;
// Acquire our FacesContextFactory instance
try {
facesContextFactory = (FacesContextFactory)
FactoryFinder.getFactory
(FactoryFinder.FACES_CONTEXT_FACTORY);
} catch (FacesException e) {
ResourceBundle rb = LOGGER.getResourceBundle();
String msg = rb.getString("severe.webapp.facesservlet.init_failed");
Throwable rootCause = (e.getCause() != null) ? e.getCause() : e;
LOGGER.log(Level.SEVERE, msg, rootCause);
throw new UnavailableException(msg);
}
// Acquire our Lifecycle instance
try {
LifecycleFactory lifecycleFactory = (LifecycleFactory)
FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
String lifecycleId ;
// First look in the servlet init-param set
if (null == (lifecycleId = servletConfig.getInitParameter(LIFECYCLE_ID_ATTR))) {
// If not found, look in the context-param set
lifecycleId = servletConfig.getServletContext().getInitParameter
(LIFECYCLE_ID_ATTR);
}
if (lifecycleId == null) {
lifecycleId = LifecycleFactory.DEFAULT_LIFECYCLE;
}
lifecycle = lifecycleFactory.getLifecycle(lifecycleId);
initHttpMethodValidityVerification();
} catch (FacesException e) {
Throwable rootCause = e.getCause();
if (rootCause == null) {
throw e;
} else {
throw new ServletException(e.getMessage(), rootCause);
}
}
} } | public class class_name {
public void init(ServletConfig servletConfig) throws ServletException {
// Save our ServletConfig instance
this.servletConfig = servletConfig;
// Acquire our FacesContextFactory instance
try {
facesContextFactory = (FacesContextFactory)
FactoryFinder.getFactory
(FactoryFinder.FACES_CONTEXT_FACTORY);
} catch (FacesException e) {
ResourceBundle rb = LOGGER.getResourceBundle();
String msg = rb.getString("severe.webapp.facesservlet.init_failed");
Throwable rootCause = (e.getCause() != null) ? e.getCause() : e;
LOGGER.log(Level.SEVERE, msg, rootCause);
throw new UnavailableException(msg);
}
// Acquire our Lifecycle instance
try {
LifecycleFactory lifecycleFactory = (LifecycleFactory)
FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
String lifecycleId ;
// First look in the servlet init-param set
if (null == (lifecycleId = servletConfig.getInitParameter(LIFECYCLE_ID_ATTR))) {
// If not found, look in the context-param set
lifecycleId = servletConfig.getServletContext().getInitParameter
(LIFECYCLE_ID_ATTR); // depends on control dependency: [if], data = [none]
}
if (lifecycleId == null) {
lifecycleId = LifecycleFactory.DEFAULT_LIFECYCLE; // depends on control dependency: [if], data = [none]
}
lifecycle = lifecycleFactory.getLifecycle(lifecycleId);
initHttpMethodValidityVerification();
} catch (FacesException e) {
Throwable rootCause = e.getCause();
if (rootCause == null) {
throw e;
} else {
throw new ServletException(e.getMessage(), rootCause);
}
}
} } |
public class class_name {
public Map<Object, Object> parseMapElement(Element mapEle, BeanDefinition bd) {
String defaultKeyType = mapEle.getAttribute(KEY_TYPE_ATTRIBUTE);
String defaultValueType = mapEle.getAttribute(VALUE_TYPE_ATTRIBUTE);
List<Element> entryEles = DomUtils.getChildElementsByTagName(mapEle, ENTRY_ELEMENT);
ManagedMap<Object, Object> map = new ManagedMap<Object, Object>(entryEles.size());
map.setSource(extractSource(mapEle));
map.setKeyTypeName(defaultKeyType);
map.setValueTypeName(defaultValueType);
map.setMergeEnabled(parseMergeAttribute(mapEle));
for (Element entryEle : entryEles) {
// Should only have one value child element: ref, value, list, etc.
// Optionally, there might be a key child element.
NodeList entrySubNodes = entryEle.getChildNodes();
Element keyEle = null;
Element valueEle = null;
for (int j = 0; j < entrySubNodes.getLength(); j++) {
Node node = entrySubNodes.item(j);
if (node instanceof Element) {
Element candidateEle = (Element) node;
if (nodeNameEquals(candidateEle, KEY_ELEMENT)) {
if (keyEle != null)
error("<entry> element is only allowed to contain one <key> sub-element", entryEle);
else keyEle = candidateEle;
} else {
// Child element is what we're looking for.
if (valueEle != null)
error("<entry> element must not contain more than one value sub-element", entryEle);
else valueEle = candidateEle;
}
}
}
// Extract key from attribute or sub-element.
Object key = null;
boolean hasKeyAttribute = entryEle.hasAttribute(KEY_ATTRIBUTE);
boolean hasKeyRefAttribute = entryEle.hasAttribute(KEY_REF_ATTRIBUTE);
if ((hasKeyAttribute && hasKeyRefAttribute)
|| ((hasKeyAttribute || hasKeyRefAttribute)) && keyEle != null) {
error("<entry> element is only allowed to contain either "
+ "a 'key' attribute OR a 'key-ref' attribute OR a <key> sub-element", entryEle);
}
if (hasKeyAttribute) {
key = buildTypedStringValueForMap(entryEle.getAttribute(KEY_ATTRIBUTE), defaultKeyType, entryEle);
} else if (hasKeyRefAttribute) {
String refName = entryEle.getAttribute(KEY_REF_ATTRIBUTE);
if (!StringUtils.hasText(refName))
error("<entry> element contains empty 'key-ref' attribute", entryEle);
RuntimeBeanReference ref = new RuntimeBeanReference(refName);
ref.setSource(extractSource(entryEle));
key = ref;
} else if (keyEle != null) {
key = parseKeyElement(keyEle, bd, defaultKeyType);
} else {
error("<entry> element must specify a key", entryEle);
}
// Extract value from attribute or sub-element.
Object value = null;
boolean hasValueAttribute = entryEle.hasAttribute(VALUE_ATTRIBUTE);
boolean hasValueRefAttribute = entryEle.hasAttribute(VALUE_REF_ATTRIBUTE);
if ((hasValueAttribute && hasValueRefAttribute)
|| ((hasValueAttribute || hasValueRefAttribute)) && valueEle != null) {
error("<entry> element is only allowed to contain either "
+ "'value' attribute OR 'value-ref' attribute OR <value> sub-element", entryEle);
}
if (hasValueAttribute) {
value = buildTypedStringValueForMap(entryEle.getAttribute(VALUE_ATTRIBUTE), defaultValueType,
entryEle);
} else if (hasValueRefAttribute) {
String refName = entryEle.getAttribute(VALUE_REF_ATTRIBUTE);
if (!StringUtils.hasText(refName)) {
error("<entry> element contains empty 'value-ref' attribute", entryEle);
}
RuntimeBeanReference ref = new RuntimeBeanReference(refName);
ref.setSource(extractSource(entryEle));
value = ref;
} else if (valueEle != null) {
value = parsePropertySubElement(valueEle, bd, defaultValueType);
} else {
error("<entry> element must specify a value", entryEle);
}
// Add final key and value to the Map.
map.put(key, value);
}
return map;
} } | public class class_name {
public Map<Object, Object> parseMapElement(Element mapEle, BeanDefinition bd) {
String defaultKeyType = mapEle.getAttribute(KEY_TYPE_ATTRIBUTE);
String defaultValueType = mapEle.getAttribute(VALUE_TYPE_ATTRIBUTE);
List<Element> entryEles = DomUtils.getChildElementsByTagName(mapEle, ENTRY_ELEMENT);
ManagedMap<Object, Object> map = new ManagedMap<Object, Object>(entryEles.size());
map.setSource(extractSource(mapEle));
map.setKeyTypeName(defaultKeyType);
map.setValueTypeName(defaultValueType);
map.setMergeEnabled(parseMergeAttribute(mapEle));
for (Element entryEle : entryEles) {
// Should only have one value child element: ref, value, list, etc.
// Optionally, there might be a key child element.
NodeList entrySubNodes = entryEle.getChildNodes();
Element keyEle = null;
Element valueEle = null;
for (int j = 0; j < entrySubNodes.getLength(); j++) {
Node node = entrySubNodes.item(j);
if (node instanceof Element) {
Element candidateEle = (Element) node;
if (nodeNameEquals(candidateEle, KEY_ELEMENT)) {
if (keyEle != null)
error("<entry> element is only allowed to contain one <key> sub-element", entryEle);
else keyEle = candidateEle;
} else {
// Child element is what we're looking for.
if (valueEle != null)
error("<entry> element must not contain more than one value sub-element", entryEle); // depends on control dependency: [if], data = [none]
else valueEle = candidateEle;
}
}
}
// Extract key from attribute or sub-element.
Object key = null;
boolean hasKeyAttribute = entryEle.hasAttribute(KEY_ATTRIBUTE);
boolean hasKeyRefAttribute = entryEle.hasAttribute(KEY_REF_ATTRIBUTE);
if ((hasKeyAttribute && hasKeyRefAttribute)
|| ((hasKeyAttribute || hasKeyRefAttribute)) && keyEle != null) {
error("<entry> element is only allowed to contain either "
+ "a 'key' attribute OR a 'key-ref' attribute OR a <key> sub-element", entryEle);
}
if (hasKeyAttribute) {
key = buildTypedStringValueForMap(entryEle.getAttribute(KEY_ATTRIBUTE), defaultKeyType, entryEle); // depends on control dependency: [if], data = [none]
} else if (hasKeyRefAttribute) {
String refName = entryEle.getAttribute(KEY_REF_ATTRIBUTE);
if (!StringUtils.hasText(refName))
error("<entry> element contains empty 'key-ref' attribute", entryEle);
RuntimeBeanReference ref = new RuntimeBeanReference(refName);
ref.setSource(extractSource(entryEle)); // depends on control dependency: [if], data = [none]
key = ref; // depends on control dependency: [if], data = [none]
} else if (keyEle != null) {
key = parseKeyElement(keyEle, bd, defaultKeyType); // depends on control dependency: [if], data = [(keyEle]
} else {
error("<entry> element must specify a key", entryEle);
}
// Extract value from attribute or sub-element.
Object value = null;
boolean hasValueAttribute = entryEle.hasAttribute(VALUE_ATTRIBUTE);
boolean hasValueRefAttribute = entryEle.hasAttribute(VALUE_REF_ATTRIBUTE);
if ((hasValueAttribute && hasValueRefAttribute)
|| ((hasValueAttribute || hasValueRefAttribute)) && valueEle != null) {
error("<entry> element is only allowed to contain either "
+ "'value' attribute OR 'value-ref' attribute OR <value> sub-element", entryEle); // depends on control dependency: [if], data = [none]
}
if (hasValueAttribute) {
value = buildTypedStringValueForMap(entryEle.getAttribute(VALUE_ATTRIBUTE), defaultValueType,
entryEle); // depends on control dependency: [if], data = [none]
} else if (hasValueRefAttribute) {
String refName = entryEle.getAttribute(VALUE_REF_ATTRIBUTE);
if (!StringUtils.hasText(refName)) {
error("<entry> element contains empty 'value-ref' attribute", entryEle);
}
RuntimeBeanReference ref = new RuntimeBeanReference(refName);
ref.setSource(extractSource(entryEle)); // depends on control dependency: [if], data = [none]
value = ref; // depends on control dependency: [if], data = [none]
} else if (valueEle != null) {
value = parsePropertySubElement(valueEle, bd, defaultValueType); // depends on control dependency: [if], data = [(valueEle]
} else {
error("<entry> element must specify a value", entryEle);
}
// Add final key and value to the Map.
map.put(key, value); // depends on control dependency: [for], data = [none]
}
return map;
} } |
public class class_name {
@Override
protected String doBuildColumnString(String dm) {
StringBuilder sb = new StringBuilder();
sb.append(dm).append(businessCategory);
sb.append(dm).append(carLicense);
sb.append(dm).append(city);
sb.append(dm).append(departmentNumber);
sb.append(dm).append(description);
sb.append(dm).append(destinationIndicator);
sb.append(dm).append(displayName);
sb.append(dm).append(employeeNumber);
sb.append(dm).append(employeeType);
sb.append(dm).append(facsimileTelephoneNumber);
sb.append(dm).append(gidNumber);
sb.append(dm).append(givenName);
sb.append(dm).append(groups);
sb.append(dm).append(homeDirectory);
sb.append(dm).append(homePhone);
sb.append(dm).append(homePostalAddress);
sb.append(dm).append(initials);
sb.append(dm).append(internationaliSDNNumber);
sb.append(dm).append(labeledURI);
sb.append(dm).append(mail);
sb.append(dm).append(mobile);
sb.append(dm).append(name);
sb.append(dm).append(pager);
sb.append(dm).append(password);
sb.append(dm).append(physicalDeliveryOfficeName);
sb.append(dm).append(postOfficeBox);
sb.append(dm).append(postalAddress);
sb.append(dm).append(postalCode);
sb.append(dm).append(preferredLanguage);
sb.append(dm).append(registeredAddress);
sb.append(dm).append(roles);
sb.append(dm).append(roomNumber);
sb.append(dm).append(state);
sb.append(dm).append(street);
sb.append(dm).append(surname);
sb.append(dm).append(telephoneNumber);
sb.append(dm).append(teletexTerminalIdentifier);
sb.append(dm).append(title);
sb.append(dm).append(uidNumber);
sb.append(dm).append(x121Address);
if (sb.length() > dm.length()) {
sb.delete(0, dm.length());
}
sb.insert(0, "{").append("}");
return sb.toString();
} } | public class class_name {
@Override
protected String doBuildColumnString(String dm) {
StringBuilder sb = new StringBuilder();
sb.append(dm).append(businessCategory);
sb.append(dm).append(carLicense);
sb.append(dm).append(city);
sb.append(dm).append(departmentNumber);
sb.append(dm).append(description);
sb.append(dm).append(destinationIndicator);
sb.append(dm).append(displayName);
sb.append(dm).append(employeeNumber);
sb.append(dm).append(employeeType);
sb.append(dm).append(facsimileTelephoneNumber);
sb.append(dm).append(gidNumber);
sb.append(dm).append(givenName);
sb.append(dm).append(groups);
sb.append(dm).append(homeDirectory);
sb.append(dm).append(homePhone);
sb.append(dm).append(homePostalAddress);
sb.append(dm).append(initials);
sb.append(dm).append(internationaliSDNNumber);
sb.append(dm).append(labeledURI);
sb.append(dm).append(mail);
sb.append(dm).append(mobile);
sb.append(dm).append(name);
sb.append(dm).append(pager);
sb.append(dm).append(password);
sb.append(dm).append(physicalDeliveryOfficeName);
sb.append(dm).append(postOfficeBox);
sb.append(dm).append(postalAddress);
sb.append(dm).append(postalCode);
sb.append(dm).append(preferredLanguage);
sb.append(dm).append(registeredAddress);
sb.append(dm).append(roles);
sb.append(dm).append(roomNumber);
sb.append(dm).append(state);
sb.append(dm).append(street);
sb.append(dm).append(surname);
sb.append(dm).append(telephoneNumber);
sb.append(dm).append(teletexTerminalIdentifier);
sb.append(dm).append(title);
sb.append(dm).append(uidNumber);
sb.append(dm).append(x121Address);
if (sb.length() > dm.length()) {
sb.delete(0, dm.length()); // depends on control dependency: [if], data = [dm.length())]
}
sb.insert(0, "{").append("}");
return sb.toString();
} } |
public class class_name {
public static String resolveAndReplace(char[] chars, int offset, int length, Map<String, String> parameterValuePairs,
Properties configuration, List<String> errors) {
int lastMatchCharIndex = 0;
StringBuffer string = new StringBuffer();
Matcher matcher = PARAM_REGEX.matcher(CharBuffer.wrap(chars, offset, length));
while (matcher.find()) {
// we have a match, pull out the details and assign defaults
String name = matcher.group(ParameterRegex.PARAM.index);
String value = null;
ParameterResolutionStrategy strategy = ParameterResolutionStrategy.PARAMETER_DEFINITION_DEFAULT;
// process the prefix to the match
string.append(chars, offset + lastMatchCharIndex, matcher.start() - lastMatchCharIndex);
lastMatchCharIndex = matcher.end(ParameterRegex.CLOSE.index);
// match escape sequence
if (matcher.start(ParameterRegex.ESCAPE.index) != matcher.end(ParameterRegex.ESCAPE.index)) {
// we have an escaped out match, drop leading escape tokens and pass the match through unchanged
value = new String(chars, offset + matcher.start(ParameterRegex.OPEN.index),
matcher.end(ParameterRegex.CLOSE.index) - matcher.start(ParameterRegex.OPEN.index));
strategy = ParameterResolutionStrategy.ESCAPED_PARAMETER_DEFINITION;
}
// match parameter definition
else {
// attempt to resolve value from hierarchy of value stores
if (!"".equals(name)) {
if ((value = configuration.getProperty(name)) != null && !"".equals(value)) {
strategy = ParameterResolutionStrategy.SYSTEM_PROPERTIES;
}
else if ((value = parameterValuePairs.get(name)) != null && !"".equals(value)) {
strategy = ParameterResolutionStrategy.PARAMETER_DEFINITION_DEFAULT;
}
}
}
// resolve cloud.host
if (value == null && "cloud.host".equals(matcher.group(3))) {
LOGGER.info("${cloud.host} found in config, attempting resolution by searching cloud provider");
strategy = ParameterResolutionStrategy.CLOUD_RESOLUTION_STRATEGY;
value = resolveCloudHost(new DefaultUtilityHttpClient());
// value may be returned as null but that is good so it is caught as can't
// determine value
if (value == null) {
LOGGER.warn("${cloud.host} detected in config but could not " +
"determine cloud enviroment and find valid replacement for it");
}
}
// resolve hostname
if (value == null && "hostname".equals(matcher.group(3))) {
LOGGER.debug("${hostname} found in config, using box hostname");
strategy = ParameterResolutionStrategy.HOSTNAME;
value = resolveHostname();
// value may be returned as null but that is good so it is caught as can't
// determine value
if (value == null) {
LOGGER.warn("${hostname} detected in config but could not " +
"determine cloud enviroment and find valid replacement for it");
}
}
// resolve cloud.instanceId
if (value == null && "cloud.instanceId".equals(matcher.group(3))) {
LOGGER.info("${cloud.instanceId} found in config, attempting resolution by searching cloud provider");
strategy = ParameterResolutionStrategy.CLOUD_RESOLUTION_STRATEGY;
value = resolveCloudInstanceId(new DefaultUtilityHttpClient());
// value may be returned as null but that is good so it is caught as can't
// determine value
if (value == null) {
LOGGER.warn("${cloud.instanceId} detected in config but could not " +
"determine cloud enviroment and find valid replacement for it");
}
}
// if not resolved, add error and pass match through unchanged
if (value == null || "".equals(value)) {
value = matcher.group();
strategy = ParameterResolutionStrategy.UNRESOLVED_PARAMETER_DEFINITION;
errors.add("Could not determine non-null value for parameter definition "
+ matcher.group());
}
// add resolved value
string.append(value);
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Detected configuration parameter [" + matcher.group() + "], replaced with [" + value
+ "], as a result of resolution strategy [" + strategy + "]");
}
}
// we have a match/non-match, process suffix/entire buffer
string.append(chars, offset + lastMatchCharIndex, length - lastMatchCharIndex);
return string.toString();
} } | public class class_name {
public static String resolveAndReplace(char[] chars, int offset, int length, Map<String, String> parameterValuePairs,
Properties configuration, List<String> errors) {
int lastMatchCharIndex = 0;
StringBuffer string = new StringBuffer();
Matcher matcher = PARAM_REGEX.matcher(CharBuffer.wrap(chars, offset, length));
while (matcher.find()) {
// we have a match, pull out the details and assign defaults
String name = matcher.group(ParameterRegex.PARAM.index);
String value = null;
ParameterResolutionStrategy strategy = ParameterResolutionStrategy.PARAMETER_DEFINITION_DEFAULT;
// process the prefix to the match
string.append(chars, offset + lastMatchCharIndex, matcher.start() - lastMatchCharIndex); // depends on control dependency: [while], data = [none]
lastMatchCharIndex = matcher.end(ParameterRegex.CLOSE.index); // depends on control dependency: [while], data = [none]
// match escape sequence
if (matcher.start(ParameterRegex.ESCAPE.index) != matcher.end(ParameterRegex.ESCAPE.index)) {
// we have an escaped out match, drop leading escape tokens and pass the match through unchanged
value = new String(chars, offset + matcher.start(ParameterRegex.OPEN.index),
matcher.end(ParameterRegex.CLOSE.index) - matcher.start(ParameterRegex.OPEN.index)); // depends on control dependency: [if], data = [none]
strategy = ParameterResolutionStrategy.ESCAPED_PARAMETER_DEFINITION; // depends on control dependency: [if], data = [none]
}
// match parameter definition
else {
// attempt to resolve value from hierarchy of value stores
if (!"".equals(name)) {
if ((value = configuration.getProperty(name)) != null && !"".equals(value)) {
strategy = ParameterResolutionStrategy.SYSTEM_PROPERTIES; // depends on control dependency: [if], data = [none]
}
else if ((value = parameterValuePairs.get(name)) != null && !"".equals(value)) {
strategy = ParameterResolutionStrategy.PARAMETER_DEFINITION_DEFAULT; // depends on control dependency: [if], data = [none]
}
}
}
// resolve cloud.host
if (value == null && "cloud.host".equals(matcher.group(3))) {
LOGGER.info("${cloud.host} found in config, attempting resolution by searching cloud provider"); // depends on control dependency: [if], data = [none]
strategy = ParameterResolutionStrategy.CLOUD_RESOLUTION_STRATEGY; // depends on control dependency: [if], data = [none]
value = resolveCloudHost(new DefaultUtilityHttpClient()); // depends on control dependency: [if], data = [none]
// value may be returned as null but that is good so it is caught as can't
// determine value
if (value == null) {
LOGGER.warn("${cloud.host} detected in config but could not " +
"determine cloud enviroment and find valid replacement for it"); // depends on control dependency: [if], data = [none]
}
}
// resolve hostname
if (value == null && "hostname".equals(matcher.group(3))) {
LOGGER.debug("${hostname} found in config, using box hostname"); // depends on control dependency: [if], data = [none]
strategy = ParameterResolutionStrategy.HOSTNAME; // depends on control dependency: [if], data = [none]
value = resolveHostname(); // depends on control dependency: [if], data = [none]
// value may be returned as null but that is good so it is caught as can't
// determine value
if (value == null) {
LOGGER.warn("${hostname} detected in config but could not " +
"determine cloud enviroment and find valid replacement for it"); // depends on control dependency: [if], data = [none]
}
}
// resolve cloud.instanceId
if (value == null && "cloud.instanceId".equals(matcher.group(3))) {
LOGGER.info("${cloud.instanceId} found in config, attempting resolution by searching cloud provider"); // depends on control dependency: [if], data = [none]
strategy = ParameterResolutionStrategy.CLOUD_RESOLUTION_STRATEGY; // depends on control dependency: [if], data = [none]
value = resolveCloudInstanceId(new DefaultUtilityHttpClient()); // depends on control dependency: [if], data = [none]
// value may be returned as null but that is good so it is caught as can't
// determine value
if (value == null) {
LOGGER.warn("${cloud.instanceId} detected in config but could not " +
"determine cloud enviroment and find valid replacement for it"); // depends on control dependency: [if], data = [none]
}
}
// if not resolved, add error and pass match through unchanged
if (value == null || "".equals(value)) {
value = matcher.group(); // depends on control dependency: [if], data = [none]
strategy = ParameterResolutionStrategy.UNRESOLVED_PARAMETER_DEFINITION; // depends on control dependency: [if], data = [none]
errors.add("Could not determine non-null value for parameter definition "
+ matcher.group()); // depends on control dependency: [if], data = [none]
}
// add resolved value
string.append(value); // depends on control dependency: [while], data = [none]
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Detected configuration parameter [" + matcher.group() + "], replaced with [" + value
+ "], as a result of resolution strategy [" + strategy + "]"); // depends on control dependency: [if], data = [none]
}
}
// we have a match/non-match, process suffix/entire buffer
string.append(chars, offset + lastMatchCharIndex, length - lastMatchCharIndex);
return string.toString();
} } |
public class class_name {
public JSONValue toJson() {
JSONObject result = new JSONObject();
if (null != getStart()) {
result.put(JsonKey.START, dateToJson(getStart()));
}
if (null != getEnd()) {
result.put(JsonKey.END, dateToJson(getEnd()));
}
if (isWholeDay()) {
result.put(JsonKey.WHOLE_DAY, JSONBoolean.getInstance(true));
}
JSONObject pattern = patternToJson();
result.put(JsonKey.PATTERN, pattern);
SortedSet<Date> exceptions = getExceptions();
if (exceptions.size() > 0) {
result.put(JsonKey.EXCEPTIONS, datesToJsonArray(exceptions));
}
switch (getEndType()) {
case DATE:
result.put(JsonKey.SERIES_ENDDATE, dateToJson(getSeriesEndDate()));
break;
case TIMES:
result.put(JsonKey.SERIES_OCCURRENCES, new JSONString(String.valueOf(getOccurrences())));
break;
case SINGLE:
default:
break;
}
if (!isCurrentTillEnd()) {
result.put(JsonKey.CURRENT_TILL_END, JSONBoolean.getInstance(false));
}
if (getParentSeriesId() != null) {
result.put(JsonKey.PARENT_SERIES, new JSONString(getParentSeriesId().getStringValue()));
}
return result;
} } | public class class_name {
public JSONValue toJson() {
JSONObject result = new JSONObject();
if (null != getStart()) {
result.put(JsonKey.START, dateToJson(getStart())); // depends on control dependency: [if], data = [getStart())]
}
if (null != getEnd()) {
result.put(JsonKey.END, dateToJson(getEnd())); // depends on control dependency: [if], data = [getEnd())]
}
if (isWholeDay()) {
result.put(JsonKey.WHOLE_DAY, JSONBoolean.getInstance(true)); // depends on control dependency: [if], data = [none]
}
JSONObject pattern = patternToJson();
result.put(JsonKey.PATTERN, pattern);
SortedSet<Date> exceptions = getExceptions();
if (exceptions.size() > 0) {
result.put(JsonKey.EXCEPTIONS, datesToJsonArray(exceptions)); // depends on control dependency: [if], data = [none]
}
switch (getEndType()) {
case DATE:
result.put(JsonKey.SERIES_ENDDATE, dateToJson(getSeriesEndDate()));
break;
case TIMES:
result.put(JsonKey.SERIES_OCCURRENCES, new JSONString(String.valueOf(getOccurrences())));
break;
case SINGLE:
default:
break;
}
if (!isCurrentTillEnd()) {
result.put(JsonKey.CURRENT_TILL_END, JSONBoolean.getInstance(false));
}
if (getParentSeriesId() != null) {
result.put(JsonKey.PARENT_SERIES, new JSONString(getParentSeriesId().getStringValue()));
}
return result;
} } |
public class class_name {
ImmutableSortedSet<String> typesToImport() {
ImmutableSortedSet.Builder<String> typesToImport = ImmutableSortedSet.naturalOrder();
for (Map.Entry<String, Spelling> entry : imports.entrySet()) {
if (entry.getValue().importIt) {
typesToImport.add(entry.getKey());
}
}
return typesToImport.build();
} } | public class class_name {
ImmutableSortedSet<String> typesToImport() {
ImmutableSortedSet.Builder<String> typesToImport = ImmutableSortedSet.naturalOrder();
for (Map.Entry<String, Spelling> entry : imports.entrySet()) {
if (entry.getValue().importIt) {
typesToImport.add(entry.getKey()); // depends on control dependency: [if], data = [none]
}
}
return typesToImport.build();
} } |
public class class_name {
public Integer getAssistedQueryColumnCount(final String logicTableName) {
if (Collections2.filter(columns, new Predicate<ColumnNode>() {
@Override
public boolean apply(final ColumnNode input) {
return input.getTableName().equals(logicTableName);
}
}).isEmpty()) {
return 0;
}
return Collections2.filter(assistedQueryColumns, new Predicate<ColumnNode>() {
@Override
public boolean apply(final ColumnNode input) {
return input.getTableName().equals(logicTableName);
}
}).size();
} } | public class class_name {
public Integer getAssistedQueryColumnCount(final String logicTableName) {
if (Collections2.filter(columns, new Predicate<ColumnNode>() {
@Override
public boolean apply(final ColumnNode input) {
return input.getTableName().equals(logicTableName);
}
}).isEmpty()) {
return 0; // depends on control dependency: [if], data = [none]
}
return Collections2.filter(assistedQueryColumns, new Predicate<ColumnNode>() {
@Override
public boolean apply(final ColumnNode input) {
return input.getTableName().equals(logicTableName);
}
}).size();
} } |
public class class_name {
public static String cleanPath(final URL url) {
String path = url.getPath();
try {
path = URLDecoder.decode(path, "UTF-8");
} catch (UnsupportedEncodingException e) { /**/ }
if (path.startsWith("jar:")) {
path = path.substring("jar:".length());
}
if (path.startsWith("file:")) {
path = path.substring("file:".length());
}
if (path.endsWith("!/")) {
path = path.substring(0, path.lastIndexOf("!/")) + "/";
}
return path;
} } | public class class_name {
public static String cleanPath(final URL url) {
String path = url.getPath();
try {
path = URLDecoder.decode(path, "UTF-8"); // depends on control dependency: [try], data = [none]
} catch (UnsupportedEncodingException e) { /**/ } // depends on control dependency: [catch], data = [none]
if (path.startsWith("jar:")) {
path = path.substring("jar:".length()); // depends on control dependency: [if], data = [none]
}
if (path.startsWith("file:")) {
path = path.substring("file:".length()); // depends on control dependency: [if], data = [none]
}
if (path.endsWith("!/")) {
path = path.substring(0, path.lastIndexOf("!/")) + "/"; // depends on control dependency: [if], data = [none]
}
return path;
} } |
public class class_name {
public void marshall(Stack stack, ProtocolMarshaller protocolMarshaller) {
if (stack == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(stack.getArn(), ARN_BINDING);
protocolMarshaller.marshall(stack.getName(), NAME_BINDING);
protocolMarshaller.marshall(stack.getDescription(), DESCRIPTION_BINDING);
protocolMarshaller.marshall(stack.getDisplayName(), DISPLAYNAME_BINDING);
protocolMarshaller.marshall(stack.getCreatedTime(), CREATEDTIME_BINDING);
protocolMarshaller.marshall(stack.getStorageConnectors(), STORAGECONNECTORS_BINDING);
protocolMarshaller.marshall(stack.getRedirectURL(), REDIRECTURL_BINDING);
protocolMarshaller.marshall(stack.getFeedbackURL(), FEEDBACKURL_BINDING);
protocolMarshaller.marshall(stack.getStackErrors(), STACKERRORS_BINDING);
protocolMarshaller.marshall(stack.getUserSettings(), USERSETTINGS_BINDING);
protocolMarshaller.marshall(stack.getApplicationSettings(), APPLICATIONSETTINGS_BINDING);
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
}
} } | public class class_name {
public void marshall(Stack stack, ProtocolMarshaller protocolMarshaller) {
if (stack == null) {
throw new SdkClientException("Invalid argument passed to marshall(...)");
}
try {
protocolMarshaller.marshall(stack.getArn(), ARN_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(stack.getName(), NAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(stack.getDescription(), DESCRIPTION_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(stack.getDisplayName(), DISPLAYNAME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(stack.getCreatedTime(), CREATEDTIME_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(stack.getStorageConnectors(), STORAGECONNECTORS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(stack.getRedirectURL(), REDIRECTURL_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(stack.getFeedbackURL(), FEEDBACKURL_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(stack.getStackErrors(), STACKERRORS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(stack.getUserSettings(), USERSETTINGS_BINDING); // depends on control dependency: [try], data = [none]
protocolMarshaller.marshall(stack.getApplicationSettings(), APPLICATIONSETTINGS_BINDING); // depends on control dependency: [try], data = [none]
} catch (Exception e) {
throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
} // depends on control dependency: [catch], data = [none]
} } |
public class class_name {
public java.util.List<String> getSnapshotIds() {
if (snapshotIds == null) {
snapshotIds = new com.amazonaws.internal.SdkInternalList<String>();
}
return snapshotIds;
} } | public class class_name {
public java.util.List<String> getSnapshotIds() {
if (snapshotIds == null) {
snapshotIds = new com.amazonaws.internal.SdkInternalList<String>(); // depends on control dependency: [if], data = [none]
}
return snapshotIds;
} } |
public class class_name {
private void setScriptEngineWrapper(
ScriptNode baseNode,
ScriptEngineWrapper engineWrapper,
ScriptEngineWrapper newEngineWrapper) {
for (@SuppressWarnings("unchecked")
Enumeration<TreeNode> e = baseNode.depthFirstEnumeration(); e.hasMoreElements();) {
ScriptNode node = (ScriptNode) e.nextElement();
if (node.getUserObject() != null && (node.getUserObject() instanceof ScriptWrapper)) {
ScriptWrapper scriptWrapper = (ScriptWrapper) node.getUserObject();
if (hasSameScriptEngine(scriptWrapper, engineWrapper)) {
scriptWrapper.setEngine(newEngineWrapper);
if (newEngineWrapper == null) {
if (scriptWrapper.isEnabled()) {
setEnabled(scriptWrapper, false);
scriptWrapper.setPreviouslyEnabled(true);
}
} else if (scriptWrapper.isPreviouslyEnabled()) {
setEnabled(scriptWrapper, true);
scriptWrapper.setPreviouslyEnabled(false);
}
}
}
}
} } | public class class_name {
private void setScriptEngineWrapper(
ScriptNode baseNode,
ScriptEngineWrapper engineWrapper,
ScriptEngineWrapper newEngineWrapper) {
for (@SuppressWarnings("unchecked")
Enumeration<TreeNode> e = baseNode.depthFirstEnumeration(); e.hasMoreElements();) {
ScriptNode node = (ScriptNode) e.nextElement();
if (node.getUserObject() != null && (node.getUserObject() instanceof ScriptWrapper)) {
ScriptWrapper scriptWrapper = (ScriptWrapper) node.getUserObject();
if (hasSameScriptEngine(scriptWrapper, engineWrapper)) {
scriptWrapper.setEngine(newEngineWrapper);
// depends on control dependency: [if], data = [none]
if (newEngineWrapper == null) {
if (scriptWrapper.isEnabled()) {
setEnabled(scriptWrapper, false);
// depends on control dependency: [if], data = [none]
scriptWrapper.setPreviouslyEnabled(true);
// depends on control dependency: [if], data = [none]
}
} else if (scriptWrapper.isPreviouslyEnabled()) {
setEnabled(scriptWrapper, true);
// depends on control dependency: [if], data = [none]
scriptWrapper.setPreviouslyEnabled(false);
// depends on control dependency: [if], data = [none]
}
}
}
}
} } |
public class class_name {
public SearchNode<O, T> makeNode(Successor successor) throws SearchNotExhaustiveException
{
SearchNode newNode;
try
{
// Create a new instance of this class
newNode = getClass().newInstance();
// Set the state, operation, parent, depth and cost for the new search node
newNode.state = successor.getState();
newNode.parent = this;
newNode.appliedOp = successor.getOperator();
newNode.depth = depth + 1;
newNode.pathCost = pathCost + successor.getCost();
// Check if there is a repeated state filter and copy the reference to it into the new node if so
if (repeatedStateFilter != null)
{
newNode.setRepeatedStateFilter(repeatedStateFilter);
}
return newNode;
}
catch (InstantiationException e)
{
// In practice this should never happen but may if the nodes if some class loader error were to occur whilst
// using a custom node implementation. Rethrow this as a RuntimeException.
throw new IllegalStateException("InstantiationException during creation of new search node.", e);
}
catch (IllegalAccessException e)
{
// In practice this should never happen but may if the nodes to use are not public whilst using a custom node
// implementation. Rethrow this as a RuntimeException.
throw new IllegalStateException("IllegalAccessException during creation of new search node.", e);
}
} } | public class class_name {
public SearchNode<O, T> makeNode(Successor successor) throws SearchNotExhaustiveException
{
SearchNode newNode;
try
{
// Create a new instance of this class
newNode = getClass().newInstance();
// Set the state, operation, parent, depth and cost for the new search node
newNode.state = successor.getState();
newNode.parent = this;
newNode.appliedOp = successor.getOperator();
newNode.depth = depth + 1;
newNode.pathCost = pathCost + successor.getCost();
// Check if there is a repeated state filter and copy the reference to it into the new node if so
if (repeatedStateFilter != null)
{
newNode.setRepeatedStateFilter(repeatedStateFilter); // depends on control dependency: [if], data = [(repeatedStateFilter]
}
return newNode;
}
catch (InstantiationException e)
{
// In practice this should never happen but may if the nodes if some class loader error were to occur whilst
// using a custom node implementation. Rethrow this as a RuntimeException.
throw new IllegalStateException("InstantiationException during creation of new search node.", e);
}
catch (IllegalAccessException e)
{
// In practice this should never happen but may if the nodes to use are not public whilst using a custom node
// implementation. Rethrow this as a RuntimeException.
throw new IllegalStateException("IllegalAccessException during creation of new search node.", e);
}
} } |
public class class_name {
private void addPostParams(final Request request) {
if (expirationDate != null) {
request.addPostParam("ExpirationDate", expirationDate.toString());
}
if (details != null) {
request.addPostParam("Details", details);
}
if (hiddenDetails != null) {
request.addPostParam("HiddenDetails", hiddenDetails);
}
} } | public class class_name {
private void addPostParams(final Request request) {
if (expirationDate != null) {
request.addPostParam("ExpirationDate", expirationDate.toString()); // depends on control dependency: [if], data = [none]
}
if (details != null) {
request.addPostParam("Details", details); // depends on control dependency: [if], data = [none]
}
if (hiddenDetails != null) {
request.addPostParam("HiddenDetails", hiddenDetails); // depends on control dependency: [if], data = [none]
}
} } |
public class class_name {
@GET
@Path("corpora/example-queries/")
@Produces(MediaType.APPLICATION_XML)
public List<ExampleQuery> getExampleQueries(
@QueryParam("corpora") String rawCorpusNames) throws WebApplicationException
{
Subject user = SecurityUtils.getSubject();
try
{
String[] corpusNames;
if (rawCorpusNames != null)
{
corpusNames = rawCorpusNames.split(",");
}
else
{
List<AnnisCorpus> allCorpora = queryDao.listCorpora();
corpusNames = new String[allCorpora.size()];
for (int i = 0; i < corpusNames.length; i++)
{
corpusNames[i] = allCorpora.get(i).getName();
}
}
List<String> allowedCorpora = new ArrayList<>();
// filter by which corpora the user is allowed to access
for (String c : corpusNames)
{
if (user.isPermitted("query:*:" + c))
{
allowedCorpora.add(c);
}
}
List<Long> corpusIDs = queryDao.mapCorpusNamesToIds(allowedCorpora);
return queryDao.getExampleQueries(corpusIDs);
}
catch (Exception ex)
{
log.error("Problem accessing example queries", ex);
throw new WebApplicationException(ex, 500);
}
} } | public class class_name {
@GET
@Path("corpora/example-queries/")
@Produces(MediaType.APPLICATION_XML)
public List<ExampleQuery> getExampleQueries(
@QueryParam("corpora") String rawCorpusNames) throws WebApplicationException
{
Subject user = SecurityUtils.getSubject();
try
{
String[] corpusNames;
if (rawCorpusNames != null)
{
corpusNames = rawCorpusNames.split(","); // depends on control dependency: [if], data = [none]
}
else
{
List<AnnisCorpus> allCorpora = queryDao.listCorpora();
corpusNames = new String[allCorpora.size()]; // depends on control dependency: [if], data = [none]
for (int i = 0; i < corpusNames.length; i++)
{
corpusNames[i] = allCorpora.get(i).getName(); // depends on control dependency: [for], data = [i]
}
}
List<String> allowedCorpora = new ArrayList<>();
// filter by which corpora the user is allowed to access
for (String c : corpusNames)
{
if (user.isPermitted("query:*:" + c))
{
allowedCorpora.add(c); // depends on control dependency: [if], data = [none]
}
}
List<Long> corpusIDs = queryDao.mapCorpusNamesToIds(allowedCorpora);
return queryDao.getExampleQueries(corpusIDs);
}
catch (Exception ex)
{
log.error("Problem accessing example queries", ex);
throw new WebApplicationException(ex, 500);
}
} } |
public class class_name {
public boolean offer(T t, Object identifier) {
checkNotNullArgument(t);
if (isPublisherThread()) {
boolean changed = false;
if (identifier != null) {
final Long id = subscriberIdentifiers.get(identifier);
checkNotNullIdentifier(id);
changed = queues.get(id).offer(t);
} else {
for (Queue<T> queue : queues.values()) {
if (queue.offer(t)) {
changed = true;
}
}
}
return changed;
}
return getCurrentThreadQueue().offer(t);
} } | public class class_name {
public boolean offer(T t, Object identifier) {
checkNotNullArgument(t);
if (isPublisherThread()) {
boolean changed = false;
if (identifier != null) {
final Long id = subscriberIdentifiers.get(identifier);
checkNotNullIdentifier(id); // depends on control dependency: [if], data = [none]
changed = queues.get(id).offer(t); // depends on control dependency: [if], data = [none]
} else {
for (Queue<T> queue : queues.values()) {
if (queue.offer(t)) {
changed = true; // depends on control dependency: [if], data = [none]
}
}
}
return changed; // depends on control dependency: [if], data = [none]
}
return getCurrentThreadQueue().offer(t);
} } |
public class class_name {
public void addNano(long nanos)
{
// convert to microseconds. 1 millionth
latency.update(nanos, TimeUnit.NANOSECONDS);
totalLatency.inc(nanos / 1000);
totalLatencyHistogram.add(nanos / 1000);
recentLatencyHistogram.add(nanos / 1000);
for(LatencyMetrics parent : parents)
{
parent.addNano(nanos);
}
} } | public class class_name {
public void addNano(long nanos)
{
// convert to microseconds. 1 millionth
latency.update(nanos, TimeUnit.NANOSECONDS);
totalLatency.inc(nanos / 1000);
totalLatencyHistogram.add(nanos / 1000);
recentLatencyHistogram.add(nanos / 1000);
for(LatencyMetrics parent : parents)
{
parent.addNano(nanos); // depends on control dependency: [for], data = [parent]
}
} } |
public class class_name {
private synchronized void updateLocal() throws ScheduleManagerException {
final List<Schedule> updates = this.loader.loadUpdatedSchedules();
for (final Schedule s : updates) {
if (s.getStatus().equals(TriggerStatus.EXPIRED.toString())) {
onScheduleExpire(s);
} else {
internalSchedule(s);
}
}
} } | public class class_name {
private synchronized void updateLocal() throws ScheduleManagerException {
final List<Schedule> updates = this.loader.loadUpdatedSchedules();
for (final Schedule s : updates) {
if (s.getStatus().equals(TriggerStatus.EXPIRED.toString())) {
onScheduleExpire(s); // depends on control dependency: [if], data = [none]
} else {
internalSchedule(s); // depends on control dependency: [if], data = [none]
}
}
} } |
public class class_name {
String [] processName (String qName, boolean isAttribute)
{
String name[];
Hashtable table;
// Select the appropriate table.
if (isAttribute) {
if(elementNameTable==null)
elementNameTable=new Hashtable();
table = elementNameTable;
} else {
if(attributeNameTable==null)
attributeNameTable=new Hashtable();
table = attributeNameTable;
}
// Start by looking in the cache, and
// return immediately if the name
// is already known in this content
name = (String[])table.get(qName);
if (name != null) {
return name;
}
// We haven't seen this name in this
// context before.
name = new String[3];
int index = qName.indexOf(':');
// No prefix.
if (index == -1) {
if (isAttribute || defaultNS == null) {
name[0] = "";
} else {
name[0] = defaultNS;
}
name[1] = qName.intern();
name[2] = name[1];
}
// Prefix
else {
String prefix = qName.substring(0, index);
String local = qName.substring(index+1);
String uri;
if ("".equals(prefix)) {
uri = defaultNS;
} else {
uri = (String)prefixTable.get(prefix);
}
if (uri == null) {
return null;
}
name[0] = uri;
name[1] = local.intern();
name[2] = qName.intern();
}
// Save in the cache for future use.
table.put(name[2], name);
tablesDirty = true;
return name;
} } | public class class_name {
String [] processName (String qName, boolean isAttribute)
{
String name[];
Hashtable table;
// Select the appropriate table.
if (isAttribute) {
if(elementNameTable==null)
elementNameTable=new Hashtable();
table = elementNameTable; // depends on control dependency: [if], data = [none]
} else {
if(attributeNameTable==null)
attributeNameTable=new Hashtable();
table = attributeNameTable; // depends on control dependency: [if], data = [none]
}
// Start by looking in the cache, and
// return immediately if the name
// is already known in this content
name = (String[])table.get(qName);
if (name != null) {
return name; // depends on control dependency: [if], data = [none]
}
// We haven't seen this name in this
// context before.
name = new String[3];
int index = qName.indexOf(':');
// No prefix.
if (index == -1) {
if (isAttribute || defaultNS == null) {
name[0] = ""; // depends on control dependency: [if], data = [none]
} else {
name[0] = defaultNS; // depends on control dependency: [if], data = [none]
}
name[1] = qName.intern(); // depends on control dependency: [if], data = [none]
name[2] = name[1]; // depends on control dependency: [if], data = [none]
}
// Prefix
else {
String prefix = qName.substring(0, index);
String local = qName.substring(index+1);
String uri;
if ("".equals(prefix)) {
uri = defaultNS; // depends on control dependency: [if], data = [none]
} else {
uri = (String)prefixTable.get(prefix); // depends on control dependency: [if], data = [none]
}
if (uri == null) {
return null; // depends on control dependency: [if], data = [none]
}
name[0] = uri; // depends on control dependency: [if], data = [none]
name[1] = local.intern(); // depends on control dependency: [if], data = [none]
name[2] = qName.intern(); // depends on control dependency: [if], data = [none]
}
// Save in the cache for future use.
table.put(name[2], name);
tablesDirty = true;
return name;
} } |
public class class_name {
public EEnum getTextOrientationIAxis() {
if (textOrientationIAxisEEnum == null) {
textOrientationIAxisEEnum = (EEnum)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(110);
}
return textOrientationIAxisEEnum;
} } | public class class_name {
public EEnum getTextOrientationIAxis() {
if (textOrientationIAxisEEnum == null) {
textOrientationIAxisEEnum = (EEnum)EPackage.Registry.INSTANCE.getEPackage(AfplibPackage.eNS_URI).getEClassifiers().get(110); // depends on control dependency: [if], data = [none]
}
return textOrientationIAxisEEnum;
} } |
public class class_name {
public static Character toCharacterObject(char ch) {
if (ch < CHAR_ARRAY.length) {
return CHAR_ARRAY[ch];
}
return new Character(ch);
} } | public class class_name {
public static Character toCharacterObject(char ch) {
if (ch < CHAR_ARRAY.length) {
return CHAR_ARRAY[ch]; // depends on control dependency: [if], data = [none]
}
return new Character(ch);
} } |
public class class_name {
public static void percentiles(long[] counts, double[] pcts, double[] results) {
Preconditions.checkArg(counts.length == BUCKET_VALUES.length,
"counts is not the same size as buckets array");
Preconditions.checkArg(pcts.length > 0, "pct array cannot be empty");
Preconditions.checkArg(pcts.length == results.length,
"pcts is not the same size as results array");
long total = 0L;
for (long c : counts) {
total += c;
}
int pctIdx = 0;
long prev = 0;
double prevP = 0.0;
long prevB = 0;
for (int i = 0; i < BUCKET_VALUES.length; ++i) {
long next = prev + counts[i];
double nextP = 100.0 * next / total;
long nextB = BUCKET_VALUES[i];
while (pctIdx < pcts.length && nextP >= pcts[pctIdx]) {
double f = (pcts[pctIdx] - prevP) / (nextP - prevP);
results[pctIdx] = f * (nextB - prevB) + prevB;
++pctIdx;
}
if (pctIdx >= pcts.length) break;
prev = next;
prevP = nextP;
prevB = nextB;
}
double nextP = 100.0;
long nextB = Long.MAX_VALUE;
while (pctIdx < pcts.length) {
double f = (pcts[pctIdx] - prevP) / (nextP - prevP);
results[pctIdx] = f * (nextB - prevB) + prevB;
++pctIdx;
}
} } | public class class_name {
public static void percentiles(long[] counts, double[] pcts, double[] results) {
Preconditions.checkArg(counts.length == BUCKET_VALUES.length,
"counts is not the same size as buckets array");
Preconditions.checkArg(pcts.length > 0, "pct array cannot be empty");
Preconditions.checkArg(pcts.length == results.length,
"pcts is not the same size as results array");
long total = 0L;
for (long c : counts) {
total += c; // depends on control dependency: [for], data = [c]
}
int pctIdx = 0;
long prev = 0;
double prevP = 0.0;
long prevB = 0;
for (int i = 0; i < BUCKET_VALUES.length; ++i) {
long next = prev + counts[i];
double nextP = 100.0 * next / total;
long nextB = BUCKET_VALUES[i];
while (pctIdx < pcts.length && nextP >= pcts[pctIdx]) {
double f = (pcts[pctIdx] - prevP) / (nextP - prevP);
results[pctIdx] = f * (nextB - prevB) + prevB; // depends on control dependency: [while], data = [none]
++pctIdx; // depends on control dependency: [while], data = [none]
}
if (pctIdx >= pcts.length) break;
prev = next; // depends on control dependency: [for], data = [none]
prevP = nextP; // depends on control dependency: [for], data = [none]
prevB = nextB; // depends on control dependency: [for], data = [none]
}
double nextP = 100.0;
long nextB = Long.MAX_VALUE;
while (pctIdx < pcts.length) {
double f = (pcts[pctIdx] - prevP) / (nextP - prevP);
results[pctIdx] = f * (nextB - prevB) + prevB; // depends on control dependency: [while], data = [none]
++pctIdx; // depends on control dependency: [while], data = [none]
}
} } |
public class class_name {
public String lookupNamespace(final String prefix) {
Object namespace = namespaceMap.get(prefix);
if (namespace != null) {
return namespace.toString();
}
return this.namespaceTagHints.isEmpty() ? prefix : this.namespaceTagHints.get(prefix);
} } | public class class_name {
public String lookupNamespace(final String prefix) {
Object namespace = namespaceMap.get(prefix);
if (namespace != null) {
return namespace.toString(); // depends on control dependency: [if], data = [none]
}
return this.namespaceTagHints.isEmpty() ? prefix : this.namespaceTagHints.get(prefix);
} } |
public class class_name {
@Override
public IPromise<T> awaitPromise(long timeout) {
long endtime = 0;
if ( timeout > 0 ) {
endtime = System.currentTimeMillis() + timeout;
}
if ( Thread.currentThread() instanceof DispatcherThread ) {
DispatcherThread dt = (DispatcherThread) Thread.currentThread();
Scheduler scheduler = dt.getScheduler();
int idleCount = 0;
dt.__stack.add(this);
while( ! isSettled() ) {
if ( ! dt.pollQs() ) {
idleCount++;
scheduler.pollDelay(idleCount);
} else {
idleCount = 0;
}
if ( endtime != 0 && System.currentTimeMillis() > endtime && ! isSettled() ) {
timedOut(Timeout.INSTANCE);
break;
}
}
dt.__stack.remove(dt.__stack.size()-1);
return this;
} else {
// if outside of actor machinery, just block
CountDownLatch latch = new CountDownLatch(1);
then( (res, err) -> {
latch.countDown();
});
boolean timedOut = false;
try {
timedOut = ! latch.await(timeout, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
if ( timedOut )
timedOut(Timeout.INSTANCE);
return this;
}
} } | public class class_name {
@Override
public IPromise<T> awaitPromise(long timeout) {
long endtime = 0;
if ( timeout > 0 ) {
endtime = System.currentTimeMillis() + timeout; // depends on control dependency: [if], data = [none]
}
if ( Thread.currentThread() instanceof DispatcherThread ) {
DispatcherThread dt = (DispatcherThread) Thread.currentThread();
Scheduler scheduler = dt.getScheduler();
int idleCount = 0;
dt.__stack.add(this); // depends on control dependency: [if], data = [none]
while( ! isSettled() ) {
if ( ! dt.pollQs() ) {
idleCount++; // depends on control dependency: [if], data = [none]
scheduler.pollDelay(idleCount); // depends on control dependency: [if], data = [none]
} else {
idleCount = 0; // depends on control dependency: [if], data = [none]
}
if ( endtime != 0 && System.currentTimeMillis() > endtime && ! isSettled() ) {
timedOut(Timeout.INSTANCE); // depends on control dependency: [if], data = [none]
break;
}
}
dt.__stack.remove(dt.__stack.size()-1); // depends on control dependency: [if], data = [none]
return this; // depends on control dependency: [if], data = [none]
} else {
// if outside of actor machinery, just block
CountDownLatch latch = new CountDownLatch(1);
then( (res, err) -> {
latch.countDown(); // depends on control dependency: [if], data = [none]
});
boolean timedOut = false;
try {
timedOut = ! latch.await(timeout, TimeUnit.MILLISECONDS); // depends on control dependency: [try], data = [none]
} catch (InterruptedException e) {
e.printStackTrace();
} // depends on control dependency: [catch], data = [none]
if ( timedOut )
timedOut(Timeout.INSTANCE);
return this;
}
} } |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.